Thursday, February 28, 2019

time - How to convert Milliseconds to "X mins, x seconds" in Java?




I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.



What's the best way to do this?


Answer



Use the java.util.concurrent.TimeUnit class:



String.format("%d min, %d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);


Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.



To add a leading zero for values 0-9, just do:



String.format("%02d min, %02d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),

TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);


If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:



int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);

//etc...

JavaScript Expression




Can anyone help me with this JavaScript expression?




+[[+!![]]+[+![]]+[+!![]]+[-~!![]+-~!![]-~!![]]+[-~!![]]+[+![]]+[+!![]]+[-~!![]+-~!![]]]


A friend sent it to me and asked me to copy and paste it in the browser console.



This is the result:



10162014




If anyone could explain this to me or at least point me to right references please. Thanks!


Answer



First break out your code to this: !![] which returns true (!! is to convert to boolean) and now + converts to number so +!![] returns 1.



![] converts to false so +![] returns 0.



~[] returns -1 and ~![] also returns -1.



~!![] returns -2.




Now, -~!![] returns 2 and -~![] returns 1.



So, combining them all returns 10162014.



All about you to know is ~, !, +, & -


java - Proper use cases for Android UserManager.isUserAGoat()?




I was looking at the new APIs introduced in Android 4.2.
While looking at the UserManager class I came across the following method:





public boolean isUserAGoat()


Used to determine whether the user making this call is subject to teleportations.



Returns whether the user making this call is a goat.




How and when should this be used?



Answer



From their source, the method used to return false until it was changed in API 21.



/**
* Used to determine whether the user making this call is subject to
* teleportations.
* @return whether the user making this call is a goat
*/
public boolean isUserAGoat() {
return false;

}


It looks like the method has no real use for us as developers. Someone has previously stated that it might be an Easter egg.



In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator



/**
* Used to determine whether the user making this call is subject to
* teleportations.

*
*

As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
* now automatically identify goats using advanced goat recognition technology.


*
* @return Returns true if the user making this call is a goat.
*/
public boolean isUserAGoat() {
return mContext.getPackageManager()
.isPackageAvailable("com.coffeestainstudios.goatsimulator");
}



Here is the source and the change.


asynchronous - Javascript Promise and Async code



I'm struggling to wrap my head around the concept of async and promises in js. I can't figure out why the code below doesn't print anything on my console.




I'm assuming it's because the code inside my Promise is not asynchronous, but isn't that the point of a promise: to make something synchronous become asynchronous?



If that's not the case, how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?



function countdown(seconds) {
return new Promise(function(resolve, reject) {
for (let i = seconds; i >= 0; i--) {
if (i > 0) console.log(i + '...');
else resolve(console.log("GO!"));
}

}
};
count = countdown(5).then(() => console.log('Completed'), (err) => console.log(err.message));

Answer




how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?




By it's nature, javascript code is synchronous (waits for howls of protest to abate) ...




Every (non-native) function that is asynchronous is due to that function, either




  1. directly calling one of those native asynchronous functions, or

  2. calling other functions that call functions etc that eventually call one of these asynchronous functions directly



the only way to transform some code from synchronous to asynchronous is to use one of the many "native" functions that are asynchronous in nature (again, either directly, or indirectly via other functions that eventually will have to call one of these asynchronous functions directly)


css - Why is a monospace font set to 80em taking up less than 80 columns of text?



I'm trying to make some text on a webpage look like a page from Gopherspace. In other words, monospace font with a maximum of 80 columns. I figured that if the font is monospace and I set the width of the containing element to 80em, that would constrain it to a perfect 80 columns since every character should be the same width in a monospace font.




The colors I've added are just to make it easier to tell where line breaks occur.



In case this works on some browsers/computers and not others, here's what I see on my computer, which is running Firefox 65.0.1 on Mac OS 10.14.3.



longer than 80 columns



Why is this div almost twice the size of 80 columns of text and how can I fix it?






.plaintext {
background-color: black;
font-family: monospace;
width: 80em;
font-size: 10px;
border: 2px solid red;
overflow-wrap: break-word;
}


.r { color: red; }
.o { color: orange; }
.y { color: yellow; }
.g { color: green; }
.b { color: blue; }
.i { color: indigo; }
.v { color: violet; }


01234567890123456789012345678901234567890123456789012345678901234567890123456789





Answer



The font size of a element (measured in em) is the height of the font, not the width.
(Originally, the word "em" refers to the width of the M, but not many fonts have an M exactly the width of 1em any more.)



The solution is to use ch as a unit for the width. In monospace fonts, 1ch is the width of a character. In variable-width fonts, 1ch is the width of the 0 (zero) character.
See the official definition at the W3C or the more readable MDN version.






.plaintext {
background-color: black;
font-family: monospace;
width: 80ch; /* changed */
font-size: 10px;
border: 2px solid red;
overflow-wrap: break-word;
}

.r { color: red; }

.o { color: orange; }
.y { color: yellow; }
.g { color: green; }
.b { color: blue; }
.i { color: indigo; }
.v { color: violet; }


01234567890123456789012345678901234567890123456789012345678901234567890123456789





android - Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?



I found the following function in package android.app.ActivityManager.



public static boolean isUserAMonkey ()


The reference describes:





public static boolean isUserAMonkey () Since: API Level 8



Returns "true" if the user interface is currently being messed with by a monkey.




I was shocked by this strange function. And have a few questions.




  • What does this (user interface is currently being messed with by a

    monkey) mean?


  • What is the practical use of this function?


  • Why do they use isUserAMonkey for the function name?



Answer



This method is for checking whether the current user is a test user by some automatic testing, called 'monkey' by Android devs.


regex - Javascript to find number after character (colon)





I've looked at other answers to this question, as there have been similar ones before, but I just can't get it work. I'm new to javascript, so please be kind.



From the body of an email, I need to find a phrase that will end with "number:" followed by a number.



e.g. Sample Email Body:



...  
customer reference number: 123456
or
site reference number : 827893

...


then that reference number '123456' or whatever it is, needs to be a variable/value I'll use elsewhere.



I don't want anything before the number, and I don't want anything after the number (eg. the next lines).



Tried this:



var str  = "reference number: 1234";

var RefStr = str.match(/number\:\s+(\d+)$/i)


But it returns number: 1234.



I think regex is not the best solution for me.





Edit, I couldn't respond to my own question, and comments don't let me format nicely.






Thanks, even though this worked in a regex checker, trying to use it in the context of the database, didn't work. I'm still working on that.



var str  = email.body_text;
var refStr = str.match((/number\:\s+(\d+)$/i)[1]);
externalReferenceNumberCreate(current.sys_id, 'Client reference number',refStr,'Ref number');



I know line 1 and 3 are correct, so perhaps I've messed the syntax for line 2? As



I understand that this is probably a product specific query, and perhaps more complicated than I thought.


Answer



Alex already gave you the answer: str.match(/number\:\s+(\d+)$/i)[1], which means the result at the index of 1. That index in the array is generated by the usage of the () in your regex. The first index (0) is the answer you've been getting.


Why can I type alias functions and use them without casting?



In Go, if you define a new type e.g.:



type MyInt int



You can't then pass a MyInt to a function expecting an int, or vice versa:



func test(i MyInt) {
//do something with i
}

func main() {
anInt := 0
test(anInt) //doesn't work, int is not of type MyInt
}



Fine. But why is it then that the same does not apply to functions? e.g.:



type MyFunc func(i int)
func (m MyFunc) Run(i int) {
m(i)
}

func run(f MyFunc, i int) {

f.Run(i)
}

func main() {
var newfunc func(int) //explicit declaration
newfunc = func(i int) {
fmt.Println(i)
}
run(newfunc, 10) //works just fine, even though types seem to differ
}



Now, I'm not complaining because it saves me having to explicitly cast newfunc to type MyFunc, as I would have to do in the first example; it just seems inconsistent. I'm sure there is a good reason for it; can anyone enlighten me?



The reason I ask is mainly because I would like to shorten some of my rather long function types in this way, but I want to make sure it's expected and acceptable to do this :)


Answer



Turns out, this is a misunderstanding that I had about how Go dealt with types, which can be resolved by reading the relevant part of the spec:



http://golang.org/ref/spec#Type_identity




The relevant distinction that I was unaware of was that of named and unnamed types.



Named types are types with a name, such as int, int64, float, string, bool. In addition, any type you create using 'type' is a named type.



Unnamed types are those such as []string, map[string]string, [4]int. They have no name, simply a description corresponding to how they are to be structured.



If you compare two named types, the names must match in order for them to be interchangeable. If you compare a named and an unnamed type, then as long as the underlying representation matches, you're good to go!



e.g. given the following types:




type MyInt int
type MyMap map[int]int
type MySlice []int
type MyFunc func(int)


the following is invalid:



var i int = 2
var i2 MyInt = 4

i = i2 //both named (int and MyInt) and names don't match, so invalid


the following is fine:



is := make([]int)
m := make(map[int]int)
f := func(i int){}

//OK: comparing named and unnamed type, and underlying representation

//is the same:
func doSlice(input MySlice){...}
doSlice(is)

func doMap(input MyMap){...}
doMap(m)

func doFunc(input MyFunc){...}
doFunc(f)



I'm a bit gutted I didn't know that sooner, so I hope that clarifies the type lark a little for someone else! And means much less casting than I at first thought :)


