问:
Creating Chat App with MySql, php ,w/o GCM
I wanna make Chat App using MySql And Php , But in Syria  I can't use GCM
is there any alternative way to do it? (Not Firebase , or quickblox )
Thanks in advance .. </p>

答:
Take a look at ajax technology, you can build a full web-based chat system, and use Javascript interface to communicate with your app, so that you can notify your app user there is a new message.

BTW, you can modify your question title like Creating Chat App with MySql, php, w/o GCM


来源: stackexchange

问:
Binding onchange event using JS (Syntax error)
I've recently been spending some time playing with javascript event listeners in an attempt to learn a little more. However I've kinda hit a road block.

I appear to be getting a syntax error, SyntaxError: expected expression, got keyword 'if'.

The Question

If someone could elaborate and explain my mistake to me, I would be thankful. See the Js Fiddle for a more complete example of what I'm tryign to accomplish.

I've attempted to read up a bit more using MDN (This Article Imparticular) as highlighted by the console. However I'm failing to understand, my error and how it coinsides with this article.

```<code>function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }

}

function myFunction()
</code>```

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.

EDIT TUE 4 JULY

I ended up completely reworking this to try and get things a little smoother. With some help from you all I was able to clarify I few things.

especially the key points highlighted by, @Kind User & @Shaminder S Aujla.

You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

Calling it like myFunction(); will throw "Too much recursion error".

The resulting change is shown below and you can also see my finished fiddle here;

```<code>window.addEventListener('load', function() {

  // Select Element
  var c = document.getElementById('dept');
  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Bind onchange event.
  c.onchange = function() {

    if (this.options[this.selectedIndex].value == 3) {
      a.disabled = false;
      a.placeholder = 'Enter Your Full Name.';
    } else {
      a.disabled = true;
      a.placeholder = 'Not Applicable.';
    }
  }
})
</code>```

Thanks again all,
really appreciate it. :)

Regards,
- B.

答:
You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

```<code>function myFunction() {

   var a = document.getElementsByName('field-one')[0];

   var b = document.getElementById('box-2');

   var c = document.getElementById('dept');

   c.setAttribute('onchange', myFunction);

   if (b.checked) {
     a.disabled = false;
     a.placeholder = 'Enter Your Full Name.';
   } else {
     a.disabled = true;
     a.placeholder = 'Not Applicable.';
 }

}

myFunction();
</code>```

function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction); // semicolon + don't call it

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }
}

myFunction(); // call the func```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Open+Sans');
* {
  margin: 0;
  padding: 0;
}

h3 {
  color: #fff !important;
  padding-left: 0 !important;
}

#txt-field {
  position: relative;
  height: 100vh;
}

#col {
  width: 40%;
  margin: 0 auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.spacer {
  margin-bottom: .5em;
}

.original {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url(http://imageshack.com/a/img661/3954/bwalqa.jpg);
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.txt {
  font-family: "Open Sans", Arial, Helvetica, sans-serif !important;
  font-weight: 200 !important;
  letter-spacing: 4px !important;
  font-size: 26px !important;
  text-transform: uppercase;
  color: #272727;
  padding: .5em;
}

.stretch {
  box-sizing: border-box;
  width: 100%;
}

.shift {
  margin-top: 9%;
}

.boxes {
  box-sizing: border-box;
  width: 100%;
  margin: auto;
  padding: 1.5em;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0%, rgba(0, 0, 0, 0.6) 100%);
  margin-top: 1.5em;
}

/*Checkboxes styles*/

input[type="checkbox"] {
  display: none;
}

input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 20px;
  font: 14px/20px 'Open Sans', Arial, sans-serif;
  color: #ddd;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

input[type="checkbox"] + label:last-child {
  margin-bottom: 0;
}

input[type="checkbox"] + label:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid #6cc0e5;
  position: absolute;
  left: 0;
  top: 0;
  opacity: .6;
  -webkit-transition: all .12s, border-color .08s;
  transition: all .12s, border-color .08s;
}

input[type="checkbox"]:checked + label:before {
  width: 10px;
  top: -5px;
  left: 5px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

.selectpicker {
  margin: 3em 3em;
}</code>```

  <select title="Please Select" class="selectpicker" name="dept" id="dept" required="true">
    <option value="">Choose...</option>
    <option value="1">Winter</option>
    <option value="2">Spring</option>
    <option value="3">Summer</option>
    <option value="4" selected="selected">Autumn</option>
  </select>

Dynamic input, based on checkbox state...

    <input type="text" name="field-one" class="txt stretch" />

      <input type="checkbox" id="box-2" onChange="myFunction()" checked>
      Apply a name?

```

ContentLicense: CC BY-SA 3.0

Body:
I've recently been spending some time playing with javascript event listeners in an attempt to learn a little more. However I've kinda hit a road block.

I appear to be getting a syntax error, SyntaxError: expected expression, got keyword 'if'.

The Question

If someone could elaborate and explain my mistake to me, I would be thankful. See the Js Fiddle for a more complete example of what I'm tryign to accomplish.

I've attempted to read up a bit more using MDN (This Article Imparticular) as highlighted by the console. However I'm failing to understand, my error and how it coinsides with this article.

function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }

}

function myFunction()

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.

EDIT TUE 4 JULY

I ended up completely reworking this to try and get things a little smoother. With some help from you all I was able to clarify I few things.

especially the key points highlighted by, @Kind User & @Shaminder S Aujla.

You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

Calling it like myFunction(); will throw "Too much recursion error".

The resulting change is shown below and you can also see my finished fiddle here;

window.addEventListener('load', function() {

  // Select Element
  var c = document.getElementById('dept');
  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Bind onchange event.
  c.onchange = function() {

    if (this.options[this.selectedIndex].value == 3) {
      a.disabled = false;
      a.placeholder = 'Enter Your Full Name.';
    } else {
      a.disabled = true;
      a.placeholder = 'Not Applicable.';
    }
  }
})

Thanks again all,
really appreciate it. :)

Regards,
- B.

Body:
You have used comma instead of semicolon.

If you want to call the function, use just the name of the function.

Don't call the function while binding it.

function myFunction() {

   var a = document.getElementsByName('field-one')[0];

   var b = document.getElementById('box-2');

   var c = document.getElementById('dept');

   c.setAttribute('onchange', myFunction);

   if (b.checked) {
     a.disabled = false;
     a.placeholder = 'Enter Your Full Name.';
   } else {
     a.disabled = true;
     a.placeholder = 'Not Applicable.';
 }

}

myFunction();

function myFunction() {

  // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');

  // Select Element
  var c = document.getElementById('dept');

  // Bind onchange event.
  c.setAttribute('onchange', myFunction); // semicolon + don't call it

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }
}

myFunction(); // call the func

@import url('https://fonts.googleapis.com/css?family=Open+Sans');
* {
  margin: 0;
  padding: 0;
}

h3 {
  color: #fff !important;
  padding-left: 0 !important;
}

#txt-field {
  position: relative;
  height: 100vh;
}

#col {
  width: 40%;
  margin: 0 auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.spacer {
  margin-bottom: .5em;
}

