问:
Image resize Plugin for Wordpress
I need a plugin in WOrdpress that would meets the following requirements-

I need a plgin where we can upload an image that appears behind the mask and can be moveable and scaleable.

The user can scale and move the images around how they like, once they are happy then we want to be able to download as a jpg.

So basically users need to upload there own picture, be able to move it around and scale behind the mask. Once they have finished download it to jpg.

Is their any plugin aroud in Wordpress?

Thanks in advance. Any help would appreciated !

答:
Try below plugins Hope this will help you,

https://wordpress.org/plugins/resize-image-after-upload/

https://wordpress.org/plugins/imsanity/

Title: Image resize Plugin for Wordpress


来源: stackexchange

问:
Open pdf file from the server in GWT
I want to open a pdf file from a button of my GWT application. Actually to access that file I've to query the server that returns the file encoded in base64 from a JSON request.
It's possible to open that file then?</p>

答:
To show a pdf "file" (it's not a file, but a byte stream in http reply) you need to rely on browsers own capability to render pdf data. To do this you must either open a URL in a new window or in in an iframe. The second is probably a better option when using GWT. Docs of the GWT Frame.

```<code>// url of the pdf (must have application/pdf content-type)
Frame frame = new Frame("url");
// add the frame wherever you want
RootPanel.get().add(frame);
</code>```

In order for the browser to correctly display pdf page (by invoking the pdf plugin), the url that serves the pdf data must have a header that says Content-Type: application/pdf. Check that your response has this header.

ContentLicense: CC BY-SA 2.5

Title: Open pdf file from the server in GWT

Body:
To show a pdf "file" (it's not a file, but a byte stream in http reply) you need to rely on browsers own capability to render pdf data. To do this you must either open a URL in a new window or in in an iframe. The second is probably a better option when using GWT. Docs of the GWT Frame.

// url of the pdf (must have application/pdf content-type)
Frame frame = new Frame("url");
// add the frame wherever you want
RootPanel.get().add(frame);

In order for the browser to correctly display pdf page (by invoking the pdf plugin), the url that serves the pdf data must have a header that says Content-Type: application/pdf. Check that your response has this header.


问:
Candidate and Superkey
Given a relation schema R with n attributes R(A1, A2, ..., An). What’s the maximum number of possible super-keys for R? Please justify your answer.

Given a relation schema R with n attributes R(A1, A2, ..., An). What’s the maximum number of possible candidate keys for R? Please justify your answer.

I am still wondering on how to answer both of these questions. What I have thought as answer for the first question would be (2^n) - 1 because empty set is not included.

As for the second question. My answer would be n atrributes.

What do you guys think?

答:
The maximum number of superkeys for R with n attributes is 2^n, which is the size of the power set of R's attributes. This is obvious when you realise that ∅ (the empty set) may be a candidate key and that ∅ is a subset of every set of attributes.

The maximum number of candidate keys is given by nC(n/2) (binomial coefficient).

ContentLicense: CC BY-SA 3.0

Title: Candidate and Superkey


问:
How to open pdf file in external app or in webview size is greater than 25mb
hello i want to show pdf file in webview or in external app.

1) i use this url
https://docs.google.com/gview?embedded=true&url= +pdfurl , but google says "Whoops There was a problen while previewing document"

2) if i use intent to open the url in external app then they didnot load the file in external app.

3) if i use the intent to open the url in browser then its start downloading the pdf file.

```<code>Intent ii=new Intent(Intent.ACTION_VIEW);
    ii.setDataAndType(Uri.parse(pdf),"text/html");
    try {
        startActivity(ii);
    }catch (ActivityNotFoundException e)
    {
        Toast.makeText(QuranPara.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
</code>```

here is the complete url https://docs.google.com/gview?embedded=true&url=www.elibrary.alnoorpk.com/PDF%20Books/Lafzi_aur_bamahawrah_terjma_2015/Para%201%20(Lafzi%20aur%20Bamuhawra%20Tarjma).pdf

check the image

答:
To show it in WebView try something like this

```<code>String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
</code>```

To show it in browser try something like this

```<code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
</code>```

Body:
hello i want to show pdf file in webview or in external app.

1) i use this url
https://docs.google.com/gview?embedded=true&url= +pdfurl , but google says "Whoops There was a problen while previewing document"

2) if i use intent to open the url in external app then they didnot load the file in external app.

3) if i use the intent to open the url in browser then its start downloading the pdf file.

Intent ii=new Intent(Intent.ACTION_VIEW);
    ii.setDataAndType(Uri.parse(pdf),"text/html");
    try {
        startActivity(ii);
    }catch (ActivityNotFoundException e)
    {
        Toast.makeText(QuranPara.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }

here is the complete url https://docs.google.com/gview?embedded=true&url=www.elibrary.alnoorpk.com/PDF%20Books/Lafzi_aur_bamahawrah_terjma_2015/Para%201%20(Lafzi%20aur%20Bamuhawra%20Tarjma).pdf

check the image

Body:
To show it in WebView try something like this

String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

To show it in browser try something like this

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);


问:
Firebase WEB - Email Verification not being sent. What's wrong with the code
Well, I've tried using many ways to trigger the function sendEmailVerification(). But none have worked successfully. The docs aren't helping either.

Below is part of the source code that I will be using. Please let me know of how I can correct this.

On my console I get the the following error:

TypeError: Cannot read property 'emailVerified' of null
           at Object.firebase.auth.onAuthStateChanged.firebaseUser [as next]

```

        btnSignUpWithGoogle.addEventListener('click', e => {
            var provider = new firebase.auth.GoogleAuthProvider();

            firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
          }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log(errorCode);
          });
    });

    btnLogin.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.signInWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";
    });

    btnSignUp.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.createUserWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";

      const emailVerified = firebaseUser.emailVerified;

      if (!emailVerified){
        firebase.auth().firebaseUser.sendEmailVerification().then(function(){
          alert('Please check your email to verify your Account.');
        });
      } else {
        alert('Your Email has been verified!');
      }

    });

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        console.log(firebaseUser);
        console.log('Logged IN!');
        btnLogout.style.visibility = 'visible';
    }
      if (firebaseUser.emailVerified) {
        console.log('Email is verified');
      }
      else {
        console.log('Email is not verified');
        firebaseUser.sendEmailVerification();
      }

    });

```

答:
Can we see all the code? Are you sure that your firebase.auth() is declared properly?

Your auth should look like this:

```<code>const firebaseApp = firebase.initializeApp(firebaseConfig, 'Client');
const firebaseAuth = firebaseApp.auth();
</code>```

firebaseUser should have emailVerified key. Move your if else statement inside if firebaseUser like this:

```<code>firebase.auth().onAuthStateChanged(firebaseUser => {
  if (firebaseUser) {
    console.log(firebaseUser);
    console.log('Logged IN!');
    btnLogout.style.visibility = 'visible';

    if (firebaseUser.emailVerified) {
      console.log('Email is verified');
    }
    else {
      console.log('Email is not verified');
      firebaseUser.sendEmailVerification();
    }

  }

});
</code>```

console.log(firebaseUser), what is says?

Body:
Well, I've tried using many ways to trigger the function sendEmailVerification(). But none have worked successfully. The docs aren't helping either.

Below is part of the source code that I will be using. Please let me know of how I can correct this.

On my console I get the the following error:

TypeError: Cannot read property 'emailVerified' of null
           at Object.firebase.auth.onAuthStateChanged.firebaseUser [as next]

        btnSignUpWithGoogle.addEventListener('click', e => {
            var provider = new firebase.auth.GoogleAuthProvider();

            firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
          }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log(errorCode);
          });
    });

    btnLogin.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.signInWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";
    });

    btnSignUp.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.createUserWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";

      const emailVerified = firebaseUser.emailVerified;

      if (!emailVerified){
        firebase.auth().firebaseUser.sendEmailVerification().then(function(){
          alert('Please check your email to verify your Account.');
        });
      } else {
        alert('Your Email has been verified!');
      }

    });

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        console.log(firebaseUser);
        console.log('Logged IN!');
        btnLogout.style.visibility = 'visible';
    }
      if (firebaseUser.emailVerified) {
        console.log('Email is verified');
      }
      else {
        console.log('Email is not verified');
        firebaseUser.sendEmailVerification();
      }

    });

Body:
Can we see all the code? Are you sure that your firebase.auth() is declared properly?

Your auth should look like this:

const firebaseApp = firebase.initializeApp(firebaseConfig, 'Client');
const firebaseAuth = firebaseApp.auth();

firebaseUser should have emailVerified key. Move your if else statement inside if firebaseUser like this:

firebase.auth().onAuthStateChanged(firebaseUser => {
  if (firebaseUser) {
    console.log(firebaseUser);
    console.log('Logged IN!');
    btnLogout.style.visibility = 'visible';

    if (firebaseUser.emailVerified) {
      console.log('Email is verified');
    }
    else {
      console.log('Email is not verified');
      firebaseUser.sendEmailVerification();
    }

  }

});

console.log(firebaseUser), what is says?


问:
How to skip case while using String replaceAll
Example my string have :