ajax - CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true



I have a setup involving




Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000)



Browser <-- webapp <-- Node.js (Serve the app)



Browser (webapp) --> Ajax --> Django(Serve ajax POST requests)



Now, my problem here is with CORS setup which the webapp uses to make Ajax calls to the backend server. In chrome, I keep getting





Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.




doesn't work on firefox either.



My Node.js setup is:



var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
res.header('Access-Control-Allow-Credentials', true);

res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
};


And in Django I'm using this middleware along with this



The webapp makes requests as such:




$.ajax({
type: "POST",
url: 'http://localhost:8000/blah',
data: {},
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: 'json',
success: successHandler

});


So, the request headers that the webapp sends looks like:



Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json
Accept: */*

Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"


And here's the response header:



Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *

Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json


Where am I going wrong?!



Edit 1: I've been using chrome --disable-web-security, but now want things to actually work.



Edit 2: Answer:




So, solution for me django-cors-headers config:



CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)

Answer



This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :





  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols

  2. Cross Origin Resource Sharing with Credentials



Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.


function - How am getting this output ? Javascript ES6





Please find my snippet here,



for (var i=0;i<11;i++) {
setTimeout( () => console.log(i), 10);
}






How it print 11 for 11 times? since i was set < 11?



if i console it without function it print 1-10 .



for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}


this gives me 1-10. i am wonder how its getting changed if i include function without condition?



Answer



Root case for:



for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}


that console.log will be triggered directly (without any delay), so it should be:




for (var i=0;i<11;i++) {
setTimeout(function () { console.log(i); }, 10);
}


that will give directly the same result as for ES6



Right way will be by using closures:






for (var i=0;i<11;i++) {
((i) => {
setTimeout(() => console.log(i), 10);
})(i);
}






The reason for that that we have a single-threaded model in JavaScript. So, all setTimeout will be executed after for-cycle.



In addition it can be used let:



for (let i=1; i<=11; i++) {
setTimeout(() => console.log(i), 10);
}

multithreading - What so different about Node.js's event-driven? Can't we do that in ASP.Net's HttpAsyncHandler?



I'm not very experienced in web programming,
and I haven't actually coded anything in Node.js yet, just curious about the event-driven approach. It does seems good.



The article explains some bad things that could happen when we use a thread-based approach to handle requests, and should opt for a event-driven approach instead.
In thread-based, the cashier/thread is stuck with us until our food/resource is ready. While in event-driven, the cashier send us somewhere out of the request queue so we don't block other requests while waiting for our food.
To scale the blocking thread-based, you need to increase the number of threads.
To me this seems like a bad excuse for not using threads/threadpools properly.




Couldn't that be properly handled using IHttpAsyncHandler?
ASP.Net receives a request, uses the ThreadPool and runs the handler (BeginProcessRequest), and then inside it we load the file/database with a callback. That Thread should then be free to handle other requests. Once the file-reading is done, the ThreadPool is called into action again and executes the remaining response.
Not so different for me, so why is that not as scalable?



One of the disadvantages of the thread-based that I do know is, using threads needs more memory. But only with these, you can enjoy the benefits of multiple cores. I doubt Node.js is not using any threads/cores at all.



So, based on just the event-driven vs thread-based (don't bring the "because it's Javascript and every browser..." argument), can someone point me out what is the actual benefit of using Node.js instead of the existing technology?



That was a long question. Thanks :)


Answer




First of all, Node.js is not multi-threaded. This is important. You have to be a very talented programmer to design programs that work perfectly in a threaded environment. Threads are just hard.



You have to be a god to maintain a threaded project where it wasn't designed properly. There are just so many problems that can be hard to avoid in very large projects.



Secondly, the whole platform was designed to be run asynchronously. Have you see any ASP.NET project where every single IO interaction was asynchronous? simply put, ASP.NET was not designed to be event-driven.



Then, there's the memory footprint due to the fact that we have one thread per open-connection and the whole scaling issue. Correct me if I'm wrong but I don't know how you would avoid creating a new thread for each connection in ASP.NET.



Another issue is that a Node.js request is idle when it's not being used or when it's waiting for IO. On the other hand, a C# thread sleeps. Now, there is a limit to the number of these threads that can sleep. In Node.js, you can easily handle 10k clients at the same time in parallel on one development machine. You try handling 10k threads in parallel on one development machine.




JavaScript itself as a language makes asynchronous coding easier. If you're still in C# 2.0, then the asynchronous syntax is a real pain. A lot of developers will simply get confused if you're defining Action<> and Function<> all over the place and using callbacks. An ASP.NET project written in an evented way is just not maintainable by an average ASP.NET developer.



As for threads and cores. Node.js is single-threaded and scales by creating multiple-node processes. If you have a 16 core then you run 16 instances of your node.js server and have a single Node.js load balancer in front of it. (Maybe a nginx load balancer if you want).



This was all written into the platform at a very low-level right from the beginning. This was not some functionality bolted on later down the line.



Other advantages



Node.js has a lot more to it then above. Above is only why Node.js' way of handling the event loop is better than doing it with asynchronous capabilities in ASP.NET.





  • Performance. It's fast. Real fast.

  • One big advantage of Node.js is its low-level API. You have a lot of control.

  • You have the entire HTTP server integrated directly into your code then outsourced to IIS.

  • You have the entire nginx vs Apache comparison.

  • The entire C10K challenge is handled well by node but not by IIS

  • AJAX and JSON communication feels natural and easy.

  • Real-time communication is one of the great things about Node.js. It was made for it.

  • Plays nicely with document-based nosql databases.

  • Can run a TCP server as well. Can do file-writing access, can run any unix console command on the server.


  • You query your database in javascript using, for example, CouchDB and map/reduce. You write your client in JavaScript. There are no context switches whilst developing on your web stack.

  • Rich set of community-driven open-source modules. Everything in node.js is open source.

  • Small footprint and almost no dependencies. You can build the node.js source yourself.



Disadvantages of Node.js



It's hard. It's young. As a skilled JavaScript developer, I face difficulty writing a website with Node.js just because of its low-level nature and the level of control I have. It feels just like C. A lot of flexibility and power either to be used for me or to hang me.



The API is not frozen. It's changing rapidly. I can imagine having to rewrite a large website completely in 5 years because of the amount Node.js will be changed by then. It is do-able, you just have to be aware that maintenance on node.js websites is not cheap.




further reading



http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/



http://blip.tv/file/2899135



http://nodeguide.com/


php - Parse error: syntax error, unexpected 'endif' (T_ENDIF)?



I getting error with php endif, couldn't find the error. here I have given my code. please help me to fix this



       
$video_banner = get_sub_field('video-banner');

?>




Answer



Wrong syntax there :







To be replaced by






writting a ; after the condition of a if is like writting




    if( $video_banner )
{
; //Do nothing
}
?>


This means you have one endif; in excess



javascript - Assign default text to select menu d3

I have a select menu that updates a graph .on('change') using d3.



I am trying to get the select menu to have a default text value 'Select from me'.




But when the .on('change') is triggered I don't want this value to update the graph. The way I have it now when you choose to select the default text 'Select from me' it tries to update the graph based on this value.



So is there a way to disable this from acting as an option?



D3 CODE



var select = d3.select('#select').append('select');

select.append('option').text('Select from me');


select.attr( 'id', 'select-menu' )
.on( 'change', updateGraph )
.selectAll( 'option' )
.data( dataNest )
.enter().append( 'option' )
.attr( 'value', function (d) {return d.key; } )
.text( function (d) { return d.key; } );

c++ - Crash on reading file on seekg()



I am trying to read a bmp file into a character buffer and transfer it across processes using inter process communication. I accomplished this using following code:



     std::ifstream ImageFile;
char* str=new char[strlen(pFilePath)+strlen(pFileName)+1];
strcpy(str,pFilePath);
strcat(str,pFileName);
ImageFile.open(str, ios::binary);

if(ImageFile.is_open()){
ImageFile.seekg(0,ios::end);
m_uiImageSize = ImageFile.tellg();
ImageFile.seekg(0,ios::beg);

m_pcImageBuffer = new char[m_uiImageSize];
ImageFile.read(m_pcImageBuffer,m_uiImageSize);
ImageFile.close();
}


WebCore::FloatRect rect;
BITMAP cBitmap;
HBITMAP hBitmap;
tagBITMAPFILEHEADER bfh = *(tagBITMAPFILEHEADER*)m_pcImageBuffer;
tagBITMAPINFOHEADER bih = *(tagBITMAPINFOHEADER*)(m_pcImageBuffer+sizeof(tagBITMAPFILEHEADER));
RGBQUAD rgb = *(RGBQUAD*)(m_pcImageBuffer+sizeof(tagBITMAPFILEHEADER)+sizeof(tagBITMAPINFOHEADER));

BITMAPINFO bi;
bi.bmiColors[0] = rgb;
bi.bmiHeader = bih;


char* pPixels = (m_pcImageBuffer+bfh.bfOffBits);
char* ppvBits;
hBitmap = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**) &ppvBits, NULL, 0);
SetDIBits(NULL, hBitmap, 0, bih.biHeight, pPixels, &bi, DIB_RGB_COLORS);
GetObject(hBitmap, sizeof(BITMAP), &cBitmap);


This was working perfectly for me before. But now my program crashes at ImageFile.seekg(0,ios::end) and I cant figure out why. The file opens fine and even the ifstream::good() returns true. Following is my call stack:





StorageTree.exe!std::use_facet >(const std::locale & _Loc) Line 586 C++
msvcp110d.dll!std::basic_istream >::_Sentry_base::_Sentry_base(std::basic_istream > & _Istr) Line 103 C++
msvcp110d.dll!std::basic_istream >::sentry::sentry(std::basic_istream > & _Istr, bool _Noskip) Line 123 C++
msvcp110d.dll!std::basic_istream >::seekg(__int64 _Off, int _Way) Line 876 C++


Pls guide me in the right direction.


Answer



Found the solution to my problem. There wasn't any problem in the code, I had added some more code to the app and hadn't initialised some of my variables thus affecting the entry points and data locations.



Wednesday, February 27, 2019

c++ - What is move semantics?




I just finished listening to the Software Engineering radio podcast interview with Scott Meyers regarding C++0x. Most of the new features made sense to me, and I am actually excited about C++0x now, with the exception of one. I still don't get move semantics... What is it exactly?


Answer



I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:



#include 
#include

class string
{

char* data;

public:

string(const char* p)
{
size_t size = std::strlen(p) + 1;
data = new char[size];
std::memcpy(data, p, size);
}



Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:



    ~string()
{
delete[] data;
}

string(const string& that)

{
size_t size = std::strlen(that.data) + 1;
data = new char[size];
std::memcpy(data, that.data, size);
}


The copy constructor defines what it means to copy string objects. The parameter const string& that binds to all expressions of type string which allows you to make copies in the following examples:



string a(x);                                    // Line 1

string b(x + y); // Line 2
string c(some_function_returning_a_string()); // Line 3


Now comes the key insight into move semantics. Note that only in the first line where we copy x is this deep copy really necessary, because we might want to inspect x later and would be very surprised if x had changed somehow. Did you notice how I just said x three times (four times if you include this sentence) and meant the exact same object every time? We call expressions such as x "lvalues".



The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time.
rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of b and c, we could do whatever we wanted with the source string, and the client couldn't tell a difference!



C++0x introduces a new mechanism called "rvalue reference" which, among other things,

allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:



    string(string&& that)   // string&& is an rvalue reference to a string
{
data = that.data;
that.data = nullptr;
}


What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.




Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.



    string& operator=(string that)
{
std::swap(data, that.data);
return *this;
}
};



Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)



Note that we pass the parameter that by value, so that has to be initialized just like any other string object. Exactly how is that going to be initialized? In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.



So if you say a = b, the copy constructor will initialize that (because the expression b is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.



But if you say a = x + y, the move constructor will initialize that (because the expression x + y is an rvalue), so there is no deep copy involved, only an efficient move.
that is still an independent object from the argument, but its construction was trivial,
since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because x + y is an rvalue, and again, it is okay to move from string objects denoted by rvalues.




To summarize, the copy constructor makes a deep copy, because the source must remain untouched.
The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.



I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see my supplementary answer.


Check if a variable is a string in JavaScript



How can I determine whether a variable is a string or something else in JavaScript?


Answer



You can use typeof operator:




var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"



Example from this webpage. (Example was slightly modified though).



This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.







  1. The Google JavaScript Style Guide says to never use primitive object wrappers.

  2. Douglas Crockford recommended that primitive object wrappers be deprecated.



awk - git commit trigger to block byte order mark



I'm on Windows and sometimes edit files with Notepad, which likes to put a BOM at the start of the file (EF BB BF). It's easy overlook this in the diff and commit to Git a Python file with such a BOM, which I've found will not work on Mac.



I want to create a commit trigger that removes the BOM before committing. Or at least rejects the commit.



The best I've come up with is the script below which I put in 'pre-commit'. It removes any BOM but only after the commit, so then I have to make a second commit.



#!/bin/sh

git diff --cached --diff-filter=ACMR --name-only -z *.py | xargs -0 -n 1 sh -c '
for FILE; do
sed -b -i -e "1s/^\xEF\xBB\xBF//" "$FILE"
done
' sh


I tried to use commands and 'q' like this so the exit code would be 1 if it matched, but it doesn't work.



#!/bin/sh

git diff --cached --diff-filter=ACMR --name-only -z *.py | xargs -0 -n 1 sh -c '
for FILE; do
sed -b -i -e "1 /^\xEF\xBB\xBF/ {s/^\xEF\xBB\xBF//;q1};q0" "$FILE"
done
' sh


Can someone help fix it?


Answer



You're on the right track.




A good general rule for a pre-commit hook is not to modify the index contents (i.e., "don't change the commit or work dir, nor even try") but rather just to fail the commit, so your second block of code is probably closer—but you're still modifying the files. You can do this if you want, and you can even git add them as well if you really want. It's just generally not a great idea: it tends to be too surprising, and it does unexpected things with carefully staged versions that deliberately differ from the work-directory versions (as produced by git add -p for instance).



You also have two options here: you could inspect only new and modified files (which is what your --diff-filter is for); or you could inspect every file in the index. If you'd like to allow any existing (but unmodified) file to retain an existing Unicode-BOM you definitely want the new-and-modified-only method, so let's stick with that. I'll retain the *.py as well, but we want to protect it from the shell so that it uses git's idea of files whose name ends with .py, not the shell's. In particular, that means that if some .py files exist in the index—and will therefore be committed, if the commit proceeds—but are not in the work directory, they will get checked.



We can simplify the diff filter a bit, by adding --no-renames to the diff command so that R status cannot occur. We also know that C should not occur since we did not supply any -C or --find-copies-harder options. Thus, we start with:



git diff --cached --no-renames --diff-filter=AM --name-only -- '*.py'



I've taken out the -z: -z is good if we can use xargs -0, but I'm planning to read the file names one at a time instead, since most of these commands really only work on one file at a time. (It's possible to do that with xargs too, but if none of your file names contains a newline, we'll be OK without it.) The -- separates diff options from paths (this seems like it should not be required, but see comments below; and it's generally a good idea anyway).



This produces a list of files to be inspected, so now let's inspect (but not edit) them. If you're on Windows, you may need to modify the below to use whatever limited tools you have; since I'm always on a Linux or Unix box I use head -1 to get the first line, and grep to check for the BOM:



#! /bin/sh
git diff --cached --no-renames --diff-filter=AM --name-only -- '*.py' |
(status=0; while IFS= read path; do
if git show ":$path" | head -1 | grep $'^\xEF\xBB\xBF' >/dev/null; then
echo "Error: file '$path' starts with Unicode BOM.'"
status=1

fi
done
exit $status)


Here are the various tricks:




  • We set IFS to nothing during the read, to allow other kinds of white space. (For methods that work with -z, and hence handle newlines too, see Etan Reisner's comments below.)

  • We use git show ":$path" to extract the version of the file that's in the index. This may (as with git add -p, for instance) differ from the version of the file in the work-directory.


  • We use head -1 to discard all but the first line.

  • We use grep to check for the BOM, which we make with a shell string expansion ($'...'), with grep's output directed to /dev/null so that it doesn't show up (grep -q also works but only if that particular grep supports -q).

  • We go on to check all listed files, even if some have a BOM.

  • To work around the shell's subshell-action with pipes (cmd | while ... runs the while in a sub-shell), we set the status in an explicit (parenthesized) sub-shell and exit that sub-shell with that status. That propagates the sub-shell's status—success if no BOMs, failure if some—up to the main shell, where it can become the result of the git hook.



Note: the above is not tested as a complete hook (though I believe it's correct).


c# - Why same values differ with float and double




Consider this program



float a = 0.7f;


if (a < 0.7)
{
Console.WriteLine("Less");
}


The output is Less. Why??


Answer



Because 0.7 does not have an exact representation as a float or a double: it is not an exact sum of negative powers of 2.




It happens that the closest representation of 0.7 as a is float approximately 0.69999998807907104492, while the closest double representation is 0.69999999999999995559. As you can see, double is slightly greater, which explains the behavior of your program.



Here is a small demo that you could run to see the values on your system:



printf("%20.20f %20.20f\n", 0.7, (float)0.7);


(live demo on ideone).




The takeaway lesson here is that you should not expect double and float representations of mathematically equal numbers to compare for equality correctly. Only a small subset of fractional numbers are representable in floating point system as exact numbers.



Since the overwhelming majority of fractions would be approximated, it is a good idea to do the comparisons with some level of tolerance. For example, instead of writing if (a == 0.7) you should write if (abs(a - 0.7) < 1E-8)


javascript - Why is document.GetElementById returning null

I've been using document.GetElementById succesfully but from some time on I can't make it work again.
Old pages in which I used it still work but things as simple as this:





no title








Are giving me "document.getElementById("parsedOutput") is null" all the time now.
It doesnt matter if I use Firefox or Chrome or which extensions i have enabled or what headers I use for the html, it's always null and I can't find what could be wrong.



Thanks for your input =)

How to check if a column exists in a SQL Server table?




I need to add a specific column if it does not exist. I have something like the following, but it always returns false:



IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')


How can I check if a column exists in a table of the SQL Server database?



Answer



SQL Server 2005 onwards:



IF EXISTS(SELECT 1 FROM sys.columns 
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END



Martin Smith's version is shorter:



IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END

php - Why is if(empty(strlen(trim($_POST['name'])))) invalid?




I have a if statement check to see if a string is empty




if(empty(strlen(trim($_POST['name'])))){
$error_empty = true;
}


gives me this error:




Fatal error: Can't use function return value in write context in C:\xampp\htdocs\requestaccess\index.php on line 51




Answer



empty is not a function -- it's a "language construct" that prior to PHP 5.5 can only be used to evaluate variables, not the results of arbitrary expressions.



If you wanted to use empty in exactly this manner (which is meaningless) you would have to store the result in an intermediate variable:



$var = strlen(trim($_POST['name']));
if(empty($var)) ...


But you don't need to do anything like this: strlen will always return an integer, so empty will effectively be reduced to checking for zero. You don't need empty for that; zero converts to boolean false automatically, so a saner option is




if(!strlen(trim($_POST['name']))) ...


or the equivalent



if(trim($_POST['name']) === '') ...

javascript - Enable CORS in fetch api

I am getting the following error message that unable me to continue




Failed to load https://site/data.json: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'

header is present on the requested resource. Origin
'http://localhost:8080' is therefore not allowed access. If an opaque
response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
localhost/:1 Uncaught (in promise) TypeError: Failed to fetch




I am trying to enable CORS in my react js file but I was not able to get the expected result. I have installed a chrome extension and it work. But to use this in production site, I need to enable it inside my code. How should I properly arrange the code to enable the CORS.



fetch(URL, {

mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
})
.then(response => response.json())
.then(data => {

javascript - Set a minimum value for randomly generated numbers




I am using this function to generate and alternate random values inside a div






var change_price = $('#myprice');
animationTimer = setInterval(function() {
change_price.text( ''+ Math.floor(Math.random() * 100) );
}, 1000);

#myprice {
padding: 20px;
font-size:24px;
color: green;
}



50





What I want to do is to control the min value too.
For example, to have random generated values from 50 to 100.
Not starting from zero(0) as other posts do


Answer



As mentioned in mozilla developer you can generate random number between max and min as shown in bottom




Math.floor(Math.random() * (max - min + 1)) + min;


So your code should changed to





var change_price = $('#myprice');
animationTimer = setInterval(function() {

change_price.text(Math.floor(Math.random() * (100-50+1)) + 50);
}, 100);

#myprice {
padding: 20px;
font-size:24px;
color: green;
}


50





plot explanation - Taken - "I can tell you I don't have money" - Movies & TV

I'm watching Taken (2008) again, and I'm at the infamous "particular set of skills" speech. I just realized he says "...I can tell you I don't have money...".



His wife's new husband is portrayed as an obvious millionaire and this guy just blew the chance that he could get his daughter back by offering them the husband's money.



Can anyone think of any sort of logic or reasoning behind this?

regex - awk extract multiple groups from each line



How do I perform action on all matching groups when the pattern matches multiple times in a line?



To illustrate, I want to search for /Hello! (\d+)/ and use the numbers, for example, print them out or sum them, so for input



abcHello! 200 300 Hello! Hello! 400z3
ads

Hello! 0


If I decided to print them out, I'd expect the output of



200
400
0

Answer




This is a simple syntax, and every awk (nawk, mawk, gawk, etc) can use this.



{
while (match($0, /Hello! [0-9]+/)) {
pattern = substr($0, RSTART, RLENGTH);
sub(/Hello! /, "", pattern);
print pattern;
$0 = substr($0, RSTART + RLENGTH);
}
}


Tuesday, February 26, 2019

c++ - Return the enumeration instead of the index

I have a simple class that uses an enum for "status". When I use the getStatus member function, it does indeed return "Busy" but when I print the value, it shows a "1". How can I print "Busy" instead of 1?


http://codepad.org/9NDlxxyU demonstration


#include 
using namespace std;
enum Status{Idle, Busy};
class text
{
public:
void SetStatus(Status s);
Status getStatus();
private:
Status s;
};
void text::SetStatus(Status s)
{
this->s = s;
}
Status text::getStatus()
{
return this->s;
}
int main()
{
text myText;
myText.SetStatus(Busy);
cout << myText.getStatus() << endl; //outputs 1, should output "Busy"
}

php - Magento error: call to member function on a non-object



I have this error message:




Fatal error: Call to a member function load() on a non-object in /home/autoco/public_html/shop/app/code/core/Mage/Core/Model/Abstract.php on line 225





How to fix this?






1.0.0






Becker_Tec_Model
tec_resource

Becker_Tec_Model_Resource


tof_manufacturers











standard

Becker_Tec

tecdoc







Model class:




class Becker_Tec_Model_Manufacturers extends Mage_Core_Model_Abstract
{

protected function _construct()
{
$this->_init('tec/manufacturers');
}
public function test(){
$this->getCollection()->load(15);

}

}


Resource class:




class Becker_Tec_Model_Resource_Manufacturers extends Mage_Core_Model_Resource_Db_Abstract {


protected function _construct()
{
$this->_init('tec/manufacturers', 'tof_manufacturers_id');
}

}


Test Page:





require_once("app/Mage.php");

Mage::app();

$data = Mage::getModel("tec/manufacturers");
$data->load(136);
print_r($data);


Answer






Was the culprit as it didn't recognize how to hook up your call.



First of all use the same naming convention to avoid driving yourself mad.



Config xml model section:






Becker_Tec_Model
becker_tec_resource


Becker_Tec_Model_Resource



becker_tec







Model Class:



class Becker_Tec_Model_Tec extends Mage_Core_Model_Abstract 

{
protected function _construct()
{
$this->_init( 'becker_tec/tec' );
}


Resource class:



class Becker_Tec_Model_Tec_Resource_Tec extends Mage_Core_Model_Resource_Db_Abstract

{
protected function _construct()
{
$this->_init( 'becker_tec/tec', 'entity_id' );
}


Collection class: ( If you want to use built in collection mechanisms )



class Becker_Tec_Model_Tec_Resource_Tec_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract

{
public function _construct()
{
parent::_construct();
$this->_init( 'becker_tec/tec' );
}


Place them in the appropriate folders and you'll be able to call:




$oTec = Mage::getModel( 'becker_tec/tec' );

memory - Automatic variables in C++

C++ does not have the concept of a stack or heap, it is an implementation detail as far as the language is concerned.


That being said, every implementation I know of uses the stack to manage the lifetime of local variables. However, many local variables may end up living entirely within registers and never touch the stack, and some local variables may be optimised out completely. Just because you declare an automatic variable doesn't mean that it will be put on the stack.


e.g.


int main()
{
int x = rand();
int y = 2;
cout << x << y << endl;
return 0;
}

In this code, with optimisations on, the variable y will almost certainly be removed completely and variable x will probably be given its own register. It's unlikely that either of those variables will ever exist on the stack.

android - Passing object to method in java appears to be by reference (and Java is by val)

I thought when you passed objects to methods in Java, they were supposed to be by value.



Here is my code:



public class MyClass{
int mRows;
int mCols;

Tile mTiles[][]; //Custom class

//Constructor
public MyClass(Tile[][] tiles, int rows, int cols) {
mRows = rows;
mCols = cols;

mTiles = new Tile[mRows][mCols];
for (int i=0; i < mRows; i++) {
for (int j=0; j < mCols; j++) {

mTiles[i][j] = new Tile();
mTiles[i][j] = tiles[i][j];
}
}
}


At this point, any changes to the mTiles object are reflected back to the tiles object. Any ideas how to fix this?



Thanks all.

mysql - Unexpected T_CONSTANT_ENCAPSED_STRING error in SQL Query



I am getting an unexpected T_CONSTANT_ENCAPSED_STRING error in the following SQL query:




mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id');


Can you guys see where the error might be?



Here is the full code in case it helps:



    $key = 'feed';
$post_ids = array(2263, 2249);


foreach ($post_ids as $id) {
$feedurl = get_post_custom_values($key, $id);
$feedurlstr = implode($feedurl);

// Ignore - it determines whether feed is live and returns $result
LiveOrNot($feedurlstr);

if ( $result == "live" ) {
mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id');

}
elseif ( $result == "notlive" ) {
mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'draft' WHERE 'post_id' = '$id');
}
endif;
}

Answer



Wrap your SQL statements in quote-marks - ".




mysql_query ("UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id'");

c++ - What are the basic rules and idioms for operator overloading?

Note: The answers were given in a specific order, but since many users sort answers according to votes, rather than the time they were given, here's an index of the answers in the order in which they make most sense:






(Note: This is meant to be an entry to C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)

bash - How do I prompt for Yes/No/Cancel input in a Linux shell script?



I want to pause input in a shell script, and prompt the user for choices. The standard 'Yes, No, or Cancel' type question. How do I accomplish this in a typical bash prompt?


Answer



The simplest and most widely available method to get user input at a shell prompt is the read command. The best way to illustrate its use is a simple demonstration:



while true; do
read -p "Do you wish to install this program?" yn
case $yn in

[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done


Another method, pointed out by Steven Huwig, is Bash's select command. Here is the same example using select:



echo "Do you wish to install this program?"

select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done


With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.




Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:



set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"

while true; do
read -p "Install (${yesword} / ${noword})? " yn
case $yn in
${yesptrn##^} ) make install; break;;
${noptrn##^} ) exit;;

* ) echo "Answer ${yesword} / ${noword}.";;
esac
done


Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.



Finally, please check out the excellent answer by F. Hauri.


javascript - Resolve $http request before running app and switching to a route or state



I have written an app where I need to retrieve the currently logged in user's info when the application runs, before routing is handled. I use ui-router to support multiple/nested views and provide richer, stateful routing.




When a user logs in, they may store a cookie representing their auth token. I include that token with a call to a service to retrieve the user's info, which includes what groups they belong to. The resulting identity is then set in a service, where it can be retrieved and used in the rest of the application. More importantly, the router will use that identity to make sure they are logged in and belong to the appropriate group before transitioning them to the requested state.



I have code something like this:



app
.config(['$stateProvider', function($stateProvider) {

// two states; one is the protected main content, the other is the sign-in screen

$stateProvider

.state('main', {
url: '/',
data: {
roles: ['Customer', 'Staff', 'Admin']
},
views: {} // omitted
})
.state('account.signin', {
url: '/signin',
views: {} // omitted

});
}])
.run(['$rootScope', '$state', '$http', 'authority', 'principal', function($rootScope, $state, $http, authority, principal) {

$rootScope.$on('$stateChangeStart', function (event, toState) { // listen for when trying to transition states...
var isAuthenticated = principal.isAuthenticated(); // check if the user is logged in

if (!toState.data.roles || toState.data.roles.length == 0) return; // short circuit if the state has no role restrictions

if (!principal.isInAnyRole(toState.data.roles)) { // checks to see what roles the principal is a member of

event.preventDefault(); // role check failed, so...
if (isAuthenticated) $state.go('account.accessdenied'); // tell them they are accessing restricted feature
else $state.go('account.signin'); // or they simply aren't logged in yet
}
});

$http.get('/svc/account/identity') // now, looks up the current principal
.success(function(data) {
authority.authorize(data); // and then stores the principal in the service (which can be injected by requiring "principal" dependency, seen above)
}); // this does its job, but I need it to finish before responding to any routes/states

}]);


It all works as expected if I log in, navigate around, log out, etc. The issue is that if I refresh or drop on a URL while I am logged in, I get sent to the signin screen because the identity service call has not finished before the state changes. After that call completes, though, I could feasibly continue working as expected if there is a link or something to- for example- the main state, so I'm almost there.



I am aware that you can make states wait to resolve parameters before transitioning, but I'm not sure how to proceed.


Answer



OK, after much hair pulling, here is what I figured out.





  1. As you might expect, resolve is the appropriate place to initiate any async calls and ensure they complete before the state is transitioned to.

  2. You will want to make an abstract parent state for all states that ensures your resolve takes place, that way if someone refreshes the browser, your async resolution still happens and your authentication works properly. You can use the parent property on a state to make another state that would otherwise not be inherited by naming/dot notation. This helps in preventing your state names from becoming unmanageable.

  3. While you can inject whatever services you need into your resolve, you can't access the toState or toStateParams of the state it is trying to transition to. However, the $stateChangeStart event will happen before your resolve is resolved. So, you can copy toState and toStateParams from the event args to your $rootScope, and inject $rootScope into your resolve function. Now you can access the state and params it is trying to transition to.

  4. Once you have resolved your resource(s), you can use promises to do your authorization check, and if it fails, use $state.go() to send them to the login page, or do whatever you need to do. There is a caveat to that, of course.

  5. Once resolve is done in the parent state, ui-router won't resolve it again. That means your security check won't occur! Argh! The solution to this is to have a two-part check. Once in resolve as we've already discussed. The second time is in the $stateChangeStart event. The key here is to check and see if the resource(s) are resolved. If they are, do the same security check you did in resolve but in the event. if the resource(s) are not resolved, then the check in resolve will pick it up. To pull this off, you need to manage your resources within a service so you can appropriately manage state.



Some other misc. notes:





  • Don't bother trying to cram all of the authz logic into $stateChangeStart. While you can prevent the event and do your async resolution (which effectively stops the change until you are ready), and then try and resume the state change in your promise success handler, there are some issues preventing that from working properly.

  • You can't change states in the current state's onEnter method.



This plunk is a working example.


Monday, February 25, 2019

security - How to detect SQL Injection sitting at a reverse proxy?

I am writing a simple reverse proxy in java. So, I have access to all Http requests and responses exchanged between client and server. Sitting at the proxy I am trying to detect SQL Injection Attack.



I got few links - (like for example)



http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks



where some regex are mentioned, but I suppose it's not that simple.
It is impossible to write regex for all possible/valid SQL statements.

Because so many databases are there in the market and SQL statements must follow some grammer rules.



Let me break down the problem to a simple question -



Given a string, can it be checked that whether it contains a valid SQL statement?



Can anyone tell me the best way to do it? Or, any library which does that for me?

javascript - PhantomJS GET URL Parameter



How do I retrieve the GET URL parameters when running a server under PhantomJS. Here's the code.



var webserver = require('webserver');

var server = webserver.create();


var service = server.listen(9090, function(request, response)
{
var page = require('webpage').create();

console.log('GET: ' + request.get)
console.log('POST: ' + request.post)

Answer



The Web Server module doesn't parse the parameters for you like PHP does it. You would need to do this yourself.




server.listen(9090, function(request, response) {
// parse url property to get the GET parameters
console.log('URL: ' + request.url);
console.log(" " + JSON.stringify(parseGET(request.url), undefined, 4)); // pretty print

// parse post property to get the POST parameters (message body)
console.log('BODY: ' + request.post);
};


function parseGET(url){
// adapted from http://stackoverflow.com/a/8486188
var query = url.substr(url.indexOf("?")+1);
var result = {};
query.split("&").forEach(function(part) {
var e = part.indexOf("=")
var key = part.substr(0, e);
var value = part.substr(e+1);
result[key] = decodeURIComponent(value);
});

return result;
}


The complete documentation this can be found here.


How can I merge properties of two JavaScript objects dynamically?

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:



var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }


obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal


Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

html - How do I remove the space between inline-block elements?




Given this HTML and CSS:





span {
display:inline-block;
width:100px;
background-color:palevioletred;
}



Foo
Bar






As a result, there will be a 4 pixel wide space between the SPAN elements.




Demo: http://jsfiddle.net/dGHFV/



I understand why this happens, and I also know that I could get rid of that space by removing the white-space between the SPAN elements in the HTML source code, like so:




Foo Bar




However, I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with.




I know how to solve this with JavaScript - by removing the text nodes from the container element (the paragraph), like so:



// jQuery
$('p').contents().filter(function() { return this.nodeType === 3; }).remove();


Demo: http://jsfiddle.net/dGHFV/1/



But can this issue be solved with CSS alone?



Answer



Since this answer has become rather popular, I'm rewriting it significantly.



Let's not forget the actual question that was asked:




How to remove the space between inline-block elements? I was hoping
for a CSS solution that doesn't require the HTML source code to be
tampered with. Can this issue be solved with CSS alone?





It is possible to solve this problem with CSS alone, but there are no completely robust CSS fixes.



The solution I had in my initial answer was to add font-size: 0 to the parent element, and then declare a sensible font-size on the children.



http://jsfiddle.net/thirtydot/dGHFV/1361/



This works in recent versions of all modern browsers. It works in IE8. It does not work in Safari 5, but it does work in Safari 6. Safari 5 is nearly a dead browser (0.33%, August 2015).



Most of the possible issues with relative font sizes are not complicated to fix.




However, while this is a reasonable solution if you specifically need a CSS only fix, it's not what I recommend if you're free to change your HTML (as most of us are).






This is what I, as a reasonably experienced web developer, actually do to solve this problem:




FooBar





Yes, that's right. I remove the whitespace in the HTML between the inline-block elements.



It's easy. It's simple. It works everywhere. It's the pragmatic solution.



You do sometimes have to carefully consider where whitespace will come from. Will appending another element with JavaScript add whitespace? No, not if you do it properly.



Let's go on a magical journey of different ways to remove the whitespace, with some new HTML:





  • Item 1

  • Item 2

  • Item 3





  • You can do this, as I usually do:





    • Item 1
    • Item 2
    • Item 3




    http://jsfiddle.net/thirtydot/dGHFV/1362/


  • Or, this:




    • Item 1
      >
    • Item 2 >
    • Item 3



  • Or, use comments:




    • Item 1
    • Item 2
    • Item 3




  • Or, if you are using using PHP or similar:




    • Item 1
    • ?>
    • Item 2
    • ?>
    • Item 3




  • Or, you can even skip certain closing tags entirely (all browsers are fine with this):




    • Item 1
    • Item 2
    • Item 3





Now that I've gone and bored you to death with "one thousand different ways to remove whitespace, by thirtydot", hopefully you've forgotten all about font-size: 0.






Alternatively, you can now use flexbox to achieve many of the layouts that you may previously have used inline-block for: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


Is List a subclass of List? Why are Java generics not implicitly polymorphic?



I'm a bit confused about how Java generics handle inheritance / polymorphism.



Assume the following hierarchy -




Animal (Parent)



Dog - Cat (Children)



So suppose I have a method doSomething(List animals). By all the rules of inheritance and polymorphism, I would assume that a List is a List and a List is a List - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subclass of Animal by saying doSomething(List animals).



I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?


Answer



No, a List is not a List. Consider what you can do with a List - you can add any animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.




// Illegal code - because otherwise life would be Bad
List dogs = new ArrayList(); // ArrayList implements List
List animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?


Suddenly you have a very confused cat.



Now, you can't add a Cat to a List because you don't know it's a List. You can retrieve a value and know that it will be an Animal, but you can't add arbitrary animals. The reverse is true for List - in that case you can add an Animal to it safely, but you don't know anything about what might be retrieved from it, because it could be a List.



php - syntax error, unexpected T_DOUBLE_ARROW





how i can rid of this error??



Parse error: syntax error, unexpected T_DOUBLE_ARROW in /var/www/core/restvt.api.php on line 35



PHP Code :



            $datax = Array();

foreach ($inis as $key => $data){

if ($data=="mem"){
$str = number_format($ARRAY[(array_search($data.':',$ARRAY)+2)]/1024,0,',','.')." MB [ ".number_format(($ARRAY[(array_search($data.':',$ARRAY)+2)]/$ARRAY[(array_search($data.':',$ARRAY)+1)])*100,0,',','.')." % ]";
array_push($datax, "mem"=>$str); //error here, why?
}else{

array_push($datax,$data=>$ARRAY[(array_search($data.':',$ARRAY)+1)]);
}
}

$jsonr = json_encode($datax);


thx alot for your help...


Answer



I hate seeing people use array_push - I know it's legal. In this case, you can't push a key => value to your array, just do this instead:




$datax['mem'] = $str;


Manual: http://php.net/manual/en/function.array-push.php




edit





If you insist on using the array_push type method, you'll need to create a new array with your new key value pair then use array_merge to join them:



$new_data = array('mem' => $str);
$datax = array_merge($datax, $new_data);

How to parse xml using python

I have the below xml file :





cq:lastReplicated="{Date}2016-03-02T15:23:40.679-05:00"
cq:lastReplicatedBy="XXXXt"
cq:lastReplicationAction="Activate"
jcr:description="Procedure"
jcr:mixinTypes="[cq:ReplicationStatus]"
jcr:primaryType="cq:Tag"
jcr:title="Lung Volume Reduction Surgery"
sling:resourceType="cq/tagging/components/tag"/>



I am trying to parse the XML file using ElementTree but I am not able to extract "Lung Volume Reduction Surgery" which is under the tag jcr:title .



I have already tried with BeatifulSoup , Regex and ElementTree but unable to do it



Below is the code that I used for Element Tree :



import xml.etree.ElementTree as ET
xml="Actual xml document"
xml.find('./root').attrib['title']



I am a beginner in XML parsing .. and spent more than 3 hours now on this XML file but unable to parse the value of jcr:title Any help will be greatly appreciated

linux - Can atomic ops based spin lock's Unlock directly set the lock flag to zero?

Say for example, I have an exclusive atomic-ops-based spin lock implementation as below:



bool TryLock(volatile TInt32 * pFlag)
{
return !(AtomicOps::Exchange32(pFlag, 1) == 1);
}

void Lock (volatile TInt32 * pFlag)
{
while (AtomicOps::Exchange32(pFlag, 1) == 1) {
AtomicOps::ThreadYield();
}
}

void Unlock (volatile TInt32 * pFlag)
{
*pFlag = 0; // is this ok? or here as well a atomicity is needed for load and store
}


Where AtomicOps::Exchange32 is implemented on windows using InterlockedExchange and on linux using __atomic_exchange_n.

javascript - Is it possible to apply CSS to half of a character?



What I am looking for:



A way to style one HALF of a character. (In this case, half the letter being transparent)



What I have currently searched for and tried (With no luck):




  • Methods for styling half of a character/letter


  • Styling part of a character with CSS or JavaScript

  • Apply CSS to 50% of a character



Below is an example of what I am trying to obtain.



x



Does a CSS or JavaScript solution exist for this, or am I going to have to resort to images? I would prefer not to go the image route as this text will end up being generated dynamically.







UPDATE:



Since many have asked why I would ever want to style half of a character, this is why. My city had recently spent $250,000 to define a new "brand" for itself. This logo is what they came up with. Many people have complained about the simplicity and lack of creativity and continue to do so. My goal was to come up with this website as a joke. Type in 'Halifax' and you will see what I mean.


Answer





enter image description here Feel free to fork and improve.










  • Pure CSS for a Single Character

  • JavaScript used for automation across text or multiple characters

  • Preserves Text Accessibility for screen readers for the blind or visually
    impaired






Half Style on text



Demo: http://jsfiddle.net/arbel/pd9yB/1694/






This works on any dynamic text, or a single character, and is all automated. All you need to do is add a class on the target text and the rest is taken care of.




Also, the accessibility of the original text is preserved for screen readers for the blind or visually impaired.



Explanation for a single character:



Pure CSS. All you need to do is to apply .halfStyle class to each element that contains the character you want to be half-styled.



For each span element containing the character, you can create a data attribute, for example here data-content="X", and on the pseudo element use content: attr(data-content); so the .halfStyle:before class will be dynamic and you won't need to hard code it for every instance.



Explanation for any text:




Simply add textToHalfStyle class to the element containing the text.








// jQuery for automated mode
jQuery(function($) {
var text, chars, $el, i, output;


// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {
$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');


// Reset output for appending
output = '';

// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}

// Write to DOM only once

$el.append(output);
});
});

.halfStyle {
position: relative;
display: inline-block;
font-size: 80px; /* or any font size will work */
color: black; /* or transparent, any color */
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */

}