.original {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url(http://imageshack.com/a/img661/3954/bwalqa.jpg);
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.txt {
  font-family: "Open Sans", Arial, Helvetica, sans-serif !important;
  font-weight: 200 !important;
  letter-spacing: 4px !important;
  font-size: 26px !important;
  text-transform: uppercase;
  color: #272727;
  padding: .5em;
}

.stretch {
  box-sizing: border-box;
  width: 100%;
}

.shift {
  margin-top: 9%;
}

.boxes {
  box-sizing: border-box;
  width: 100%;
  margin: auto;
  padding: 1.5em;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0%, rgba(0, 0, 0, 0.6) 100%);
  margin-top: 1.5em;
}

/*Checkboxes styles*/

input[type="checkbox"] {
  display: none;
}

input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 20px;
  font: 14px/20px 'Open Sans', Arial, sans-serif;
  color: #ddd;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

input[type="checkbox"] + label:last-child {
  margin-bottom: 0;
}

input[type="checkbox"] + label:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid #6cc0e5;
  position: absolute;
  left: 0;
  top: 0;
  opacity: .6;
  -webkit-transition: all .12s, border-color .08s;
  transition: all .12s, border-color .08s;
}

input[type="checkbox"]:checked + label:before {
  width: 10px;
  top: -5px;
  left: 5px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

.selectpicker {
  margin: 3em 3em;
}

<div id="txt-field" class="original box">

  <select title="Please Select" class="selectpicker" name="dept" id="dept" required="true">
    <option value="">Choose...</option>
    <option value="1">Winter</option>
    <option value="2">Spring</option>
    <option value="3">Summer</option>
    <option value="4" selected="selected">Autumn</option>
  </select>

  <div id="col">

    <h3 class="txt spacer">Dynamic input, based on checkbox state...</h3>
    <input type="text" name="field-one" class="txt stretch" />

    <div class="boxes">
      <input type="checkbox" id="box-2" onChange="myFunction()" checked>
      <label for="box-2">Apply a name?</label>
    </div>
  </div>
</div>


问:
How to make custom shape (arrow on the sides pointing outwards) of a button?
I want to make my button look like the following. Can you please tell me, how to make a drawable xml file for the following?

like this image

答: If it were only the shape maybe a vector drawable would be enough, but to draw shape, icon and text, better to create your own Button class and draw things in the overriden onDraw. The shape can be drawn using a Path.</p>


问:
How to calculate scrolling speed of RecyclerView
I want to calculate the speed (in pixel/millis) for a recyclerView. Currently I am overriding onScrolled(RecyclerView recyclerView, int dx, int dy) and dividing the dx or dy by the time difference between current call to the method and last call to the method.

The speed that I get is generally correct, but there are peaks locally. Sudden increase and decrease in speed. Although to a human eye speed seems pretty smooth.

Should I follow some different approach? Any suggestions are welcome.

Image of the speed graph. This is when I fling the recyclerView.

答:
I would suggest the method you have used is your best option. The localised peaks will be a result of variation in painting/assigning recyclerview list items. Both your Android phone and Android application are running a myriad of processes at once. This will result in minor increases and decreases in your chart line at seemingly arbitrary points.

As you noted the human eye cannot see these differences though, so I would not concern yourself with them, your data will be correct.


问:
Getting the Device Token when tapping the "Don't Allow" button for Push Notification
I have a bit of difficulty getting the device token when the user tapped the "Don't Allow" Button.

I can only get the Device Token when tapping the "OK" button. -- i have no problem with this one

Here is the note from the UIApplication.h

```<code>[application registerForRemoteNotifications];
</code>```

// Calling this will result in either
  application:didRegisterForRemoteNotificationsWithDeviceToken: or
  application:didFailToRegisterForRemoteNotificationsWithError: to be
  called on the application delegate.

Note: these callbacks will be made only if the application has
  successfully registered for user notifications with
  registerUserNotificationSettings:, or if it is enabled for Background
  App Refresh.

? does this note means that if you select the "Don't Allow" button you can never get the device token ?

答:
It does not really matter, what action you choose in the permission popup for Push Notifications, the device token will anyways be obtained everytime and the only difference that user choice makes is that, it enables/disables the notification in the phone Settings.

And this behaviour is ideal. For an example:-

When user clicks on Dont Allow, if no device token is fetched and later on if user turn on the notification from the phone settings , then how are you going to send the deivice token to the server?
You will have to register for remote notification once again which is very weird.

I hope you understood.

Body:
I have a bit of difficulty getting the device token when the user tapped the "Don't Allow" Button.

I can only get the Device Token when tapping the "OK" button. -- i have no problem with this one

Here is the note from the UIApplication.h

[application registerForRemoteNotifications];

// Calling this will result in either
  application:didRegisterForRemoteNotificationsWithDeviceToken: or
  application:didFailToRegisterForRemoteNotificationsWithError: to be
  called on the application delegate.

Note: these callbacks will be made only if the application has
  successfully registered for user notifications with
  registerUserNotificationSettings:, or if it is enabled for Background
  App Refresh.

? does this note means that if you select the "Don't Allow" button you can never get the device token ?


问:
Javascript regex matching syntax not working
I would like to test a string to ensure it has the following pattern:

```<code>asas/asas2/asas
</code>```

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

```<code>var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);
</code>```

The above code example always returns false.

答:
You just have to remove quotes.

var str = 'dfdfdf/dfdf/dfdf';
var patt = /(^\w+\/\w+\/\w+$)/g;
var res = patt.test(str);
alert(res);```

Body:
I would like to test a string to ensure it has the following pattern:

asas/asas2/asas

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);

The above code example always returns false.


问:
CMAKE_BUILD_TYPE Release: strange results
We are creating an Android app to compare execution time between ART and native code. We are using Android Studio and CMake for compiling C/C++.

When in CMakeList.txt we set the flag

```<code>set(CMAKE_BUILD_TYPE Release)
</code>```

in some algorithms (Primality Test and Fibonacci) the execution time drastically drop to 0ms for all different input.

Here the native lib

```<code>bool flag = false;

extern "C" JNIEXPORT void JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_cancel(JNIEnv *env, jobject obj) {
        flag = true;
    }

extern "C" JNIEXPORT jlong JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_primalityTest(JNIEnv *env, jobject obj, jlong r) {
    if(r < 0) return -1L;
    timeval start, stop;
    long long t;
    gettimeofday(&start, NULL);

    bool prime = true;

    unsigned long long sr = (unsigned long long) sqrt(r);
    for (unsigned long long i = 2; (i <   sr) && prime; i++) {
        if (flag) return -1;
        if (r % i == 0) prime = false;
    }

    gettimeofday(&stop, NULL);
    t = (stop.tv_sec - start.tv_sec) * 1000;
    t += (long long) ((stop.tv_usec - start.tv_usec) / 1000)
    return (jlong) t;
    }
</code>```

flag is a flag that is set true when we terminate the asyncTask that execute the algorithm.

I can not figure how this is possible. Any suggestion? Thank you.

答:
This is because by default your CMake project is build with Debug type. In this type the debugging information is generated as well as optimisations are disabled (-O0 -g flags to gcc).

This is to enable you to step trough your C++ code line by line as it was written by you. If you change the type to Release the optimisations are turned on and the debug info is not included with the binary.

The optimisations make the code run so fast, no matter how well you think you wrote something, the compiler is still ahead of you and will make it better. Those optimisations however will show erratic behaviour when the code is debugged, lines executed out of order, or not at all, variables not showing in watches or shown wrong, this is not nice for debugging.

The missing debug info means the binary is lighter but if you need to debug it better practice some assembly since any information on what line of C++ resulted in these assembly instructions is lost. As a side note there is also RelWithDebugInfo build type in case you really need to debug the optimised code.

Normally the Android Studio should take care of the appropriate build type for you so there is no need to fiddle with that.

Body:
We are creating an Android app to compare execution time between ART and native code. We are using Android Studio and CMake for compiling C/C++.

When in CMakeList.txt we set the flag

set(CMAKE_BUILD_TYPE Release)

in some algorithms (Primality Test and Fibonacci) the execution time drastically drop to 0ms for all different input.

Here the native lib

bool flag = false;

extern "C" JNIEXPORT void JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_cancel(JNIEnv *env, jobject obj) {
        flag = true;
    }

extern "C" JNIEXPORT jlong JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_primalityTest(JNIEnv *env, jobject obj, jlong r) {
    if(r < 0) return -1L;
    timeval start, stop;
    long long t;
    gettimeofday(&start, NULL);

    bool prime = true;

    unsigned long long sr = (unsigned long long) sqrt(r);
    for (unsigned long long i = 2; (i <   sr) && prime; i++) {
        if (flag) return -1;
        if (r % i == 0) prime = false;
    }

    gettimeofday(&stop, NULL);
    t = (stop.tv_sec - start.tv_sec) * 1000;
    t += (long long) ((stop.tv_usec - start.tv_usec) / 1000)
    return (jlong) t;
    }

flag is a flag that is set true when we terminate the asyncTask that execute the algorithm.

I can not figure how this is possible. Any suggestion? Thank you.


问:
RODBC ERROR: 'Calloc' could not allocate memory
I am setting up a SQL Azure database. I need to write data into the database on daily basis. I am using 64-bit R version 3.3.3 on Windows10. Some of the columns contain text (more than 4000 characters). Initially, I have imported some data from a csv into the SQL Azure database using Microsoft SQL Server Management Studios. I set up the text columns as ntext format, because when I tried using nvarchar the max was 4000 and some of the values got truncated even though they were about 1100 characters long.

In order to append to the database I am first saving the records in a temp table when I have predefined the varTypes:

```<code>varTypesNewFile <- c("Numeric", rep("NTEXT", ncol(newFileToAppend) - 1))
names(varTypesNewFile) <- names(newFileToAppend)
sqlSave(dbhandle, newFileToAppend, "newFileToAppendTmp", rownames = F, varTypes = varTypesNewFile, safer = F)
</code>```

and then append them by using:

```<code>insert into mainTable select * from newFileToAppendTmp
</code>```

If the text is not too long, the above does work. However, sometimes I get the following error during the sqlSave command:

```<code>Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  :
'Calloc' could not allocate memory (1073741824 of 1 bytes)
</code>```

My questions are:

How can I counter this issue?

Is this the format I should be using?

Additionally, even when the above works, it takes about an hour to upload about 5k of records. Is it not too long? Is this the normal amount of time it should take? If not, what could I do better.

答: RODBC is very old, and can be a bit flaky with NVARCHAR columns. Try using the RSQLServer package instead, which offers an alternative means to connect to SQL Server (and also provides a dplyr backend).</p>

Body:
I am setting up a SQL Azure database. I need to write data into the database on daily basis. I am using 64-bit R version 3.3.3 on Windows10. Some of the columns contain text (more than 4000 characters). Initially, I have imported some data from a csv into the SQL Azure database using Microsoft SQL Server Management Studios. I set up the text columns as ntext format, because when I tried using nvarchar the max was 4000 and some of the values got truncated even though they were about 1100 characters long.

In order to append to the database I am first saving the records in a temp table when I have predefined the varTypes:

varTypesNewFile <- c("Numeric", rep("NTEXT", ncol(newFileToAppend) - 1))
names(varTypesNewFile) <- names(newFileToAppend)
sqlSave(dbhandle, newFileToAppend, "newFileToAppendTmp", rownames = F, varTypes = varTypesNewFile, safer = F)

and then append them by using:

insert into mainTable select * from newFileToAppendTmp

If the text is not too long, the above does work. However, sometimes I get the following error during the sqlSave command:

Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  :
'Calloc' could not allocate memory (1073741824 of 1 bytes)

My questions are:

How can I counter this issue?

Is this the format I should be using?

Additionally, even when the above works, it takes about an hour to upload about 5k of records. Is it not too long? Is this the normal amount of time it should take? If not, what could I do better.


问:
What does <bdi> do?
I'm aware that its for text that runs in the opposite direction of the rest of the page, but I'm not fully understanding what it does. Does it just mark it so the browser knows its running in the opposite direction? If so why does the browser benefit from knowing this? Also what is the "surrounding text", is it literally just the text around it, its getting compared to or is it getting compared to the lang attribute?</p>

```<code><p>this is text going from left to right <bdi>opposite running text</bdi></p>
</code>```

答:
The BDI tag(bidirectional isolation) isolates a span of text that might be formatted in a different direction from other text outside it.

This resource has some data for you to read.

http://html.com/tags/bdi/

Title: What does <bdi> do?

Body:
I'm aware that its for text that runs in the opposite direction of the rest of the page, but I'm not fully understanding what it does. Does it just mark it so the browser knows its running in the opposite direction? If so why does the browser benefit from knowing this? Also what is the "surrounding text", is it literally just the text around it, its getting compared to or is it getting compared to the lang attribute?

this is text going from left to right <bdi>opposite running text</bdi>


问:
What is the difference between ng build and webpack
As I understand it, ng-build creates a distributable packaged version of your application. I also understand that webpack is used to bundle Javascript modules.

I ran ng build on a test project and found that it created a dist folder containing what looked like a packaged version of my Angular application. All of the .js files had been combined however my referenced .css files had been left in the original form (not bundled or minified).

Therefore, what is the difference between using ng build or webpack to do this job. Or are they complimentary? Would I potentially use both in my deployment pipeline?

答:
Not a complete answer, but worth to note:

If your css files were not compiled, it probably means, either:

you ran ng build (a.k.a. ng build --dev) which adds default --extract-css to false:

--extract-css (aliases: -ec)

Extract css from global styles onto css files instead of js ones.

You ran ng build --prod but forgot to reference your styles as global styles in angular.cli.json:

"styles": [
    "styles.css",
    "assets/styles/test.component.css"
  ],

Once you do this you will find your css files inlined, however, you will also find them in normal format as well. Cant understand why is that..


问:
Please explain powershell script error on specific code line
I have getting error on this below line in .ps1 file.

Code:

```<code>Import-Csv $csvPath `| ? { $_.Datum -ne $date } `| Export-Csv $csvTempPath -NoTypeInformation
</code>```

Error:

```<code>Import-Csv : A positional parameter cannot be found that accepts argument '?'.
</code>```

答:
I have solved problem. It is spacing issue, i have added one space between tilde and pipe sign.

```<code>Import-Csv $csvPath ` | ? { $_.Datum -ne $date } ` | Export-Csv $csvTempPath -NoTypeInformation
</code>```

Now it is works fine. Thanks!

Body:
I have getting error on this below line in .ps1 file.

Code:

Import-Csv $csvPath `| ? { $_.Datum -ne $date } `| Export-Csv $csvTempPath -NoTypeInformation

Error:

Import-Csv : A positional parameter cannot be found that accepts argument '?'.

Body:
I have solved problem. It is spacing issue, i have added one space between tilde and pipe sign.

Import-Csv $csvPath ` | ? { $_.Datum -ne $date } ` | Export-Csv $csvTempPath -NoTypeInformation

Now it is works fine. Thanks!


答:
You are missing semi-colon (;). Remove the comma and replace it with a semi-colon.
Look at this working fiddle.
 That Should be

```<code>// Bind onchange event.
  c.setAttribute('onchange', myFunction());
</code>```

and remove the last line i.e

function myFunction()

EDIT

Remove this line.

```<code>c.setAttribute('onchange', myFunction());
</code>```

Call the funtion at the end like

```<code>myFunction();
</code>```

Keep the inline binding i.e onchange="myFunction()"

Title: Binding onchange event using JS (Syntax error)

Body:
You are missing semi-colon (;). Remove the comma and replace it with a semi-colon.
Look at this working fiddle.
 That Should be

// Bind onchange event.
  c.setAttribute('onchange', myFunction());

and remove the last line i.e

function myFunction()

EDIT

Remove this line.

c.setAttribute('onchange', myFunction());

Call the funtion at the end like

myFunction();

Keep the inline binding i.e onchange="myFunction()"


问:
deploy rails app on heroku
Hey
I'm afraid I should ask a rookie question :

After push my app to heroku. I got error of no database

This is the command I use

heroku rake db:migrate

My app can run locally with no problem, but I notice the database file only in development.
and my test evironment only use rails server and localhost:3000

anyone tell me how to make the database in production mode in heroku.

Thanks

here's the heroku log file:

here's the logs

Started GET "/drummers/1" for
  221.9.247.14 at Sat Dec 18 06:17:40 -0800 2010  Processing by DrummersController#show as HTML
  Parameters: {"id"=>"1"}  Completed in
  167ms

ActiveRecord::RecordNotFound (Couldn't
  find Drummer with ID=1):
  app/controllers/drummers_controller.rb:11:in
  `show'

I think it may due to the datebase,config file, become I use sqlite3 in local test, and all the migration file is development prefix,

答: I believe Heroku creates a new database.yml for you on deploy if you have no production according to the Docs.</p>

ContentLicense: CC BY-SA 2.5

Title: deploy rails app on heroku


问:
Rest Api Best practice - Passing date as query param
I am writing a rest service using NodeJs and express middleware. I have below questions -

I have to take userid and token for authentication in every service irrespective of the method type i.e. GET, POST, PUT and DELETE. What is the best way to take these two param i.e  as request header or query param? I don't want to take it as body params since the get requests wouldn't have the body.

I want to write a service with method type GET for data retrieval, the params for this call are string and a date. How shoule I pass the params as query parameter for this, specifically the date param should i pass it as js date or any other format?

```<code>GET - https://localhost:someport/<objectid>/<createddate>
headers - x-user-id:someid
          x-access-token:sometoken
</code>```

if this then which format the created date should be passed.

or should I use the below one?

```<code>GET - https://localhost:someport/
headers - x-user-id:someid
          x-access-token:sometoken
          x-object-id:someid
          x-created-date:somedate
</code>```

答:
The best practices for a rest API design says that expose the parameters which are not sensitive user information to get request as query params. So user id and token like things should go in header and other things can go in get request params.

Choose the first one which has only user id and token in headers.

Body:
I am writing a rest service using NodeJs and express middleware. I have below questions -

I have to take userid and token for authentication in every service irrespective of the method type i.e. GET, POST, PUT and DELETE. What is the best way to take these two param i.e  as request header or query param? I don't want to take it as body params since the get requests wouldn't have the body.

I want to write a service with method type GET for data retrieval, the params for this call are string and a date. How shoule I pass the params as query parameter for this, specifically the date param should i pass it as js date or any other format?

GET - https://localhost:someport/<objectid>/<createddate>
headers - x-user-id:someid
          x-access-token:sometoken

if this then which format the created date should be passed.

or should I use the below one?

GET - https://localhost:someport/
headers - x-user-id:someid
          x-access-token:sometoken
          x-object-id:someid
          x-created-date:somedate


答:
Here's the updated fiddle:
https://jsfiddle.net/9fzqegso/26/

You have at least 2 issues

1) this must end with a semi colon:

Incorrect:

```<code>  c.setAttribute('onchange', myFunction()),
</code>```

Corrected:

```<code>  c.setAttribute('onchange', myFunction());
</code>```

2) Function must have a body:

Incorrect:

```<code>function myFunction()
</code>```

Corrected:

```<code>function myFunction(){
//future codes here

}
</code>```

I moved this codes into the function (myFunction) for it to work:

```<code>    // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');
    if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }
</code>```

Body:
Here's the updated fiddle:
https://jsfiddle.net/9fzqegso/26/

You have at least 2 issues

1) this must end with a semi colon:

Incorrect:

  c.setAttribute('onchange', myFunction()),

Corrected:

  c.setAttribute('onchange', myFunction());

2) Function must have a body:

Incorrect:

function myFunction()

Corrected:

function myFunction(){
//future codes here

}

I moved this codes into the function (myFunction) for it to work:

    // Text field element.
  var a = document.getElementsByName('field-one')[0];

  // Checkbox element.
  var b = document.getElementById('box-2');
    if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }


问:
Reading excel sheet from same workbook using nodejs
I am new to nodejs, i wanted to know how it is possible to read different excel sheets from excel workbook(.xlsx) using nodejs.
I tried to use excel module of nodejs to read excel file, but using it i can only read the first sheet of that  workbook. please help!!
thank you</p>