```<code>text = " Hi {fullname}, wellcome u join my group"
</code>```

this is my code:

```<code>text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");
</code>```

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

答:
ReplaceAll takes regex, so you can try (?i) ignorecase in regex

```<code>text = text.replaceAll("\\{(?i)fullname\\}", us...
</code>```

That works for all {fullname} , {FULLNAME} , {Fullname} ,{fuLLname}

Body:
Example my string have :

text = " Hi {fullname}, wellcome u join my group"

this is my code:

text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

Body:
ReplaceAll takes regex, so you can try (?i) ignorecase in regex

text = text.replaceAll("\\{(?i)fullname\\}", us...

That works for all {fullname} , {FULLNAME} , {Fullname} ,{fuLLname}


问:
Elements from xml using php
so I can access an xml file and all its elements using

```<code>$xml = simplexml_load_file('file.xml');
</code>```

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

```<code><images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >
</code>```

I am in desperate need to loop through these images and get their Url. For that I've tried:

```<code>$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '<br>';
    $i++
}
</code>```

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

答:
```<code> foreach ($element->images as $img) { echo $img->image[$i] . '<br>'; $i++ }
</code>```

There's no image[ ] array declared ,so just try

```<code>echo $img;
</code>```

And it has to loop through it

Title: Elements from xml using php

Body:
so I can access an xml file and all its elements using

$xml = simplexml_load_file('file.xml');

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

<images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >

I am in desperate need to loop through these images and get their Url. For that I've tried:

$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '
';
    $i++
}

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

Body:
 foreach ($element->images as $img) { echo $img->image[$i] . '<br>'; $i++ }

There's no image[ ] array declared ,so just try

echo $img;

And it has to loop through it


问:
Does the Iphone 1/2 have a compass inside?
Can one be simulated by periodicly syncing with GPS and in the meen while working with the accelerometer? I know for example that the N95 accelerometer is invarient to rotation on the Y axis (while beeing face up/down).</p>

答: Extra info: The IPHONE 1 did not have GPS or compass.</p>

OwnerDisplayName: winter

OwnerDisplayName: jm


问:
Sign a WIN CE .cab file as well as all the files inside
I have a cab file provided by a company and in order to secure my environment (terminal) I need to sign the cab as well as all the files inside (DLLs and EXEs) I want to avoid uncabing and recabing to do it. Is there any tool? I've seen signtool from Microsoft I can only sign the cab, not the files inside.</p>

答:
You can sign the files BUT ONLY if it's your code on the device which will unpack them, unwrap the signed data into original files and then install them.

Explanation:

there must be something that will
validate the signatures. You can
sign the CAB, but if the system
doesn't care about the signature
(say allows the user to install the
unsigned or badly-signed CABs), then
your signature makes little sense
unless it's your own code that
performs CAB installation

You can sign any file, but then
again, there must be something (your
code?) that will validate the
signatures. For PKCS#7
(certificate-based) signing you can
use wrapping signatures which make
the file original data part of the
signed file, or detached signatures,
which are kept separately in the
different place (eg. other file). In
case of wrapping signature your code
needs to unwrap the files after
extracting them from the CAB.


问:
Select specifics characters with jquery
I would like tu select the specifics characters cm in a specific div and add this in a span.

The html :

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100
50X50
100X100</div>
</code>```

Jquery

```<code><script>
function highlight_words(cm , fc_img_tooltip_desc) {
if(keywords) {
    var textNodes;
    keywords = keywords.replace(/\W/g, '');
    var str = keywords.split(" ");
    $(str).each(function() {
        var term = this;
        var textNodes = $(element).contents().filter(function() { return
this.nodeType === 3 });
        textNodes.each(function() {
          var content = $(this).text();
          var regex = new RegExp(term, "gi");
          content = content.replace(regex, '<span class="highlight">' + term
+ '</span>');
          $(this).replaceWith(content);
        });
    });
}
}
$(window).onload(function(){ highlight_words(); });
</script>
</code>```

This don't work, i do something wrong.

What i have :

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100cm
50X50cm
100X100cm</div>
</code>```

What i want:

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10 cm
10X100 cm
50X50 cm
100X100 cm</div>
</code>```

答:
Select HTML element with querySelector() then do a replacement on textContent property:

var el = document.querySelector('.fc_img_tooltip_desc');
el.textContent = el.textContent.replace(/\Bcm/, function(match){
  return ' ' + match;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100
50X50
100X100</div></code>```

Put above script at the bottom of html document or fire this snippet on DOMContentLoaded event like this:

```<code><script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) {
        var el = document.querySelector('.fc_img_tooltip_desc');
        el.textContent = el.textContent.replace(/\Bcm/, function(match){
            return ' ' + match;
        })
    });
</script>
</code>```

Update

If you have multiple elements to select, you have to use querySelectorAll() function:

```<code><script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) {
        document.querySelectorAll('.fc_img_tooltip_desc').forEach(function(value) {
            value.innerHTML = value.textContent.replace(/\Bcm/gi, function(match) {
                return ' <span class="highlight">' + match + '</span>';
            })
        });
    });
</script>
</code>```

Title: Select specifics characters with jquery

Body:
I would like tu select the specifics characters cm in a specific div and add this in a span.

The html :

20X10cm
10X100
50X50
100X100

Jquery

This don't work, i do something wrong.

What i have :

20X10cm
10X100cm
50X50cm
100X100cm

What i want:

20X10 cm
10X100 cm
50X50 cm
100X100 cm

Body:
Select HTML element with querySelector() then do a replacement on textContent property:

var el = document.querySelector('.fc_img_tooltip_desc');
el.textContent = el.textContent.replace(/\Bcm/, function(match){
  return ' ' + match;
})

<div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100
50X50
100X100</div>

Put above script at the bottom of html document or fire this snippet on DOMContentLoaded event like this:

<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) {
        var el = document.querySelector('.fc_img_tooltip_desc');
        el.textContent = el.textContent.replace(/\Bcm/, function(match){
            return ' ' + match;
        })
    });
</script>

Update

If you have multiple elements to select, you have to use querySelectorAll() function:

<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) {
        document.querySelectorAll('.fc_img_tooltip_desc').forEach(function(value) {
            value.innerHTML = value.textContent.replace(/\Bcm/gi, function(match) {
                return ' <span class="highlight">' + match + '</span>';
            })
        });
    });
</script>


问:
Spark GraphX : Filtering by passing a vertex value in triplet
I am using Spark 2.1.0 on Windows 10. Since I am new to Spark, I am following this tutorial

In the tutorial, the author prints all the triplets of the graph using the following code:

```<code>graph.triplets.sortBy(_.attr, ascending=false).map(triplet =>
"There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + ".").take(10)
</code>```

Problem : I would like to give an input (ATL for example) and I would like to see all the outbound flights from ATL and their counts as shown below:

```<code>res60: Array[String] = Array(There were 1388 flights from ATL to LAX.,
There were 1330 flights from ATL to SFO., There were 1283 flights from ATL to HNL.,
There were 1205 flights from ATL to BOS., There were 1229 flights from ATL to LGA.,
There were 1214 flights from ATL to OGG., There were 1173 flights from ATL to LAS.,
There were 1157 flights from ATL to SAN.)
</code>```

答:
The following is the code:

```<code>// Selecting the desired airport
val input = "ATL"
// filtering the edges of the desired airport (here "ATL") from the `graph`(which is built on the full data)
val TEMPEdge = graph.edges.filter { case Edge(src, dst, prop) => src == MurmurHash3.stringHash(input) }
// Creating a new graph with the filtered edges
val TEMPGraph = Graph(airportVertices, TEMPEdge, defaultAirport)
// Printing the top 10
TEMPGraph.triplets.sortBy(_.attr, ascending=false).map(triplet => "There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + "\n").take(10)
</code>```

or, we can use filter

```<code>graph.triplets.sortBy(_.attr, ascending=false).filter {_.dstAttr == input }.map(triplet => "There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + "\n").take(3)
</code>```

Body:
I am using Spark 2.1.0 on Windows 10. Since I am new to Spark, I am following this tutorial

In the tutorial, the author prints all the triplets of the graph using the following code:

graph.triplets.sortBy(_.attr, ascending=false).map(triplet =>
"There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + ".").take(10)

Problem : I would like to give an input (ATL for example) and I would like to see all the outbound flights from ATL and their counts as shown below:

res60: Array[String] = Array(There were 1388 flights from ATL to LAX.,
There were 1330 flights from ATL to SFO., There were 1283 flights from ATL to HNL.,
There were 1205 flights from ATL to BOS., There were 1229 flights from ATL to LGA.,
There were 1214 flights from ATL to OGG., There were 1173 flights from ATL to LAS.,
There were 1157 flights from ATL to SAN.)

Body:
The following is the code:

// Selecting the desired airport
val input = "ATL"
// filtering the edges of the desired airport (here "ATL") from the `graph`(which is built on the full data)
val TEMPEdge = graph.edges.filter { case Edge(src, dst, prop) => src == MurmurHash3.stringHash(input) }
// Creating a new graph with the filtered edges
val TEMPGraph = Graph(airportVertices, TEMPEdge, defaultAirport)
// Printing the top 10
TEMPGraph.triplets.sortBy(_.attr, ascending=false).map(triplet => "There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + "\n").take(10)

or, we can use filter

graph.triplets.sortBy(_.attr, ascending=false).filter {_.dstAttr == input }.map(triplet => "There were " + triplet.attr.toString + " flights from " + triplet.srcAttr + " to " + triplet.dstAttr + "\n").take(3)


问:
Unable to query data between two dates in MongoDB
```<code>db.test.find({"date":{$gte:"2017-04-11",$lt:"2017-04-13"}},function(err,doc){
      console.log("date function called");
    res.json(doc);

    console.log(doc);
});
</code>```

<p>code works fine in mongodb and output,but in nodejs the output is empty array. </p>

答:
Collections can be queried with find.  The result for the query is actually a cursor object. This can be used directly or converted to an array. Making queries with find()

cursor.toArray(function(err, docs){}) converts the cursor object into an array of all the matching records. Probably the most convenient way to retrieve results but be careful with large datasets as every record is loaded into memory. toArray

The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date. Return Date

```<code>var collection = db.collection('test');
collection.find({ "date": { $gte: new Date("2017-04-11"), $lt: new Date("2017-04-13") } })
  .toArray(function (err, doc) {
    console.log("date function called");
    if (err) {
      console.error(err);
    } else {
      console.log(doc);
      res.json(doc);
    }
  });
</code>```

Body:
db.test.find({"date":{$gte:"2017-04-11",$lt:"2017-04-13"}},function(err,doc){
      console.log("date function called");
    res.json(doc);

    console.log(doc);
});

code works fine in mongodb and output,but in nodejs the output is empty array.

Body:
Collections can be queried with find.  The result for the query is actually a cursor object. This can be used directly or converted to an array. Making queries with find()

cursor.toArray(function(err, docs){}) converts the cursor object into an array of all the matching records. Probably the most convenient way to retrieve results but be careful with large datasets as every record is loaded into memory. toArray

The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date. Return Date

var collection = db.collection('test');
collection.find({ "date": { $gte: new Date("2017-04-11"), $lt: new Date("2017-04-13") } })
  .toArray(function (err, doc) {
    console.log("date function called");
    if (err) {
      console.error(err);
    } else {
      console.log(doc);
      res.json(doc);
    }
  });


答:
According to your example in comment and clarification in the question body:

var text = $('.fc_img_tooltip_desc').text();
text = text.replace(/([^\s])cm/gi, '$1 cm
');
$('.fc_img_tooltip_desc').html(text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100cm
50X50cm
100X100cm</div></code>```

This code is runnable. Is this what you want to achieve?

The 2nd version according to the requirements change in comments:

var text = $('.fc_img_tooltip_desc').text();
text = text.replace('cm', 'cm');
$('.highlight').html(text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc_img_tooltip_desc" style="line-height:1em;">
20X10cm
10X100
50X50
100X100
</div>
<span class="highlight"></span></code>```

FYI: your JS example has 3 obvious flaws. 1: the function (highlight_words) signature has 2 parameters, but you call the function without any. 2: The 2 signature parameters aren't used in the function body, hence the question - why do you need this signature? 3: the 'keywords' is undefined - not in function body, neither out of the function, thus causing JS warnings and never passing the if (keywords) condition. These are general programming issues that have nothing to do with your specific issue, but with basic programming experience. You may need to practice (or/and read about) some more basic programming tasks than manipulate DOM.

Title: Select specifics characters with jquery

Body:
According to your example in comment and clarification in the question body:

var text = $('.fc_img_tooltip_desc').text();
text = text.replace(/([^\s])cm/gi, '$1 cm<br />');
$('.fc_img_tooltip_desc').html(text);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100cm
50X50cm
100X100cm</div>

This code is runnable. Is this what you want to achieve?

The 2nd version according to the requirements change in comments:

var text = $('.fc_img_tooltip_desc').text();
text = text.replace('cm', '<span>cm</span>');
$('.highlight').html(text);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc_img_tooltip_desc" style="line-height:1em;">
20X10cm
10X100
50X50
100X100
</div>
<span class="highlight"></span>

FYI: your JS example has 3 obvious flaws. 1: the function (highlight_words) signature has 2 parameters, but you call the function without any. 2: The 2 signature parameters aren't used in the function body, hence the question - why do you need this signature? 3: the 'keywords' is undefined - not in function body, neither out of the function, thus causing JS warnings and never passing the if (keywords) condition. These are general programming issues that have nothing to do with your specific issue, but with basic programming experience. You may need to practice (or/and read about) some more basic programming tasks than manipulate DOM.


问:
Why does an equality check in Ruby behave this way with an OR expression?
I came across something like this in some specs at work today. A service was checking if a param was either "true" as a String or true as a TrueClass. It looked legit to me, but I found that it only evaluated to true when the supplied param value was the same as the first element in the OR.

A simplified example below:

5 == (5 || 6) evaluates to true

5 == (6 || 5) evaluates to false

Why?

答:
Everything is truthy in Ruby, except nil and false. So as others have mentioned, 5 || 6 is just 5.

I suppose that with :

```<code>5 == (6 || 5)
# => false
</code>```

you actually meant to write

```<code>[5, 6].include? 5
# => true
</code>```

Body:
Everything is truthy in Ruby, except nil and false. So as others have mentioned, 5 || 6 is just 5.

I suppose that with :

5 == (6 || 5)
# => false

you actually meant to write

[5, 6].include? 5
# => true


问:
Issues with angular links
hello I am have this issue with angular and I don't know how to resolve it,

```<code><td><a href="#!/repo/{{searchValue}}/{{repo.name}}">{{repo.name}}</a></td>
</code>```

I have this in my view and have the route defined here

```<code>(function(){
   var git = angular.module("main", ["ngRoute"]);
   git.config(function($routeProvider){
   $routeProvider
     .when("/main", {
        templateUrl: "main.html",
        controller: "MainCtrl"
      })
      .when("/user/:username", {
        templateUrl: "user.html",
        controller: "userController"
      })
      .when("/repo/:username/:reponame", {
        templateUrl: "repo.html",
        controller: "repoController"
      })
      .otherwise({redirectTo: "/main"});
  });
}());
</code>```

but any time I follow a click the link the url that show is http://localhost/plunk/#!/main#%2Fuser%2Fangular, for some reasons the "/" is replaced with "%2F" and the url that is loaded is the otherwise url, but if I do, http://localhost/plunk/#!/user/angular it works fine, pls how can I resolve this

答:
Generally, %2F is the percent-encoding for the forward-slash / character.Inorder to fix include $locationProvider.hashPrefix(''); in your config.

You could do,

```<code>git.config(['$locationProvider','$routeProvider', function($locationProvider,$routeProvider) {
  $locationProvider.hashPrefix('');
}]);
</code>```

Title: Issues with angular links

Body:
hello I am have this issue with angular and I don't know how to resolve it,

{{repo.name}}

I have this in my view and have the route defined here

(function(){
   var git = angular.module("main", ["ngRoute"]);
   git.config(function($routeProvider){
   $routeProvider
     .when("/main", {
        templateUrl: "main.html",
        controller: "MainCtrl"
      })
      .when("/user/:username", {
        templateUrl: "user.html",
        controller: "userController"
      })
      .when("/repo/:username/:reponame", {
        templateUrl: "repo.html",
        controller: "repoController"
      })
      .otherwise({redirectTo: "/main"});
  });
}());

but any time I follow a click the link the url that show is http://localhost/plunk/#!/main#%2Fuser%2Fangular, for some reasons the "/" is replaced with "%2F" and the url that is loaded is the otherwise url, but if I do, http://localhost/plunk/#!/user/angular it works fine, pls how can I resolve this

Body:
Generally, %2F is the percent-encoding for the forward-slash / character.Inorder to fix include $locationProvider.hashPrefix(''); in your config.

You could do,

git.config(['$locationProvider','$routeProvider', function($locationProvider,$routeProvider) {
  $locationProvider.hashPrefix('');
}]);


问:
Browsers cannot read javascript file
I'm developing an app for the iPad in which I'm building an html file for a webview. I'm using several javascript files which I'm copying out of my resource bundle to the app's temp directory.

When I try to bring this html file up, the javascript is throwing errors. It seems that any browser sees every linked resource as a string of chinese characters. I've looked in the error consoles of Safari, Chrome and FireFox.

https://skitch.com/jwwest/ryyat/5a898706-961e-49f0-9b98-cbbcd66127f1-9932-0000eb81e81473ef.html

If I pull these files up in TextMate or any other editor, they load fine.

This is definitely a file encoding problem. The same problem occurred by loading the html up on my windows machine. Opening it up in Notepad++, I notice that it's being saved as 'UCS-2 Little Endian' after resaving it as ANSI, the Javascript runs fine. Still no idea why it's saved this way after specifying nsutf8stringencoding.

答: The problem turned out to be simply a mismatch of encodings. While the html files were being saved as ANSI, I was trying to read them as UTF8. By switching to saving and reading as UTF8, the issue disappeared.</p>

Title: Browsers cannot read javascript file


问:
How to split a directory containing N folders in 2 directories containing N/2 folders each
I have a directory which contains 50.0000 folders. I want to split it into 2 directories. Each directory will contain 25.0000 folders.

How can I do it in python ?

答:
You can iterate over the folders using

os.walk("/path/to/folders")

iterate over the first half of the folders contained in the root folder and use shutil.move("directory_to_move","destination_directory") to move the "directory_to_move" into "destination_directory"

you will have to import both the os module and shutil

Checkout shutil and os.walk for guidance.


问:
Setting divider location on a JSplitPane
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

```<code>public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }
</code>```

I get this:

Can someone help me?
Thanks.

答:
The documentation of the setDividerLocation(double proportionalLocation) method says:

If the split pane is not correctly realized and on screen, this method
  will have no effect (new divider location will become (current size *
  proportionalLocation) which is 0).

What you can do instead is using the setDividerLocation(int location) method like this:

```<code>sp.setDividerLocation(300);
sp2.setDividerLocation(600);
</code>```

Body:
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }

I get this:

Can someone help me?
Thanks.

Body:
The documentation of the setDividerLocation(double proportionalLocation) method says:

If the split pane is not correctly realized and on screen, this method
  will have no effect (new divider location will become (current size *
  proportionalLocation) which is 0).

What you can do instead is using the setDividerLocation(int location) method like this:

sp.setDividerLocation(300);
sp2.setDividerLocation(600);


问:
I made a bubble sort for a list in c and I want to know if I made any particular mistakes
It seems to work,but I want to know if a particular situation would make my algorithm crash.Does anyone have any ideas of hidden particular cases,that my program would not cover?
I know it's not the proper way to sort a list,but this is what I had to do.

```<code>struct Student {
    float medie;
    char nrMatricol[10];
    char *nume;
    char facltate[6];

};
struct Nod{
    Student stud;
    Nod* next;
};
Nod* inserareNodEnd(Nod *l,Student st)
{
    Nod *nou = (Nod*)malloc(sizeof(Nod));
    nou->next = NULL;//NOU->NEXT=0
    nou->stud = st;
    if (!l) {
        //lista este goala
        return nou;
    }
    else
    {
     //lista contine un nod
        Nod *t = l;
        while (t->next) {
            t = t->next;
        }
        t->next = nou;
        return l;
    }

}

Nod * interschimbare(Nod *l, Nod *pred) {
    Nod *aux=l;
    //Nod *auxPred = pred;
    //Nod *auxPredNext =pred->next;
    if (pred) {
        //caz general
        Nod *p, *q, *r;
        pred = pred->next;
        q = p->next;
        r = q->next;
        pred->next = q;
        p->next = r;
        q->next = p;
    }
    else {
        //interschimb noduri 1 cu 2
        Nod *p, *q;
        p = l->next;
        q = p->next;
        l->next = q;
        l = p;

    }
    return l;
}
Nod* sortareBubble(Nod* l) {
char dinNou; // flag interschimb noduri

if (!l && !l->next)
    return l; //lista trebuie sa contina cel putin 2 noduri

do {
    dinNou = 0; // 0 -> ipoteza fara interschimb
    Nod *tmp = l, *pred = 0;
    while (tmp->next) {
        if (tmp->stud.medie > tmp->next->stud.medie) {
            l = interschimb(l, pred);
            dinNou = 1;
            if (pred) {
                pred = pred->next;
            }
            else {
                pred = l;
            }
        }
        else {
            pred = tmp;
            tmp = tmp->next;
        }
    }

} while (dinNou == 1);

return l;
</code>```

}

答:
You use dinNou (again) to check whether you need to enter again into the cycle. The cycle is a do-while and dinNou is initialized with 0 and if a change occurs, then it will be modified to 1. Essentially, you do the change until there was no change. You have a mistake leading to an inifite loop at

```<code>while (tmp->next);
</code>```

This will be false if tmp (which was initialized to l) happens to have no next element. Otherwise it will repeatedly ask whether there is a next element and since there is no change, it will always be true, leading to an infinite loop. What you did want in my opinion is to use the block following the while as the operation set to be done while tmp has next. To achieve that, simply remove the semi-colon:

```<code>while (tmp->next)
</code>```

After you do that, inside the loop you check whether the average mark of the current student is greater than the next. If so, then you call interschimbare (swap) and set dinNou to 1. This also seems to be incorrect. If the two neighboring values have to be swapped, then interschimbare of tmp and tmp->next should be called. As a result, you do not really need the pred variable and you will need to set tmp to tmp->next regardless of whether a swap was done or not. Or even better, you can break the loop if a swap occurred.

Body:
It seems to work,but I want to know if a particular situation would make my algorithm crash.Does anyone have any ideas of hidden particular cases,that my program would not cover?
I know it's not the proper way to sort a list,but this is what I had to do.

struct Student {
    float medie;
    char nrMatricol[10];
    char *nume;
    char facltate[6];

};
struct Nod{
    Student stud;
    Nod* next;
};
Nod* inserareNodEnd(Nod *l,Student st)
{
    Nod *nou = (Nod*)malloc(sizeof(Nod));
    nou->next = NULL;//NOU->NEXT=0
    nou->stud = st;
    if (!l) {
        //lista este goala
        return nou;
    }
    else
    {
     //lista contine un nod
        Nod *t = l;
        while (t->next) {
            t = t->next;
        }
        t->next = nou;
        return l;
    }

}

Nod * interschimbare(Nod *l, Nod *pred) {
    Nod *aux=l;
    //Nod *auxPred = pred;
    //Nod *auxPredNext =pred->next;
    if (pred) {
        //caz general
        Nod *p, *q, *r;
        pred = pred->next;
        q = p->next;
        r = q->next;
        pred->next = q;
        p->next = r;
        q->next = p;
    }
    else {
        //interschimb noduri 1 cu 2
        Nod *p, *q;
        p = l->next;
        q = p->next;
        l->next = q;
        l = p;

    }
    return l;
}
Nod* sortareBubble(Nod* l) {
char dinNou; // flag interschimb noduri

if (!l && !l->next)
    return l; //lista trebuie sa contina cel putin 2 noduri

do {
    dinNou = 0; // 0 -> ipoteza fara interschimb
    Nod *tmp = l, *pred = 0;
    while (tmp->next) {
        if (tmp->stud.medie > tmp->next->stud.medie) {
            l = interschimb(l, pred);
            dinNou = 1;
            if (pred) {
                pred = pred->next;
            }
            else {
                pred = l;
            }
        }
        else {
            pred = tmp;
            tmp = tmp->next;
        }
    }

} while (dinNou == 1);

return l;

}

Body:
You use dinNou (again) to check whether you need to enter again into the cycle. The cycle is a do-while and dinNou is initialized with 0 and if a change occurs, then it will be modified to 1. Essentially, you do the change until there was no change. You have a mistake leading to an inifite loop at

while (tmp->next);

This will be false if tmp (which was initialized to l) happens to have no next element. Otherwise it will repeatedly ask whether there is a next element and since there is no change, it will always be true, leading to an infinite loop. What you did want in my opinion is to use the block following the while as the operation set to be done while tmp has next. To achieve that, simply remove the semi-colon:

while (tmp->next)

After you do that, inside the loop you check whether the average mark of the current student is greater than the next. If so, then you call interschimbare (swap) and set dinNou to 1. This also seems to be incorrect. If the two neighboring values have to be swapped, then interschimbare of tmp and tmp->next should be called. As a result, you do not really need the pred variable and you will need to set tmp to tmp->next regardless of whether a swap was done or not. Or even better, you can break the loop if a swap occurred.


问:
Variable initialisation in JavaScript
```<code>var foo = {n: 1};
foo.x = foo = {a: 2};
console.log(foo.x);
// Output -- undefined

var a = 1;
c = b = a;
console.log(a,b,c);
// Output -- 1, 1, 1
</code>```

Could you please explain why first example returns undefined where as second returns 1,1,1?

答:
That's because the {a:2} object is actually being assigned to the {n:1}.x property! Not to {a:2}. There is no "x" property in it.

What we have here is:

```<code>var foo = {n:1};
foo.x = foo = {a:2}; // equals:...
{n:1}.x = {a:2};
/* note that foo.x is actually referring to {n:1} object! */
foo = {a:2}; // ==>
/* while foo is being pointed to a different object
   which is now the {a:2} object!
   wherefore ...*/
{a:2}.x   // is normally undefined i.e.: never set!
</code>```

However:

```<code>{n:1}.x // has been successfully assigned with:
>> {a:2} object.
</code>```

But because you are loosing a reference to the object {n:1}, and have no other way to examine it. In order to verify and prove that it is {n:1} who is actually receiving the property "x", we'll have to give it a backup  reference before we overwrite the foo variable in order to be able to return it.

```<code>var foo = {n:1};
var bak = foo;
foo.x=foo={a:2};

console.log(foo.x);
console.log(bak.x);

>> undefined
>> {a:2}.
</code>```

Title: Variable initialisation in JavaScript

Body:
var foo = {n: 1};
foo.x = foo = {a: 2};
console.log(foo.x);
// Output -- undefined

var a = 1;
c = b = a;
console.log(a,b,c);
// Output -- 1, 1, 1

Could you please explain why first example returns undefined where as second returns 1,1,1?

Body:
That's because the {a:2} object is actually being assigned to the {n:1}.x property! Not to {a:2}. There is no "x" property in it.

What we have here is:

var foo = {n:1};
foo.x = foo = {a:2}; // equals:...
{n:1}.x = {a:2};
/* note that foo.x is actually referring to {n:1} object! */
foo = {a:2}; // ==>
/* while foo is being pointed to a different object
   which is now the {a:2} object!
   wherefore ...*/
{a:2}.x   // is normally undefined i.e.: never set!

However:

{n:1}.x // has been successfully assigned with:
>> {a:2} object.

But because you are loosing a reference to the object {n:1}, and have no other way to examine it. In order to verify and prove that it is {n:1} who is actually receiving the property "x", we'll have to give it a backup  reference before we overwrite the foo variable in order to be able to return it.

var foo = {n:1};
var bak = foo;
foo.x=foo={a:2};

console.log(foo.x);
console.log(bak.x);

>> undefined
>> {a:2}.


问:
Javascript + Browser - How to detect when dev tools / firebug is open?
Before anyone of you starts saying it's impossible, please navigate to facebook.com open the devtools, even in non attached mode, and it will tell you that dev tools is opened, right?

So how is facebook able to pull that off?

I am able to do it for attached windows

```<code>window.outerHeight - window.innerHeight > 200 || window.outerWidth - window.innerWidth > 200
</code>```

But when the window is popped up, this doesn't work.

How is facebook able to pull this off?

答:
I think what facebook has done is just logged the warning in Console.
Below is the code that worked for me in Chrome.
I disabled 3 ways I know to start Developer Tool in Chrome:

Right Click and select Inspect option: For this, I disabled Right Click

F12 Key Press: blocked this event's default behavior

Ctrl + Shift + I: blocked all Ctrl default behavior

See, if you can afford this.

```<code>document.onkeydown = function(event) {
    if(event.code == "F12" || event.ctrlKey) {
        event.preventDefault();
    }
}
document.addEventListener('contextmenu', event => event.preventDefault());
</code>```

Body:
Before anyone of you starts saying it's impossible, please navigate to facebook.com open the devtools, even in non attached mode, and it will tell you that dev tools is opened, right?

So how is facebook able to pull that off?

I am able to do it for attached windows

window.outerHeight - window.innerHeight > 200 || window.outerWidth - window.innerWidth > 200

But when the window is popped up, this doesn't work.

How is facebook able to pull this off?

Body:
I think what facebook has done is just logged the warning in Console.
Below is the code that worked for me in Chrome.
I disabled 3 ways I know to start Developer Tool in Chrome:

Right Click and select Inspect option: For this, I disabled Right Click

F12 Key Press: blocked this event's default behavior

Ctrl + Shift + I: blocked all Ctrl default behavior

See, if you can afford this.

document.onkeydown = function(event) {
    if(event.code == "F12" || event.ctrlKey) {
        event.preventDefault();
    }
}
document.addEventListener('contextmenu', event => event.preventDefault());


问:
Grouped line charts using pandas and matplotlib
I have a dataset like this:

DataSet image

DataSet can be found here: https://ucr.fbi.gov/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/1tabledatadecoverviewpdf/table_1_crime_in_the_united_states_by_volume_and_rate_per_100000_inhabitants_1994-2013.xls

And i want to plot line chart containing line for every crime rate by year.
Something like this:
Crime Rate graph

But the graph shows continuous years on x-axis like 2005.5 2007.5.
Any one can help? or suggest a better approach to do this. Thanks

and here is the code:

```<code>%matplotlib inline
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import plotly.plotly as py
import seaborn as sns

cd =pd.read_clipboard() #after copying the dataset from given url above

        yearRate = cd[['Year','ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate']]
    # These are the "Tableau 20" colors as RGB.
    tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
                 (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
                 (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
                 (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
                 (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]
    for i in range(len(tableau20)):
        r, g, b = tableau20[i]
        tableau20[i] = (r / 255., g / 255., b / 255.)

    plt.figure(figsize=(20,15))
    ax = plt.subplot(111)

    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)

    plt.ylim(0,5000)
    plt.xlim(1994, 2013)

    plt.yticks(fontsize=14)
    plt.xticks(fontsize=14)

    for y in range(0, 5000, 1000):
        plt.plot(range(1994, 2013), [y] * len(range(1994, 2013)), "--", lw=0.5, color="black", alpha=0)

    rates=['ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate']

    for rank, column in enumerate(rates):
        # Plot each line separately with its own color, using the Tableau 20
        # color set in order.
        plt.plot(yearRate.Year.values,yearRate[column.replace("\n", " ")].values,lw=2.5, color=tableau20[rank])
        # Add a text label to the right end of every line. Most of the code below
        # is adding specific offsets y position because some labels overlapped.
        y_pos = yearRate[column.replace("\n", " ")].values[-1] - 0.5
        if column == "MotorVehicleTheftRate":
            y_pos -= 50
        elif column == "MurderRate":
            y_pos -= 50
        plt.text(2013, y_pos, column, fontsize=14, color=tableau20[rank])
</code>```

答:
Adding:

```<code>plt.xticks(cd['Year'])
</code>```

solved the issue.

Body:
I have a dataset like this:

DataSet image

DataSet can be found here: https://ucr.fbi.gov/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/1tabledatadecoverviewpdf/table_1_crime_in_the_united_states_by_volume_and_rate_per_100000_inhabitants_1994-2013.xls

And i want to plot line chart containing line for every crime rate by year.
Something like this:
Crime Rate graph

But the graph shows continuous years on x-axis like 2005.5 2007.5.
Any one can help? or suggest a better approach to do this. Thanks

and here is the code:

%matplotlib inline
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import plotly.plotly as py
import seaborn as sns

cd =pd.read_clipboard() #after copying the dataset from given url above

        yearRate = cd[['Year','ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate']]
    # These are the "Tableau 20" colors as RGB.
    tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
                 (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
                 (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
                 (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
                 (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]
    for i in range(len(tableau20)):
        r, g, b = tableau20[i]
        tableau20[i] = (r / 255., g / 255., b / 255.)

    plt.figure(figsize=(20,15))
    ax = plt.subplot(111)

    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)

    plt.ylim(0,5000)
    plt.xlim(1994, 2013)

    plt.yticks(fontsize=14)
    plt.xticks(fontsize=14)

    for y in range(0, 5000, 1000):
        plt.plot(range(1994, 2013), [y] * len(range(1994, 2013)), "--", lw=0.5, color="black", alpha=0)

    rates=['ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate']

    for rank, column in enumerate(rates):
        # Plot each line separately with its own color, using the Tableau 20
        # color set in order.
        plt.plot(yearRate.Year.values,yearRate[column.replace("\n", " ")].values,lw=2.5, color=tableau20[rank])
        # Add a text label to the right end of every line. Most of the code below
        # is adding specific offsets y position because some labels overlapped.
        y_pos = yearRate[column.replace("\n", " ")].values[-1] - 0.5
        if column == "MotorVehicleTheftRate":
            y_pos -= 50
        elif column == "MurderRate":
            y_pos -= 50
        plt.text(2013, y_pos, column, fontsize=14, color=tableau20[rank])

Body:
Adding:

plt.xticks(cd['Year'])

solved the issue.


问:
Access Label control inside the detailsview control
I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object."
can anyone guide me please.. ??
My front end code is:

```<code><asp:Panel ID="sub_question_panel" runat="server">
   <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6"    ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
   <Fields>
      <asp:TemplateField>
         <ItemTemplate>
               <table id="Question_view_table">
                  <tr>
<td style="font-family:Arial Rounded MT;">
<label id="Question_no"><span style="font-size:20px;">Question</span>:</label>
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label></td>
</tr>
<tr>
<td style="height:20px"></td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px; ">
<label id="Question_detail"><%# Eval ("Question") %></label>
</td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px;">
<ol style="list-style:upper-alpha">
<li>
<label id="optn1"> &nbsp&nbsp<%# Eval ("Option1") %></label></li>
<li>
<label id="optn2"> &nbsp&nbsp<%# Eval ("Option2") %></label></li>
<li>
<label id="optn3"> &nbsp&nbsp<%# Eval ("Option3") %></label></li>
<li>
<label id="optn4"> &nbsp&nbsp<%# Eval ("Option4") %></label></li>
</ol>
</td>
</tr>
            </table>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>
</code>```

My back end code is:

```<code>protected void Page_Load(object sender, EventArgs e)
{
      int question_id = 1;
      Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
      Question_Id .Text = Convert.ToString(question_id);
}
</code>```

答:
You must use the FindControl for a row, not DataListView

You want to find your label by id, But which one? For each row you have a label with id 'Ques_id_label' . So to find a specific label you must specify the intended row. I did not work with DataLisView but I know that it is logically similar to Asp:Repeater . To find a control in a row of a Repeater when a command is sent from a row:

```<code>protected void SaveAnswer(Object Sender, RepeaterCommandEventArgs e)
{
    Label Ques_id_label = (Label)e.Item.FindControl("Ques_id_label");
</code>```

Which with e.item you specify the intended row.

Body:
I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object."
can anyone guide me please.. ??
My front end code is:

<asp:Panel ID="sub_question_panel" runat="server">
   <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6"    ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
   <Fields>
      <asp:TemplateField>
         <ItemTemplate>

Question:
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label>

<%# Eval ("Question") %>

 &nbsp&nbsp<%# Eval ("Option1") %>

 &nbsp&nbsp<%# Eval ("Option2") %>

 &nbsp&nbsp<%# Eval ("Option3") %>

 &nbsp&nbsp<%# Eval ("Option4") %>

</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>

My back end code is:

protected void Page_Load(object sender, EventArgs e)
{
      int question_id = 1;
      Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
      Question_Id .Text = Convert.ToString(question_id);
}

Body:
You must use the FindControl for a row, not DataListView

You want to find your label by id, But which one? For each row you have a label with id 'Ques_id_label' . So to find a specific label you must specify the intended row. I did not work with DataLisView but I know that it is logically similar to Asp:Repeater . To find a control in a row of a Repeater when a command is sent from a row:

protected void SaveAnswer(Object Sender, RepeaterCommandEventArgs e)
{
    Label Ques_id_label = (Label)e.Item.FindControl("Ques_id_label");

Which with e.item you specify the intended row.


问:
i am stucking when i submitt my contact form
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!  </p>

```<code><?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>
</code>```

答:
You try sql below   </p>

```<code>      INSERT INTO enquiry_form(name,email,contact,message,courece,created_date,etime) VALUES (?,?,?,?,?,?,?)
if($stmt=$conn->prepare($q){
$stmt->bind_param('/dependent your datatype',$name,$email,$contact,...);
$stmt->execute();
echo "<script>
window.location.href='thank.php';
alert('Thank you');
</script>"
</code>```

<p>;
}</p>

Body:
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!

<?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>

Body:
You try sql below

      INSERT INTO enquiry_form(name,email,contact,message,courece,created_date,etime) VALUES (?,?,?,?,?,?,?)
if($stmt=$conn->prepare($q){
$stmt->bind_param('/dependent your datatype',$name,$email,$contact,...);
$stmt->execute();
echo "<script>
window.location.href='thank.php';
alert('Thank you');
</script>"

;
}


问:
Laravel Image Upload using ajax 500 Internal Server Error
I am trying to upload image using ajax in laravel 5.2.but still i am getting error 500 Internal Server Error in route.
when i am trying to  upload  image using ajax request the browser shown correct route path but still i am not getting reason why it still showing error to me.

HTML

```<code><!-- CHANGE AVATAR TAB -->
                        <div class="tab-pane" id="tab_1_2">

                            <div class="uploadimagediv"></div>
                                {{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage'))  }}

                                <div class="form-group">
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt=""/>
                                        </div>
                                        <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
                                        </div>
                                        <div>
                                            <span class="btn default btn-file">
                                            <span class="fileinput-new">
                                            Select image </span>
                                            <span class="fileinput-exists">
                                            Change </span>
                                            <p class="text-danger" id="error_image"></p>
                                            <input type="file" id="picture" name="picture"/>
                                            {{--{{ Form::file('picture') }}--}}
                                            </span>
                                            <span class="error alert-danger">{{ $errors->first('picture') }}</span>
                                            <a href="javascript:;" class="btn default fileinput-exists" data-dismiss="fileinput">
                                            Remove </a>
                                        </div>
                                    </div>
                                    <div class="clearfix margin-top-10">

                                    </div>
                                </div>
                                <div class="margin-top-10">
                                    {{Form::hidden('id', 2, ["id"=>"id"])}}
                                    {{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}

                                    {{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}
                                    <a href="javascript:;" class="btn default">
                                    Cancel </a>
                                </div>
                            {{ Form::close() }}
                        </div>
                        <!-- END CHANGE AVATAR TAB -->
</code>```

Route

```<code>Route::group(['prefix' => 'admin'], function ()
{
    Route::controller('/','DashboardController');
});
</code>```

Ajax

```<code>$(document).on('click', '#updatepicture', function($e)
{
    $e.preventDefault();
    // send an ajax request
    $("#error_image").empty();
    $.ajax(
    {

        url: 'avatar',
        processData: false,
        contentType: false,
        type: "post",//use for update
        data: new FormData($("#updateprofileimage")[0]),
        success: function(data)
        {
            if(data.status)
            {
                $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                window.setTimeout(function()
                {
                    $(".alert").fadeTo(500, 0).slideUp(500, function()
                    {
                        $(this).remove();
                    });
                }, 5000);
                $('.alert .close').on("click", function(e)
                {
                    $(this).parent().fadeTo(500, 0).slideUp(500);
                });
                //console.log(data);
                //$("#updateprofileimage")[0].reset();
                //window.location.href = "http://localhost/laravel/admin/profile";
            }
            else
            {
                errors = data.errors;

                for(error in errors)
                {
                    $("#error_"+error.title).html(error.message);
                }
            }
        },
        error: function(xhr)
        {
            if(xhr.status == 422)
            {
                errors = xhr.responseJSON;
                for(error in errors)
                {
                    $("#error_"+error).html(errors[error][0]);
                }
            }
        }
    });
});
</code>```

Error is :"NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar"

please suggest me where i am getting wrong.

Controller is

```<code>public function postAvatar(ImageUploadRequest $request)
{
  ---
}
</code>```

答:
In your ajax setup you have to provide x-csrf-token with the request. For your ajax request , also there is a problem with your url:</p>

```<code> $(document).on('click', '#updatepicture', function($e)
    {
        $e.preventDefault();
        // send an ajax request
        $("#error_image").empty();
        $.ajax(
        {

            url: "{{url('avatar')}}",
            processData: false,
            contentType: false,
            type: "post",//use for update
            data: new FormData($("#updateprofileimage")[0]),
            headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
            success: function(data)
            {
                if(data.status)
                {
                    $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                    window.setTimeout(function()
                    {
                        $(".alert").fadeTo(500, 0).slideUp(500, function()
                        {
                            $(this).remove();
                        });
                    }, 5000);
                    $('.alert .close').on("click", function(e)
                    {
                        $(this).parent().fadeTo(500, 0).slideUp(500);
                    });
                    //console.log(data);
                    //$("#updateprofileimage")[0].reset();
                    //window.location.href = "http://localhost/laravel/admin/profile";
                }
                else
                {
                    errors = data.errors;

                    for(error in errors)
                    {
                        $("#error_"+error.title).html(error.message);
                    }
                }
            },
            error: function(xhr)
            {
                if(xhr.status == 422)
                {
                    errors = xhr.responseJSON;
                    for(error in errors)
                    {
                        $("#error_"+error).html(errors[error][0]);
                    }
                }
            }
        });
    });
</code>```

Body:
I am trying to upload image using ajax in laravel 5.2.but still i am getting error 500 Internal Server Error in route.
when i am trying to  upload  image using ajax request the browser shown correct route path but still i am not getting reason why it still showing error to me.

HTML

                                {{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage'))  }}

                                            Select image

                                            Change

                                            <input type="file" id="picture" name="picture"/>
                                            {{--{{ Form::file('picture') }}--}}

                                            {{ $errors->first('picture') }}

                                            Remove

                                    {{Form::hidden('id', 2, ["id"=>"id"])}}
                                    {{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}

                                    {{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}

                                    Cancel

                            {{ Form::close() }}

Route

Route::group(['prefix' => 'admin'], function ()
{
    Route::controller('/','DashboardController');
});

Ajax

$(document).on('click', '#updatepicture', function($e)
{
    $e.preventDefault();
    // send an ajax request
    $("#error_image").empty();
    $.ajax(
    {

        url: 'avatar',
        processData: false,
        contentType: false,
        type: "post",//use for update
        data: new FormData($("#updateprofileimage")[0]),
        success: function(data)
        {
            if(data.status)
            {
                $("#uploadimagediv").html('
<button type="button" class="close">×</button>'+data.message+'
');
                window.setTimeout(function()
                {
                    $(".alert").fadeTo(500, 0).slideUp(500, function()
                    {
                        $(this).remove();
                    });
                }, 5000);
                $('.alert .close').on("click", function(e)
                {
                    $(this).parent().fadeTo(500, 0).slideUp(500);
                });
                //console.log(data);
                //$("#updateprofileimage")[0].reset();
                //window.location.href = "http://localhost/laravel/admin/profile";
            }
            else
            {
                errors = data.errors;

                for(error in errors)
                {
                    $("#error_"+error.title).html(error.message);
                }
            }
        },
        error: function(xhr)
        {
            if(xhr.status == 422)
            {
                errors = xhr.responseJSON;
                for(error in errors)
                {
                    $("#error_"+error).html(errors[error][0]);
                }
            }
        }
    });
});

Error is :"NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar"

please suggest me where i am getting wrong.

Controller is

public function postAvatar(ImageUploadRequest $request)
{
  ---
}

Body:
In your ajax setup you have to provide x-csrf-token with the request. For your ajax request , also there is a problem with your url:

 $(document).on('click', '#updatepicture', function($e)
    {
        $e.preventDefault();
        // send an ajax request
        $("#error_image").empty();
        $.ajax(
        {

            url: "{{url('avatar')}}",
            processData: false,
            contentType: false,
            type: "post",//use for update
            data: new FormData($("#updateprofileimage")[0]),
            headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
            success: function(data)
            {
                if(data.status)
                {
                    $("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
                    window.setTimeout(function()
                    {
                        $(".alert").fadeTo(500, 0).slideUp(500, function()
                        {
                            $(this).remove();
                        });
                    }, 5000);
                    $('.alert .close').on("click", function(e)
                    {
                        $(this).parent().fadeTo(500, 0).slideUp(500);
                    });
                    //console.log(data);
                    //$("#updateprofileimage")[0].reset();
                    //window.location.href = "http://localhost/laravel/admin/profile";
                }
                else
                {
                    errors = data.errors;

                    for(error in errors)
                    {
                        $("#error_"+error.title).html(error.message);
                    }
                }
            },
            error: function(xhr)
            {
                if(xhr.status == 422)
                {
                    errors = xhr.responseJSON;
                    for(error in errors)
                    {
                        $("#error_"+error).html(errors[error][0]);
                    }
                }
            }
        });
    });


问:
How do center an image within another image and have it responsive to mobile landscape?
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

```<code>.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}
</code>```

working, sort of. The HTML:

```<code><div class="parent">
<img class="image1" src="https://placehold.it/1"/ alt="1">
<img class="image2" src="https://placehold.it/2"/ alt="2">
</div>
</code>```

答:
I your first image dictate the size of the parent container, then you should position your images like this (for my code, I've use divs with fixed size. You could give your images display: block)

.parent {
  position: relative;
  border: 2px solid gray;
}

.child-1 {
  height:300px;
  width: 300px;
  background: lightgreen;
  margin: 0 auto;
}

.child-2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: salmon;
  height: 50px;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-1"></div>
  <div class="child-2"></div>
</div></code>```

Body:
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}

working, sort of. The HTML:

Body:
I your first image dictate the size of the parent container, then you should position your images like this (for my code, I've use divs with fixed size. You could give your images display: block)

.parent {
  position: relative;
  border: 2px solid gray;
}

.child-1 {
  height:300px;
  width: 300px;
  background: lightgreen;
  margin: 0 auto;
}

.child-2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: salmon;
  height: 50px;
  width: 50px;
}

<div class="parent">
  <div class="child-1"></div>
  <div class="child-2"></div>
</div>


问:
SOAP: looks like we got no XML document
I'm trying to create a web service but before I do I'm trying to get a simple example that I found on the internet to work first but I keep getting the following error:

```<code>Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document in C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php:20 Stack trace: #0 [internal function]: SoapClient->__call('getStockQuote', Array) #1 C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php(20): SoapClient->getStockQuote(Array) #2 {main} thrown in C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php on line 20
</code>```

I am using nusoap v1.94

My web service code looks like this:

```<code>function getStockQuote($symbol) {
$price = '1.23';
return $price;
}

require('nusoap.php');

$server = new soap_server();

$server->configureWSDL('stockserver', 'urn:stockquote');

$server->register("getStockQuote",
            array('symbol' => 'xsd:string'),
            array('return' => 'xsd:decimal'),
            'urn:stockquote',
            'urn:stockquote#getStockQuote');

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
                  ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
</code>```

I know one cause is to have whitespace before or after your php tags in your server script but thats not the case. It has been driving me mad for hours! Any help would be much appreciated.

答:
A byte order mark (BOM) would have the same effect as whitespace before the php tags.
Here you find a PHP snippet to detect and remove a BOM. Be sure to configure you editor to not insert the BOM again.</p>

Title: SOAP: looks like we got no XML document

Body:
I'm trying to create a web service but before I do I'm trying to get a simple example that I found on the internet to work first but I keep getting the following error:

Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document in C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php:20 Stack trace: #0 [internal function]: SoapClient->__call('getStockQuote', Array) #1 C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php(20): SoapClient->getStockQuote(Array) #2 {main} thrown in C:\Documents and Settings\geoff\My Documents\Websites\jquery\index.php on line 20

I am using nusoap v1.94

My web service code looks like this:

function getStockQuote($symbol) {
$price = '1.23';
return $price;
}

require('nusoap.php');

$server = new soap_server();

$server->configureWSDL('stockserver', 'urn:stockquote');

$server->register("getStockQuote",
            array('symbol' => 'xsd:string'),
            array('return' => 'xsd:decimal'),
            'urn:stockquote',
            'urn:stockquote#getStockQuote');

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
                  ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);

I know one cause is to have whitespace before or after your php tags in your server script but thats not the case. It has been driving me mad for hours! Any help would be much appreciated.


问:
onClick handler is triggered on each render cycle
I have default state like this

```<code>this.state = {
  selectedTab : 'tab1'
}
</code>```

then

My render method like this

```<code>render(){
   const { selectedTab } = this.state;
   return(
      <li>tab1</li><li>tab2</li>
      <div id="content">
         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}
      </div>
   )
}
</code>```

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

```<code><li onClick={this.setState({selectedTab :'tab1'})}>Tab 1</li>
<li onClick={this.setState({selectedTab :'someothertab'})}>Tab 2/li>
</code>```

Why?

答:
I will introduce concept of "higher order functions here".

Basicaly, higher order function is function returning another function.

Let's modify onClick handler and make it "higher order function".

```<code>// Original function
setActiveTab = (activeTab) => {
  this.setState({ activeTab });
}

// Higher order function
setActiveTab = (activeTab) => {
  // Here, we already "remember" name of tab which becomes active after click.
  // Return "true" `onClick` handler from this place.
  return () => {
    // Finaly set state after click.
    this.setState({ activeTab });
  }
}
</code>```

How will render function look like?

```<code><li onClick={this.setActiveTab('tab1')}>Tab 1</li>
<li onClick={this.setActiveTab('someothertab')}>Tab 2/li>
</code>```

Better, isn't it?

Body:
I have default state like this

this.state = {
  selectedTab : 'tab1'
}

then

My render method like this

render(){
   const { selectedTab } = this.state;
   return(

tab1

tab2

         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}

   )
}

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

Tab 1

Tab 2/li>

Why?

Body:
I will introduce concept of "higher order functions here".

Basicaly, higher order function is function returning another function.

Let's modify onClick handler and make it "higher order function".

// Original function
setActiveTab = (activeTab) => {
  this.setState({ activeTab });
}

// Higher order function
setActiveTab = (activeTab) => {
  // Here, we already "remember" name of tab which becomes active after click.
  // Return "true" `onClick` handler from this place.
  return () => {
    // Finaly set state after click.
    this.setState({ activeTab });
  }
}

How will render function look like?

<li onClick={this.setActiveTab('tab1')}>Tab 1</li>
<li onClick={this.setActiveTab('someothertab')}>Tab 2/li>

Better, isn't it?


答:
Just found it:
unset DEBUG fixed it !

Title: Disabling network logs on Kubernetes when running kubectl exec

Body:
Runnning kubectl exec -it <PODNAME> -- /bin/bash is printing a lot of trash of the shell:

) Data frame handling
                     I0331 17:46:15.486652    3807 logs.go:41] (0xc4201158c0) Data frame received for 5
                                                                                I0331 17:46:15.486671    3807 logs.go:41] (0xc42094a000) (5) Data frame handling
                                                                                I0331 17:46:15.486682    3807 logs.go:41] (0xc42094a000) (5) Data frame sent
                                                                                root@hello-node-2399519400-6q6s3:/# I0331 17:46:16.667823    3807 logs.go:41] (0xc420687680) (3) Writing data frame
                                                  I0331 17:46:16.669223    3807 logs.go:41] (0xc4201158c0) Data frame received for 5
                                                                                I0331 17:46:16.669244    3807 logs.go:41] (0xc42094a000) (5) Data frame handling
                                                                                I0331 17:46:16.669254    3807 logs.go:41] (0xc42094a000) (5) Data frame sent

root@hello-node-2399519400-6q6s3:/# I0331 17:46:17.331753    3807 logs.go:41] (0xc420687680) (3) Writing data frame
                                                                                I0331 17:46:17.333338    3807 logs.go:41] (0xc4201158c0) Data frame received for 5
                                                                                I0331 17:46:17.333358    3807 logs.go:41] (0xc42094a000) (5) Data frame handling
                                                                                I0331 17:46:17.333369    3807 logs.go:41] (0xc42094a000) (5) Data frame sent

I0331 17:46:17.333922    3807 logs.go:41] (0xc4201158c0) Data frame received for 5
                                                                                I0331 17:46:17.333943    3807 logs.go:41] (0xc42094a000) (5) Data frame handling
                                                                                I0331 17:46:17.333956    3807 logs.go:41] (0xc42094a000) (5) Data frame sent
                                                                                root@hello-node-2399519400-6q6s3:/# I0331 17:46:17.738444    3807 logs.go:41] (0xc420687680) (3) Writing data frame
                             I0331 17:46:17.740563    3807 logs.go:41] (0xc4201158c0) Data frame received for 5
                                                                                I0331 17:46:17.740591    3807 logs.go:41] (0xc42094a000) (5) Data frame handling
                                                                                I0331 17:46:17.740606    3807 logs.go:41] (0xc42094a000) (5) Data frame sent

It is a little bit better without 't' option:

kubectl exec -i hello-4103519535-hcdm6 -- /bin/bash
I0331 18:29:06.918584    4992 logs.go:41] (0xc4200878c0) (0xc4204c5900) Create stream
I0331 18:29:06.918714    4992 logs.go:41] (0xc4200878c0) (0xc4204c5900) Stream added, broadcasting: 1
I0331 18:29:06.928571    4992 logs.go:41] (0xc4200878c0) Reply frame received for 1
I0331 18:29:06.928605    4992 logs.go:41] (0xc4200878c0) (0xc4203ffc20) Create stream
I0331 18:29:06.928614    4992 logs.go:41] (0xc4200878c0) (0xc4203ffc20) Stream added, broadcasting: 3
I0331 18:29:06.930565    4992 logs.go:41] (0xc4200878c0) Reply frame received for 3
I0331 18:29:06.930603    4992 logs.go:41] (0xc4200878c0) (0xc4204c59a0) Create stream
I0331 18:29:06.930615    4992 logs.go:41] (0xc4200878c0) (0xc4204c59a0) Stream added, broadcasting: 5
I0331 18:29:06.932455    4992 logs.go:41] (0xc4200878c0) Reply frame received for 5
I0331 18:29:06.932499    4992 logs.go:41] (0xc4200878c0) (0xc420646000) Create stream
I0331 18:29:06.932511    4992 logs.go:41] (0xc4200878c0) (0xc420646000) Stream added, broadcasting: 7
I0331 18:29:06.935363    4992 logs.go:41] (0xc4200878c0) Reply frame received for 7
echo toto
I0331 18:29:08.943066    4992 logs.go:41] (0xc4203ffc20) (3) Writing data frame
I0331 18:29:08.947811    4992 logs.go:41] (0xc4200878c0) Data frame received for 5
I0331 18:29:08.947837    4992 logs.go:41] (0xc4204c59a0) (5) Data frame handling
I0331 18:29:08.947851    4992 logs.go:41] (0xc4204c59a0) (5) Data frame sent
toto

Is there a way to disable that?
Would it come from my environment ?
I am still not sure if it comes from Kubernetes or my environment actually.

Body:
Just found it:
unset DEBUG fixed it !


问:
Does "server side rendering" mean two sides rendering?
Need some clear understanding... When we do server side rendering the app actually renders twice.

1) with renderToString function on server.

2) with render function on client (when page came from server).

And the whole point of React server side rendering is to use SEO.

Am I right or do I miss something ? Tnx

答:
Server side rendering is a technique to deliver the rendered data to the client, while retaining the ability to use variable bindings. This can be faster or slower, depending on the amount of the data.

There's almost zero duplicated code executed. The code delivered to client side will migrate the rendered state calculated by the server to the structure that the browser can process (which is identical to a loaded client-side rendered page).


问:
How to change only color of text in tabhost in android?
I am trying to write style for this. I am facing problem of how to get Text Color in style.</p>

答:
```<code>tabHost.setOnTabChangedListener(new OnTabChangeListener() {

    @Override
    public void onTabChanged(String tabId) {

        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); // unselected
            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); //Unselected Tabs
            tv.setTextColor(Color.parseColor("#ffffff"));
        }

        tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
        TextView tv = (TextView) tabhost.getCurrentTabView().findViewById(android.R.id.title); //for Selected Tab
        tv.setTextColor(Color.parseColor("#000000"))

    }
});
</code>```

To set text color initially in your activity, you can use this code in onResume() function

```<code>TabHost tabhost = getTabHost();
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
    TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
    tv.setTextColor(Color.parseColor("#000000"));
}
</code>```

Body:
tabHost.setOnTabChangedListener(new OnTabChangeListener() {

    @Override
    public void onTabChanged(String tabId) {

        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); // unselected
            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); //Unselected Tabs
            tv.setTextColor(Color.parseColor("#ffffff"));
        }

        tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
        TextView tv = (TextView) tabhost.getCurrentTabView().findViewById(android.R.id.title); //for Selected Tab
        tv.setTextColor(Color.parseColor("#000000"))

    }
});

To set text color initially in your activity, you can use this code in onResume() function

TabHost tabhost = getTabHost();
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
    TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
    tv.setTextColor(Color.parseColor("#000000"));
}


问:
Cannot read property 'style' of null - Google Sign-In Button
I'm trying to implement Google sign in for my website. The Sign-In button shows up correctly and signs-people in well initially. My problem occurs when I log out after having used the website and try to move to the Sign-In page (I'm using React, so it's all one page). I use the exact same function to render the Sign-In page but it gives me a "cb=gapi.loaded_0:249 Uncaught TypeError: Cannot read property 'style' of null". The error in gapi occurs here (at least I think):

```<code> a.El;window.document.getElementById((c?"not_signed_in":"connected"
</code>```

This is how I initially add the Sign-In button to be rendered:

```<code>elements.push(h('div.g-signin2',{'data-onsuccess': 'onSignIn'}))
        return h('div.page_content',elements)
</code>```

which I later render with a ReactDOM.render call.

Here's how I handle SignOut and SignIn:

```<code>function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      // console.log('User signed out.');
      signedin = false;
      auth2 = null;
      renderPage()
    });
  }

var google_idtoken;
var signedin = false;

// set auth2 to null to indicate that google api hasn't been loaded yet
var auth2 = null;

function onSignIn(googleUser) {
    auth2 = gapi.auth2.getAuthInstance({
        client_id: 'ClientID.apps.googleusercontent.com'
    });
    google_idtoken = googleUser.getAuthResponse().id_token;
    wrongemail = true;
  // if(auth2 != null && auth2.isSignedIn.get() == true){

    if ((((auth2.currentUser.get()).getBasicProfile()).getEmail()).split("@").pop() == 'domain.com'){
        signedin = true
        wrongemail = false
    }
    updateSources()
    // renderPage()
}
</code>```

答: I fixed this by giving a different id to each of my sign-in buttons. For instance, you may have sign-in button on your register page and login page. Give each instance of the button its own id.</p>

Body:
I'm trying to implement Google sign in for my website. The Sign-In button shows up correctly and signs-people in well initially. My problem occurs when I log out after having used the website and try to move to the Sign-In page (I'm using React, so it's all one page). I use the exact same function to render the Sign-In page but it gives me a "cb=gapi.loaded_0:249 Uncaught TypeError: Cannot read property 'style' of null". The error in gapi occurs here (at least I think):

 a.El;window.document.getElementById((c?"not_signed_in":"connected"

This is how I initially add the Sign-In button to be rendered:

elements.push(h('div.g-signin2',{'data-onsuccess': 'onSignIn'}))
        return h('div.page_content',elements)

which I later render with a ReactDOM.render call.

Here's how I handle SignOut and SignIn:

function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      // console.log('User signed out.');
      signedin = false;
      auth2 = null;
      renderPage()
    });
  }

var google_idtoken;
var signedin = false;

// set auth2 to null to indicate that google api hasn't been loaded yet
var auth2 = null;

function onSignIn(googleUser) {
    auth2 = gapi.auth2.getAuthInstance({
        client_id: 'ClientID.apps.googleusercontent.com'
    });
    google_idtoken = googleUser.getAuthResponse().id_token;
    wrongemail = true;
  // if(auth2 != null && auth2.isSignedIn.get() == true){

    if ((((auth2.currentUser.get()).getBasicProfile()).getEmail()).split("@").pop() == 'domain.com'){
        signedin = true
        wrongemail = false
    }
    updateSources()
    // renderPage()
}


问:
How to create table for a generalized class diagram?
I am developing a online job portal website. In class diagram I generalized Employer & Employee as Members class & I put 'MID' as primary key. Now I am confused how to create tables for Employer & Employee?</p>

答:
Here is tables you required:</p>

```<code>Member
========
Id (or MId) (PK)
... (Specifications you need)

Employer
========
Id (PK)
MId (FK to Member table)
... (Specifications you need)

Employee
========
Id (PK)
MId (FK to Member table)
EId (FK to Employer table)
... (Specifications you need)
</code>```

Body:
Here is tables you required:

Member
========
Id (or MId) (PK)
... (Specifications you need)

Employer
========
Id (PK)
MId (FK to Member table)
... (Specifications you need)

Employee
========
Id (PK)
MId (FK to Member table)
EId (FK to Employer table)
... (Specifications you need)