.halfStyle:before {
display: block;
z-index: 1;
position: absolute;
top: 0;
left: 0;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */

overflow: hidden;
color: #f00;
}



Single Characters:


X
Y
Z
A




Automated:



Half-style, please.





(JSFiddle demo)









Half Style on text - advanced - With Text Shadow



With this solution you can style left and right parts, individually and independently.



Everything is the same, only more advanced CSS does the magic.






jQuery(function($) {
var text, chars, $el, i, output;

// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {
$el = $(el);
text = $el.text();

chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');

// Reset output for appending
output = '';

// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {

// Create a styled element for each character and append to container
output += '';
}

// Write to DOM only once
$el.append(output);
});
});

.halfStyle {
position: relative;

display: inline-block;
font-size: 80px; /* or any font size will work */
color: transparent; /* hide the base character */
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before { /* creates the left part */
display: block;
z-index: 1;

position: absolute;
top: 0;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #f00; /* for demo purposes */
text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}


.halfStyle:after { /* creates the right part */
display: block;
direction: rtl; /* very important, will make the width to start from right */
position: absolute;
z-index: 2;
top: 0;
left: 50%;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;

pointer-events: none; /* so the base char is selectable by mouse */
color: #000; /* for demo purposes */
text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}


Single Characters:


X
Y
Z
A




Automated:



Half-style, please.





(JSFiddle demo)












Now that we know what is possible, let's create some variations.







-Horizontal Half Parts




  • Without Text Shadow:



    Horizontal Half Parts - No Text Shadow


  • Possibility of Text Shadow for each half part independently:



    halfStyle - Horizontal Half Parts - With Text Shadow







// jQuery for automated mode
jQuery(function($) {
var text, chars, $el, i, output;

// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {

$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');

// Reset output for appending
output = '';


// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}

// Write to DOM only once
$el.append(output);
});
});