答:
```<code>var spread_sheet = require('spread_sheet');

var row = "1,2,Jack,Pirate";

var filePath = '/home/Pranjal/Desktop/test.xlsx';

var sheetName = "Sheet1";

var from_row  = 2;

var to_row = 6;

/*
spread_sheet.addRow(row,filePath,sheetName,function(err,result){

console.log(err,result)

})
*/

/*
spread_sheet.getRows(filePath,sheetName,from_row,to_row,function(err,result){

console.log(err,result)
*/
</code>```


问:
Do i require to Submit a verfication request for the following google drive scopes in order to download a file from picker?
Do i require to Submit a verification request for the following google drive scopes in order to download a file from picker?

googleapis.com/auth/drive

www.googleapis.com/auth/drive.readonly

The picker doesn't load due to the following error

My objective is to download a file from google drive to our website.

The picker loads when i use drive.file, but when i try to download the file i get a 404 file not found error.

using the google drive reference files/get on there site i can simulate the 404 but if i change the scope to using just drive or drive.readonly i get a 200 status which is what i'm after but the picker does not load.

Is there a way around this without having to submit a verification request form?

The code i'm using is based of google drive sample code.

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Picker Example</title>

```

答: First, I suggest using the https://www.googleapis.com/auth/drive to have full scope. Then, show us what the code, how are you doing it?</p>


问:
syntax error while specifying DOCTYPE
I am getting a syntax error while using the DOCTYPE  ...
actually  i have a base page and loading two iframes in it , and the doctype is specifyed in one of these iframes ..
I have some php codes before starting the html code ...

The firebug error is shown below

Thanks in advance

答: You seem to be outputting a raw \n after the doctype, probably caused by a PHP echo statement.

Title: syntax error while specifying DOCTYPE


问:
Class 'App\Eloquent' not found in laravel after running php artisan db:seed
```<code><?php

namespace App;

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface
{

}
</code>```

答:
Your model should extend the Model class:

```<code>use Illuminate\Database\Eloquent\Model;
class User extends Model
</code>```

If you want to use Laravel authentication system, it should extend Illuminate\Foundation\Auth\User:

```<code>use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
</code>```

Body:
Your model should extend the Model class:

use Illuminate\Database\Eloquent\Model;
class User extends Model

If you want to use Laravel authentication system, it should extend Illuminate\Foundation\Auth\User:

use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable


问:
Java URL Connection strange behavior on https URLs
```<code>    public class URLConnectionReader {
        public static void main(String[] args) throws Exception {
            URL urlObj = new URL("https://www.paypal.com"); // enter url here
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int code = connection.getResponseCode();
            System.out.println(code);
        }
}
</code>```

I am creating a URL Tester which checks if URL is working or not .above is my code. when I test it with https://www.paypal.com it returns 200 and when I test it with https://www.facebook.com it throws exception.
Below is the exception stack trace

```<code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
    at URLConnectionReader.main(URLConnectionReader.java:27)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
    ... 11 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)

at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 17 more
</code>```

can anybody please explain me why https://www.paypal.com returns 200 but https://www.facebook.com throws exception.

答:
The problem here is that Java by default comes with a very limited set
  of root CA certificates. It "accepts" far fewer CAs than a typical
  browser. The simplest way to solve the problem is to export a set of
  CA certificates from a browser like Chrome or Firefox and import them
  into Java's keystore using keytool.

ref

Body:
    public class URLConnectionReader {
        public static void main(String[] args) throws Exception {
            URL urlObj = new URL("https://www.paypal.com"); // enter url here
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int code = connection.getResponseCode();
            System.out.println(code);
        }
}

I am creating a URL Tester which checks if URL is working or not .above is my code. when I test it with https://www.paypal.com it returns 200 and when I test it with https://www.facebook.com it throws exception.
Below is the exception stack trace

Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
    at URLConnectionReader.main(URLConnectionReader.java:27)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
    ... 11 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)

at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 17 more

can anybody please explain me why https://www.paypal.com returns 200 but https://www.facebook.com throws exception.


问:
Strange output with Array.filter() method
In the code below I expected the result of destroyer([1, 2, 3, 1, 2, 3], 2, 3); would be [1,1].

But the result pops out to be [1,2,3,1,2,3].

Where am I going wrong?

```<code>function destroyer(arr) {
  function hlp(x) {
    for(var i=1; i<arguments.length ; i++) {
      if(x == arguments[i]) return false;
    }
    return true;
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
</code>```

答:
You can use ES6 rest parameter syntax and check if array includes any of those parameters using include()

function destroyer(arr, ...rest) {
  function hlp(e) {
    return !rest.includes(e)
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));```
</div>
</div>
</p>

<p>If you want to use <code>for</code> loop and <code>arguments</code> your code should look like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function destroyer(arr) {
  var arg = arguments

  function hlp(x) {
    for (var i = 1; i < arg.length; i++) {
      if (x == arg[i]) return false;
    }
    return true;
  }
  return arg[0].filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));</code>```

Body:
In the code below I expected the result of destroyer([1, 2, 3, 1, 2, 3], 2, 3); would be [1,1].

But the result pops out to be [1,2,3,1,2,3].

Where am I going wrong?

function destroyer(arr) {
  function hlp(x) {
    for(var i=1; i<arguments.length ; i++) {
      if(x == arguments[i]) return false;
    }
    return true;
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

Body:
You can use ES6 rest parameter syntax and check if array includes any of those parameters using include()

function destroyer(arr, ...rest) {
  function hlp(e) {
    return !rest.includes(e)
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

If you want to use for loop and arguments your code should look like this.

function destroyer(arr) {
  var arg = arguments

  function hlp(x) {
    for (var i = 1; i < arg.length; i++) {
      if (x == arg[i]) return false;
    }
    return true;
  }
  return arg[0].filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));


问:
Bootstrap 3 grid boxes should take free vertical space
Actually I am working with bootstrap 3.3.6 and want to achive following with the bootstrap grid system:

The boxes are all in the same
 tag and i want that the box 4 takes the available space on the left side below the box 1.

The jsfiddle https://jsfiddle.net/byrd9wx2/

I know how to do this with normal html + css but not with bootstrap.

Thanks for your help!

答:
You can achieve this using Bootstrap grid system by reordering Box2 & Box3 and floating those to right.

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

 .content-box {
  border: 2px solid black;
  padding: 2px;
}

.mainbody{
  padding: 50px;
}

.box-spacing{
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="mainbody">
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing pull-right">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing pull-right">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat</div>
            </div>
        </div>
    </div>
</div>
</div></code>```

Body:
You can achieve this using Bootstrap grid system by reordering Box2 & Box3 and floating those to right.

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

 .content-box {
  border: 2px solid black;
  padding: 2px;
}

.mainbody{
  padding: 50px;
}

.box-spacing{
  margin-bottom: 20px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="mainbody">
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing pull-right">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing pull-right">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
            </div>
        </div>
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 box-spacing">
            <div class="content-box">
                <div style="background: yellow">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat</div>
            </div>
        </div>
    </div>
</div>
</div>


问:
Spring Secutiry retrieve Principal Object
I need to retrieve exactly Principal Object in non default Spring chain (not in controller with Principle injection). I'm implementing some interceptor with my spring-websocket and client to set user Principal from oauth header token value.

Main problem now is that I can't just directrly fetch Principal object instead I'm getting username String.

I've created this method but it returns String (getting ClassCastException):

```<code>public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
</code>```

答:
Try this:

```<code>public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
</code>```

And this will give you actual principal object that is currently logged in.
Keep in mind that UsernamePasswordAuthenticationToken contain principal object of type Object, so here you can set either UserDetail or Stringobject depending on your requirements

Body:
I need to retrieve exactly Principal Object in non default Spring chain (not in controller with Principle injection). I'm implementing some interceptor with my spring-websocket and client to set user Principal from oauth header token value.

Main problem now is that I can't just directrly fetch Principal object instead I'm getting username String.

I've created this method but it returns String (getting ClassCastException):

public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

Body:
Try this:

public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

And this will give you actual principal object that is currently logged in.
Keep in mind that UsernamePasswordAuthenticationToken contain principal object of type Object, so here you can set either UserDetail or Stringobject depending on your requirements


问:
Assigning a value to a variable after Firebase return result?
I've been struggling with this for 2 hours now. I'm building an app in Swift, using Firebase Database and storage.

The goal is to update User profile. The user has 2 images - Profile and header. Now, I have to first check if they've selected an image from the photo library, if not -  just get the old URL from the database and submit it back to the database with the rest of the updated information. If it's a new selected image, upload the image to the Storage, get back the URL using downloadURL assign it to the var storageHeaderDownloadedURL and/or var storageProfileDownloadedURL and submit the string values with the rest of the user data to Firebase Database.

The problem is that it obviously assigns the values of an empty String (I've declared them as such) BEFORE I get back the downloaded URL. If the user doesn't update the images but the rest of the UITextFields it all works, the old URL is submitted to the Firebase Database.

My question is how do I execute the downloaded URL methods for from the storage and then assign it to var storageHeaderDownloadedURL and var storageProfileDownloadedURL first hand?

```<code>func updateUserProfile ()
{
    if let userID = FIRAuth.auth()?.currentUser?.uid
    {
        // Note: Storage references to profile images & profile headers folder
        let storageUserProfileID = Storage.storage.profile_images.child(userID)
        let storageUserHeaderID = Storage.storage.profile_headers.child(userID)

        guard let imageProfile = profileImage.image else { return }

        guard let headerImage = headerImage.image else { return }

        if let newProfileImage = UIImagePNGRepresentation(imageProfile), let newHeaderImage = UIImagePNGRepresentation(headerImage)
            {
                storageUserProfileID.put(newProfileImage, metadata: nil, completion: { (metadata, error) in

                    if error != nil
                    {
                        showAlert(title: "Oops!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                        return
                    }
                    // Get the URL from the storage
                    storageUserProfileID.downloadURL(completion: { (url, error) in

                        if error != nil
                        {
                            showAlert(title: "Oops!!!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: nil)
                            return
                        }
                        else
                        {
                            if let profileImgDownloadedURL = url?.absoluteString
                            {
                                self.storageProfileDownloadedURL = profileImgDownloadedURL
                                print(self.storageProfileDownloadedURL)
                                self.selectedProfileImage = .True
                            }
                        }

                    })
                })
                storageUserHeaderID.put(newHeaderImage, metadata: nil, completion: { (metadata, error) in

                    if error != nil
                    {
                        showAlert(title: "Oops!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                        return
                    }

                    // Get the URL from the storage
                    storageUserHeaderID.downloadURL(completion: { (url, error) in

                        if error != nil
                        {
                            showAlert(title: "Oops!!!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                            return
                        }
                        else
                        {
                            if let headerImgDownloadedURL = url?.absoluteString
                            {
                                self.storageHeaderDownloadedURL = headerImgDownloadedURL
                                print(self.storageHeaderDownloadedURL)
                                self.selectedHeaderImage = .True
                            }
                        }
                    })
                })

        //Note: Update the info for that user in Database

        print(self.storageHeaderDownloadedURL)
        print(self.storageProfileDownloadedURL)

        var finalHeaderImageURL = String()

        switch self.selectedHeaderImage {

        case .True:
            finalHeaderImageURL = self.storageHeaderDownloadedURL
            break

        case .False:
            finalHeaderImageURL = self.oldHeaderImageInDB
            break

        }
        print(finalHeaderImageURL)

        var finalProfileImageURL = String()

        switch self.selectedProfileImage {

        case .True:
            finalProfileImageURL = self.storageProfileDownloadedURL
            break

        case .False:
            finalProfileImageURL = self.oldProfilePhotoImageInDB
            break

        }
        print(finalProfileImageURL)

        guard let newDisplayName = self.displayNameTextField.text else { return }
        guard let newLocation = self.locationTextField.text else { return }
        guard let newDescription = self.bioTextField.text else { return }
        guard let newWebsite = self.websiteTextField.text else { return }
        guard let newBirthday = self.birthdayTextField.text else { return }

        let newUpdatedUserDictionary = ["imageProfile": finalProfileImageURL,
                                        "imageHeader" : finalHeaderImageURL,
                                        "description" : newDescription,
                                        "location": newLocation,
                                        "displayName": newDisplayName,
                                        "website": newWebsite,
                                        "birthday": newBirthday,
                                        ]
        Database.dataService.updateUserProfile(uid: userID, user: newUpdatedUserDictionary)

        showAlert(title: "Hey", msg: "Your profile was updated", actionButton: "OK", viewController: self)
         } // Get new uploaded profile and header image URLs
    }
}
</code>```

The enums I use for the switch statements to determine if it's an old URL or a new one:

```<code> enum SelectedHeaderImage
 {
  case True
  case False
 }

 enum SelectedProfileImage
 {
 case True
 case False
 }
</code>```

Class outlets:

```<code>var storageProfileDownloadedURL = String()
var storageHeaderDownloadedURL = String()

var oldProfilePhotoImageInDB = String()
var oldHeaderImageInDB = String()

var selectedHeaderImage = SelectedHeaderImage.False
var selectedProfileImage = SelectedProfileImage.False`
</code>```

答:
From what I understood, your problem is with queuing. You want the code below to execute after the download is complete but it executes in its normal flow. If this is what your problem is then I would suggest you to create another enum, with three download states/count. And move that code below you want to be executed later in a function. Increment the state of new enum when download is complete. It would look something like this:

```<code>enum DownloadCount
{
    case Zero
    case One
    case Two
}
var downloadCount = DownloadCount.Zero
</code>```

and in each of the success block of your download complete change it to, I will just write one here to give you the idea of what needs to be done.

```<code>if let profileImgDownloadedURL = url?.absoluteString
{
     self.storageProfileDownloadedURL = profileImgDownloadedURL
     print(self.storageProfileDownloadedURL)
     self.selectedProfileImage = .True
     if(downloadCount == .Zero)
     {
         downloadCount = DownloadCount.One
     }
     else
     {
         downloadCount = DownloadCount.Two
     }
     self.newAssigningFunction()
}

func newAssigningFunction()
{
    if(downloadCount == .Two)
    {
        //Do your storage/saving work here
    }
}
</code>```

Also if you need to execute this function again, it would be best to set downloadCount back to Zero at start of your updateUserProfile function. Let me know if somethis is unclear or you need further help. Or if this was not your case.

Body:
I've been struggling with this for 2 hours now. I'm building an app in Swift, using Firebase Database and storage.

The goal is to update User profile. The user has 2 images - Profile and header. Now, I have to first check if they've selected an image from the photo library, if not -  just get the old URL from the database and submit it back to the database with the rest of the updated information. If it's a new selected image, upload the image to the Storage, get back the URL using downloadURL assign it to the var storageHeaderDownloadedURL and/or var storageProfileDownloadedURL and submit the string values with the rest of the user data to Firebase Database.

The problem is that it obviously assigns the values of an empty String (I've declared them as such) BEFORE I get back the downloaded URL. If the user doesn't update the images but the rest of the UITextFields it all works, the old URL is submitted to the Firebase Database.

My question is how do I execute the downloaded URL methods for from the storage and then assign it to var storageHeaderDownloadedURL and var storageProfileDownloadedURL first hand?

func updateUserProfile ()
{
    if let userID = FIRAuth.auth()?.currentUser?.uid
    {
        // Note: Storage references to profile images & profile headers folder
        let storageUserProfileID = Storage.storage.profile_images.child(userID)
        let storageUserHeaderID = Storage.storage.profile_headers.child(userID)

        guard let imageProfile = profileImage.image else { return }

        guard let headerImage = headerImage.image else { return }

        if let newProfileImage = UIImagePNGRepresentation(imageProfile), let newHeaderImage = UIImagePNGRepresentation(headerImage)
            {
                storageUserProfileID.put(newProfileImage, metadata: nil, completion: { (metadata, error) in

                    if error != nil
                    {
                        showAlert(title: "Oops!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                        return
                    }
                    // Get the URL from the storage
                    storageUserProfileID.downloadURL(completion: { (url, error) in

                        if error != nil
                        {
                            showAlert(title: "Oops!!!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: nil)
                            return
                        }
                        else
                        {
                            if let profileImgDownloadedURL = url?.absoluteString
                            {
                                self.storageProfileDownloadedURL = profileImgDownloadedURL
                                print(self.storageProfileDownloadedURL)
                                self.selectedProfileImage = .True
                            }
                        }

                    })
                })
                storageUserHeaderID.put(newHeaderImage, metadata: nil, completion: { (metadata, error) in

                    if error != nil
                    {
                        showAlert(title: "Oops!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                        return
                    }

                    // Get the URL from the storage
                    storageUserHeaderID.downloadURL(completion: { (url, error) in

                        if error != nil
                        {
                            showAlert(title: "Oops!!!", msg: (error?.localizedDescription)!, actionButton: "OK", viewController: self)
                            return
                        }
                        else
                        {
                            if let headerImgDownloadedURL = url?.absoluteString
                            {
                                self.storageHeaderDownloadedURL = headerImgDownloadedURL
                                print(self.storageHeaderDownloadedURL)
                                self.selectedHeaderImage = .True
                            }
                        }
                    })
                })

        //Note: Update the info for that user in Database

        print(self.storageHeaderDownloadedURL)
        print(self.storageProfileDownloadedURL)

        var finalHeaderImageURL = String()

        switch self.selectedHeaderImage {

        case .True:
            finalHeaderImageURL = self.storageHeaderDownloadedURL
            break

        case .False:
            finalHeaderImageURL = self.oldHeaderImageInDB
            break

        }
        print(finalHeaderImageURL)

        var finalProfileImageURL = String()

        switch self.selectedProfileImage {

        case .True:
            finalProfileImageURL = self.storageProfileDownloadedURL
            break

        case .False:
            finalProfileImageURL = self.oldProfilePhotoImageInDB
            break

        }
        print(finalProfileImageURL)

        guard let newDisplayName = self.displayNameTextField.text else { return }
        guard let newLocation = self.locationTextField.text else { return }
        guard let newDescription = self.bioTextField.text else { return }
        guard let newWebsite = self.websiteTextField.text else { return }
        guard let newBirthday = self.birthdayTextField.text else { return }

        let newUpdatedUserDictionary = ["imageProfile": finalProfileImageURL,
                                        "imageHeader" : finalHeaderImageURL,
                                        "description" : newDescription,
                                        "location": newLocation,
                                        "displayName": newDisplayName,
                                        "website": newWebsite,
                                        "birthday": newBirthday,
                                        ]
        Database.dataService.updateUserProfile(uid: userID, user: newUpdatedUserDictionary)

        showAlert(title: "Hey", msg: "Your profile was updated", actionButton: "OK", viewController: self)
         } // Get new uploaded profile and header image URLs
    }
}

The enums I use for the switch statements to determine if it's an old URL or a new one:

 enum SelectedHeaderImage
 {
  case True
  case False
 }

 enum SelectedProfileImage
 {
 case True
 case False
 }

Class outlets:

var storageProfileDownloadedURL = String()
var storageHeaderDownloadedURL = String()

var oldProfilePhotoImageInDB = String()
var oldHeaderImageInDB = String()

var selectedHeaderImage = SelectedHeaderImage.False
var selectedProfileImage = SelectedProfileImage.False`

Body:
From what I understood, your problem is with queuing. You want the code below to execute after the download is complete but it executes in its normal flow. If this is what your problem is then I would suggest you to create another enum, with three download states/count. And move that code below you want to be executed later in a function. Increment the state of new enum when download is complete. It would look something like this:

enum DownloadCount
{
    case Zero
    case One
    case Two
}
var downloadCount = DownloadCount.Zero

and in each of the success block of your download complete change it to, I will just write one here to give you the idea of what needs to be done.

if let profileImgDownloadedURL = url?.absoluteString
{
     self.storageProfileDownloadedURL = profileImgDownloadedURL
     print(self.storageProfileDownloadedURL)
     self.selectedProfileImage = .True
     if(downloadCount == .Zero)
     {
         downloadCount = DownloadCount.One
     }
     else
     {
         downloadCount = DownloadCount.Two
     }
     self.newAssigningFunction()
}

func newAssigningFunction()
{
    if(downloadCount == .Two)
    {
        //Do your storage/saving work here
    }
}

Also if you need to execute this function again, it would be best to set downloadCount back to Zero at start of your updateUserProfile function. Let me know if somethis is unclear or you need further help. Or if this was not your case.


问:
How does keras basic optimizer works?
Here is part of get_updates code from SGD from keras(source)

```<code>moments = [K.zeros(shape) for shape in shapes]
self.weights = [self.iterations] + moments
for p, g, m in zip(params, grads, moments):
    v = self.momentum * m - lr * g  # velocity
    self.updates.append(K.update(m, v))
</code>```

Observation:

Since moments variable is a list of zeros tensors. Each m in the for loop is a zero tensor with the shape of p. Then the self.momentum * m, at the first line of the loop, is just a scalar multiply by zero tensor which result a zero tensor.

Question

What am I missing here?

答:
Yes - during a first iteration of this loop m is equal to 0. But then it's updated by a current v value in this line:

```<code>self.updates.append(K.update(m, v))
</code>```

So in next iteration you'll have:

```<code>v = self.momentum * old_velocity - lr * g  # velocity
</code>```

where old_velocity is a previous value of v.

ContentLicense: CC BY-SA 4.0

Title: How does keras basic optimizer works?

Body:
Here is part of get_updates code from SGD from keras(source)

moments = [K.zeros(shape) for shape in shapes]
self.weights = [self.iterations] + moments
for p, g, m in zip(params, grads, moments):
    v = self.momentum * m - lr * g  # velocity
    self.updates.append(K.update(m, v))

Observation:

Since moments variable is a list of zeros tensors. Each m in the for loop is a zero tensor with the shape of p. Then the self.momentum * m, at the first line of the loop, is just a scalar multiply by zero tensor which result a zero tensor.

Question

What am I missing here?

Body:
Yes - during a first iteration of this loop m is equal to 0. But then it's updated by a current v value in this line:

self.updates.append(K.update(m, v))

So in next iteration you'll have:

v = self.momentum * old_velocity - lr * g  # velocity

where old_velocity is a previous value of v.


问:
swift skscene touch and hold other action than just touching
So I recently made a swift game with sprite kit and now I am stuck.
I have a character selection screen and I want to show a description for the character if you hold on the character, but if you just touch it you choose it and play with it. I already have the code to play/show the description. I just need to know when to call the corresponding functions and how to differentiate if the node is held or just touched.

Thanks in advance

答:
And here is how you can do it using gesture recognizers:</p>

```<code>import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var longPressGesture:UILongPressGestureRecognizer!
    var singleTapGesture:UITapGestureRecognizer!

    let kLongPressStartedActionKey = "longPressStarted"
     let kStoppingLongPressActionKey = "stoppingLongPressActionKey"

    let desc = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 150))
    let button = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let other = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))

    override func didMove(to view: SKView) {

        longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(GameScene.longPress(_:)))
        singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(GameScene.singleTap(_:)))
        self.view?.addGestureRecognizer(longPressGesture)
        self.view?.addGestureRecognizer(singleTapGesture)
        addChild(desc)
        addChild(button)
        addChild(other)

        button.position.y = -160
        button.name = "button"
        desc.alpha = 0.0
        desc.name = "description"
        other.name = "other"
        other.alpha = 0.0
        other.position.y = -320

    }

    private func stopLongPress(){

        desc.removeAction(forKey: self.kLongPressStartedActionKey)

        //Start fade out action if it isn't already started
        if desc.action(forKey: kStoppingLongPressActionKey) == nil {
            desc.run(SKAction.fadeOut(withDuration: 0.2), withKey: kStoppingLongPressActionKey)
        }

    }

    func singleTap(_ sender:UITapGestureRecognizer){

        if sender.state == .ended {

            let location = convertPoint(fromView: sender.location(in: self.view))

            if self.button.contains(location) {
                    self.other.alpha = self.other.alpha == 0.0 ? 1.0 : 0.0
            }
        }
    }

    func longPress(_ sender: UILongPressGestureRecognizer) {
        let longPressLocation = convertPoint(fromView: sender.location(in: self.view))

        if sender.state == .began {

            if button.contains(longPressLocation) {
                desc.run(SKAction.fadeIn(withDuration: 0.5), withKey: self.kLongPressStartedActionKey)
            }

        }else if sender.state == .ended {
            self.stopLongPress()
        }else if sender.state == .changed {

            let location = convertPoint(fromView:  sender.location(in: self.view))

            if !button.contains(location) {

                stopLongPress()

            }

        }
    }
}
</code>```

Body:
And here is how you can do it using gesture recognizers:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var longPressGesture:UILongPressGestureRecognizer!
    var singleTapGesture:UITapGestureRecognizer!

    let kLongPressStartedActionKey = "longPressStarted"
     let kStoppingLongPressActionKey = "stoppingLongPressActionKey"

    let desc = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 150))
    let button = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let other = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))

    override func didMove(to view: SKView) {

        longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(GameScene.longPress(_:)))
        singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(GameScene.singleTap(_:)))
        self.view?.addGestureRecognizer(longPressGesture)
        self.view?.addGestureRecognizer(singleTapGesture)
        addChild(desc)
        addChild(button)
        addChild(other)

        button.position.y = -160
        button.name = "button"
        desc.alpha = 0.0
        desc.name = "description"
        other.name = "other"
        other.alpha = 0.0
        other.position.y = -320

    }

    private func stopLongPress(){

        desc.removeAction(forKey: self.kLongPressStartedActionKey)

        //Start fade out action if it isn't already started
        if desc.action(forKey: kStoppingLongPressActionKey) == nil {
            desc.run(SKAction.fadeOut(withDuration: 0.2), withKey: kStoppingLongPressActionKey)
        }

    }

    func singleTap(_ sender:UITapGestureRecognizer){

        if sender.state == .ended {

            let location = convertPoint(fromView: sender.location(in: self.view))

            if self.button.contains(location) {
                    self.other.alpha = self.other.alpha == 0.0 ? 1.0 : 0.0
            }
        }
    }

    func longPress(_ sender: UILongPressGestureRecognizer) {
        let longPressLocation = convertPoint(fromView: sender.location(in: self.view))

        if sender.state == .began {

            if button.contains(longPressLocation) {
                desc.run(SKAction.fadeIn(withDuration: 0.5), withKey: self.kLongPressStartedActionKey)
            }

        }else if sender.state == .ended {
            self.stopLongPress()
        }else if sender.state == .changed {

            let location = convertPoint(fromView:  sender.location(in: self.view))

            if !button.contains(location) {

                stopLongPress()

            }

        }
    }
}