.halfStyle {
position: relative;
display: inline-block;
font-size: 80px; /* or any font size will work */
color: transparent; /* hide the base character */
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before { /* creates the top part */

display: block;
z-index: 2;
position: absolute;
top: 0;
height: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #f00; /* for demo purposes */
text-shadow: 2px -2px 0px #af0; /* for demo purposes */

}

.halfStyle:after { /* creates the bottom part */
display: block;
position: absolute;
z-index: 1;
top: 0;
height: 100%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;

pointer-events: none; /* so the base char is selectable by mouse */
color: #000; /* for demo purposes */
text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}


Single Characters:


X
Y
Z
A




Automated:



Half-style, please.





(JSFiddle demo)










-Vertical 1/3 Parts




  • Without Text Shadow:




    halfStyle - Vertical 1/3 Parts - No Text Shadow


  • Possibility of Text Shadow for each 1/3 part independently:



    halfStyle - Vertical 1/3 Parts - With Text Shadow






// jQuery for automated mode
jQuery(function($) {

var text, chars, $el, i, output;

// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {
$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');


// Reset output for appending
output = '';

// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}


// Write to DOM only once
$el.append(output);
});
});

.halfStyle { /* base char and also the right 1/3 */
position: relative;
display: inline-block;
font-size: 80px; /* or any font size will work */
color: transparent; /* hide the base character */
overflow: hidden;

white-space: pre; /* to preserve the spaces from collapsing */
color: #f0f; /* for demo purposes */
text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle:before { /* creates the left 1/3 */
display: block;
z-index: 2;
position: absolute;
top: 0;

width: 33.33%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #f00; /* for demo purposes */
text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}

.halfStyle:after { /* creates the middle 1/3 */
display: block;

z-index: 1;
position: absolute;
top: 0;
width: 66.66%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #000; /* for demo purposes */
text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}




Single Characters:


X
Y
Z
A



Automated:




Half-style, please.





(JSFiddle demo)










-Horizontal 1/3 Parts




  • Without Text Shadow:



    halfStyle - Horizontal 1/3 Parts - No Text Shadow


  • Possibility of Text Shadow for each 1/3 part independently:




    halfStyle - Horizontal 1/3 Parts - With Text Shadow






// jQuery for automated mode
jQuery(function($) {
var text, chars, $el, i, output;

// Iterate over all class occurences

$('.textToHalfStyle').each(function(idx, el) {
$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');

// Reset output for appending
output = '';


// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}

// Write to DOM only once
$el.append(output);
});

});

.halfStyle { /* base char and also the bottom 1/3 */
position: relative;
display: inline-block;
font-size: 80px; /* or any font size will work */
color: transparent;
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */
color: #f0f;
text-shadow: 2px 2px 0px #0af; /* for demo purposes */

}

.halfStyle:before { /* creates the top 1/3 */
display: block;
z-index: 2;
position: absolute;
top: 0;
height: 33.33%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;

pointer-events: none; /* so the base char is selectable by mouse */
color: #f00; /* for demo purposes */
text-shadow: 2px -2px 0px #fa0; /* for demo purposes */
}

.halfStyle:after { /* creates the middle 1/3 */
display: block;
position: absolute;
z-index: 1;
top: 0;

height: 66.66%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #000; /* for demo purposes */
text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}


Single Characters:


X

Y
Z
A



Automated:



Half-style, please.






(JSFiddle demo)









-HalfStyle Improvement By @KevinGranger




halfStyle - KevinGranger





// jQuery for automated mode
jQuery(function($) {
var text, chars, $el, i, output;

// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {

$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');

// Reset output for appending
output = '';


// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}

// Write to DOM only once
$el.append(output);
});
});