问:
How to launch Native App from Web app in iPhone?
I want to access TTS (Text-To-Speech) and STT (Speech-To-Text) functionality of iOS from web app. Since web app dont access ios device functions, is it possible to launch Native app from Web app?
e.g. When user wants to access TTS (e.g. Dragon Dictation), web page will launch Native app, take recording and send the recorded text to web app again.

Or we can access TTS/STT functionality right from web app?

答:
I can answer one part of your question - using the functionality of an IOS native app from a web-app;

Apps can be developed such that they respond to custom URL schemes - like, for example, the mail app responds to mailto:// and youtube responds to youtube://. Calling a URL with one of these schemes will start the IOS app - but it's entirely on the developer to code this into their application.

You could therefore in theory develop an app to get triggered from a web-app, perform an action then return to a web app after! Probably not something I would try and do though.


问:
Intercept events on modal feature in Magento 2
I need to intercept the "closed" event for a Modal popup in Magento 2 but i don't know where and how to do it.

This is the script within the template file, it works great but, as i wrote, i need to intercept the closed event to stop the video play.

```

答:
you can also specify it in the options :

var options = {
    type: 'popup',
    responsive: true,
    title: $.mage.__('Title Text'),
    closed: function (e) {
        // fun here!
    }
};
```


问:
Django/Haystack error: elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception',...)
I am using elasticsearch as backend for haystack in my Django project. I created everything required for a search as mentioned here. But when i search i throws a traceback error with TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]').

I have googled for this issue. But don't get any solution. I would appreciate helping me solve this.

My traceback:

```<code>Traceback (most recent call last):
  File "c:\python34\lib\site- packages\haystack\backends\elasticsearch_backend.py", line 524, in search
_source=True)
  File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
 File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 327, in perform_request
   status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400,  'parsing_exception', 'no [query] registered for [filtered]')
[28/Dec/2016 17:06:58]"GET /search/?q=code HTTP/1.1" 200 395
</code>```

Update-1 : TraceBack after downgraded to elasticsearch==1.7.0

```<code>GET /haystack/modelresult/_search?_source=true [status:400 request:0.001s]
Failed to query Elasticsearch using '(code)': TransportError(400, 'parsing_exception')
Traceback (most recent call last):
  File "c:\python34\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 524, in search
_source=True)
  File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 69, in _wrapped
    return func(*args, params=params, **kwargs)
  File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 527, in search
    doc_type, '_search'), params=params, body=body)
  File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 307, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 93, in perform_request
    self._raise_error(response.status, raw_data)
  File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 105, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception')
[28/Dec/2016 17:58:50]"GET /search/?q=code HTTP/1.1" 200 395
</code>```

答:
Elasticsearch already deprecate filtered query. Use bool instead.

It works for me.