body {
background-color: black;
}

.textToHalfStyle {
display: block;
margin: 200px 0 0 0;
text-align: center;
}


.halfStyle {
font-family: 'Libre Baskerville', serif;
position: relative;
display: inline-block;
width: 1;
font-size: 70px;
color: black;
overflow: hidden;
white-space: pre;
text-shadow: 1px 2px 0 white;

}

.halfStyle:before {
display: block;
z-index: 1;
position: absolute;
top: 0;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;

color: white;
}


Single Characters:


X
Y
Z
A




Automated:



Half-style, please.





(JSFiddle demo)









-PeelingStyle improvement of HalfStyle by @SamTremaine



halfStyle - SamTremaine





// jQuery for automated mode
jQuery(function($) {

var text, chars, $el, i, output;

// Iterate over all class occurences
$('.textToHalfStyle').each(function(idx, el) {
$el = $(el);
text = $el.text();
chars = text.split('');

// Set the screen-reader text
$el.html('' + text + '');


// Reset output for appending
output = '';

// Iterate over all chars in the text
for (i = 0; i < chars.length; i++) {
// Create a styled element for each character and append to container
output += '';
}


// Write to DOM only once
$el.append(output);
});
});

.halfStyle {
position: relative;
display: inline-block;
font-size: 68px;
color: rgba(0, 0, 0, 0.8);
overflow: hidden;

white-space: pre;
transform: rotate(4deg);
text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}

.halfStyle:before { /* creates the left part */
display: block;
z-index: 1;
position: absolute;
top: -0.5px;

left: -3px;
width: 100%;
content: attr(data-content);
overflow: hidden;
pointer-events: none;
color: #FFF;
transform: rotate(-4deg);
text-shadow: 0px 0px 1px #000;
}



Single Characters:


X
Y
Z
A



Automated:



Half-style, please.






(JSFiddle demo and on samtremaine.co.uk)











Customized different Half-Style style-sets can be used on desired elements on the same page.
You can define multiple style-sets and tell the plugin which one to use.



The plugin uses data attribute data-halfstyle="[-CustomClassName-]" on the target .textToHalfStyle elements and makes all the necessary changes automatically.



So, simply on the element containing the text add textToHalfStyle class and data attribute data-halfstyle="[-CustomClassName-]". The plugin will do the rest of the job.



halfStyle - Multiple on Same Page




Also the CSS style-sets' class definitions match the [-CustomClassName-] part mentioned above and is chained to .halfStyle, so we will have .halfStyle.[-CustomClassName-]





jQuery(function($) {
var halfstyle_text, halfstyle_chars, $halfstyle_el, halfstyle_i, halfstyle_output, halfstyle_style;

// Iterate over all class occurrences
$('.textToHalfStyle').each(function(idx, halfstyle_el) {
$halfstyle_el = $(halfstyle_el);

halfstyle_style = $halfstyle_el.data('halfstyle') || 'hs-base';
halfstyle_text = $halfstyle_el.text();
halfstyle_chars = halfstyle_text.split('');

// Set the screen-reader text
$halfstyle_el.html('' + halfstyle_text + '');

// Reset output for appending
halfstyle_output = '';


// Iterate over all chars in the text
for (halfstyle_i = 0; halfstyle_i < halfstyle_chars.length; halfstyle_i++) {
// Create a styled element for each character and append to container
halfstyle_output += '';
}

// Write to DOM only once
$halfstyle_el.append(halfstyle_output);
});
});