Body:
I am using elasticsearch as backend for haystack in my Django project. I created everything required for a search as mentioned here. But when i search i throws a traceback error with TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]').

I have googled for this issue. But don't get any solution. I would appreciate helping me solve this.

My traceback:

Traceback (most recent call last):
  File "c:\python34\lib\site- packages\haystack\backends\elasticsearch_backend.py", line 524, in search
_source=True)
  File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
 File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 327, in perform_request
   status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400,  'parsing_exception', 'no [query] registered for [filtered]')
[28/Dec/2016 17:06:58]"GET /search/?q=code HTTP/1.1" 200 395

Update-1 : TraceBack after downgraded to elasticsearch==1.7.0

GET /haystack/modelresult/_search?_source=true [status:400 request:0.001s]
Failed to query Elasticsearch using '(code)': TransportError(400, 'parsing_exception')
Traceback (most recent call last):
  File "c:\python34\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 524, in search
_source=True)
  File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 69, in _wrapped
    return func(*args, params=params, **kwargs)
  File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 527, in search
    doc_type, '_search'), params=params, body=body)
  File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 307, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 93, in perform_request
    self._raise_error(response.status, raw_data)
  File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 105, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception')
[28/Dec/2016 17:58:50]"GET /search/?q=code HTTP/1.1" 200 395


答: Because paypal has a certificate that was signed by an authority that is in your trustStore, whereas facebook doesn't.</p>

Title: Java URL Connection strange behavior on https URLs


问:
python incorrectly calculates number
So, this was in my exam paper and I was really confused

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()
</code>```

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

```<code>num1: 45
num2: 90
</code>```

but why is the output:

```<code>num1: 45
num2: 67.5
</code>```

?

答: in num2 you are multipliying the result of num1 after the math operations instead of doing it before, when you write "num1 =" you are assigning a new value inside the "num1" variable memory position.</p>

Title: python incorrectly calculates number

Body:
So, this was in my exam paper and I was really confused

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

num1: 45
num2: 90

but why is the output:

num1: 45
num2: 67.5

?