/* start half-style hs-base */

.halfStyle.hs-base {
position: relative;
display: inline-block;
font-size: 80px; /* or any font size will work */
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */
color: #000; /* for demo purposes */
}


.halfStyle.hs-base:before {
display: block;
z-index: 1;
position: absolute;
top: 0;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
pointer-events: none; /* so the base char is selectable by mouse */
overflow: hidden;

color: #f00; /* for demo purposes */
}

/* end half-style hs-base */


/* start half-style hs-horizontal-third */

.halfStyle.hs-horizontal-third { /* base char and also the bottom 1/3 */
position: relative;

display: inline-block;
font-size: 80px; /* or any font size will work */
color: transparent;
overflow: hidden;
white-space: pre; /* to preserve the spaces from collapsing */
color: #f0f;
text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle.hs-horizontal-third:before { /* creates the top 1/3 */

display: block;
z-index: 2;
position: absolute;
top: 0;
height: 33.33%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
pointer-events: none; /* so the base char is selectable by mouse */
color: #f00; /* for demo purposes */
text-shadow: 2px -2px 0px #fa0; /* for demo purposes */

}

.halfStyle.hs-horizontal-third:after { /* creates the middle 1/3 */
display: block;
position: absolute;
z-index: 1;
top: 0;
height: 66.66%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;

pointer-events: none; /* so the base char is selectable by mouse */
color: #000; /* for demo purposes */
text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}

/* end half-style hs-horizontal-third */


/* start half-style hs-PeelingStyle, by user SamTremaine on Stackoverflow.com */


.halfStyle.hs-PeelingStyle {
position: relative;
display: inline-block;
font-size: 68px;
color: rgba(0, 0, 0, 0.8);
overflow: hidden;
white-space: pre;
transform: rotate(4deg);
text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}


.halfStyle.hs-PeelingStyle:before { /* creates the left part */
display: block;
z-index: 1;
position: absolute;
top: -0.5px;
left: -3px;
width: 100%;
content: attr(data-content);
overflow: hidden;

pointer-events: none;
color: #FFF;
transform: rotate(-4deg);
text-shadow: 0px 0px 1px #000;
}

/* end half-style hs-PeelingStyle */


/* start half-style hs-KevinGranger, by user KevinGranger on StackOverflow.com*/


.textToHalfStyle.hs-KevinGranger {
display: block;
margin: 200px 0 0 0;
text-align: center;
}

.halfStyle.hs-KevinGranger {
font-family: 'Libre Baskerville', serif;
position: relative;

display: inline-block;
width: 1;
font-size: 70px;
color: black;
overflow: hidden;
white-space: pre;
text-shadow: 1px 2px 0 white;
}

.halfStyle.hs-KevinGranger:before {

display: block;
z-index: 1;
position: absolute;
top: 0;
width: 50%;
content: attr(data-content); /* dynamic content for the pseudo element */
overflow: hidden;
color: white;
}


/* end half-style hs-KevinGranger



Half-style, please.



Half-style, please.



Half-style, please.



Half-style, please.






(JSFiddle demo)


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...