问:
SweetAlert text formatting
I am using sweetAlert for dialog box display. Inside my dialog box, I have to display a large string with line breaks in between. My sample string is as follows:

```<code>var str="Task1Name          :    Success  :   statusCode\n
         Task2NameLonger    :    Failed   :   statusCode\n"
</code>```

and so on. So, basically, I want each of them in a new line and the spaces matched. When I use sweetalert dialog box line breaks are showing up properly but the text is aligned to the centre automatically and spacing is truncated. Can someone help me to manually set my alignment and spacing?

答:
Wrapping a string into ```</code> tag could be a solution:</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>var str="Task1Name          :    Success  :   statusCode\n" +
        "Task2NameLonger    :    Failed   :   statusCode\n";

Swal.fire({
  html: '```' + str + '```',
  customClass: {
    popup: 'format-pre'
  }
});</code>```

.format-pre pre {
  background: #49483e;
  color: #f7f7f7;
  padding: 10px;
  font-size: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script></code>```

PS. The original sweet alert plugin is unsupported, I suggest you using SweetAlert2 plugin.

Migration is simple, here's the migration guide: Migration from SweetAlert to SweetAlert2

Title: SweetAlert text formatting

Body:
I am using sweetAlert for dialog box display. Inside my dialog box, I have to display a large string with line breaks in between. My sample string is as follows:

var str="Task1Name          :    Success  :   statusCode\n
         Task2NameLonger    :    Failed   :   statusCode\n"

and so on. So, basically, I want each of them in a new line and the spaces matched. When I use sweetalert dialog box line breaks are showing up properly but the text is aligned to the centre automatically and spacing is truncated. Can someone help me to manually set my alignment and spacing?

Body:
Wrapping a string into <pre> tag could be a solution:

var str="Task1Name          :    Success  :   statusCode\n" +
        "Task2NameLonger    :    Failed   :   statusCode\n";

Swal.fire({
  html: '<pre>' + str + '</pre>',
  customClass: {
    popup: 'format-pre'
  }
});

.format-pre pre {
  background: #49483e;
  color: #f7f7f7;
  padding: 10px;
  font-size: 14px;
}

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

PS. The original sweet alert plugin is unsupported, I suggest you using SweetAlert2 plugin.

Migration is simple, here's the migration guide: Migration from SweetAlert to SweetAlert2


来源: stackexchange

问:
Namespace/Assembly errors in "Views" section in Visual Studio 2017
I have a .Net Core application that I used to develop on "back in the days of Visual Studio 2015". I have now moved on to Visual Studio 2017 and back to this project and I have a need to rename the project. I started following numerous guides online on how to rename a Visual Studio project, however none of them seems to support .Net Core and Visual Studio 2017. I believe it is important to mention that the only part of my project that complains about the namespace is the "Views" section, and it only seems to refer to files that have been created/edited recently.

After doing the following, I have still not found a solution:

Rename Solution in solution explorer.

Rename project in solution explorer.

Changing Assembly name in "Project" -> " Properties".

Changing Default namespace in "Project" -> " Properties".

Going to Program.cs and changing namespace using "Right-click" -> "Rename" -> "Rename all occurances".

Adding "@using " in _ViewImports.cshtml (complains about missing namespace here as well).

I am getting desperate as I feel like I have tried everything and nothing seems to works.

I have recently renamed my project from MobileFront to MSPFrontend and even if I change the "@using" statements inside my _ViewImports.cshtml back to MobileFront it still complains.

I am hoping that I am not the first one to encounter this tedious problem.

EDIT

I noticed the errors occured only when the files were open. I don't know if this is important to know of whether it has some importance for finding the solution.

答: I ended up downloading Microsoft.AspNetCore version 1.1.1 through NuGet. After doing that I created a completely new project and reopened my original project. That solved the problem. All of a sudden my project could find all namespaces and assemblies.

ContentLicense: CC BY-SA 3.0


问:
Converting from one nullable type to another nullable type
How can one convert from a nullable instance of class A to nullable instance of class B, while B is subclass of A, I tried this but it crashes:

```<code>class A
{
}

class B:A
{
}

A? instance_1=something_maybe_null;

if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1))?.some_method_in_B(paramters);
}
</code>```

And if I move ? into parathesis, it doesn't compile:

```<code>...
if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1)?).some_method_in_B(paramters);
}
</code>```

答:
I am assuming this is a typo A? instance_1=something_maybe_null; because you cannot do nullable reference types (i.e. classes), at least in C# 6.

If I understand your intent correctly, you just want to conditionally call a method in B if the object is actually an instance of B. If so, then you can do this:

```<code>class A
{
}

class B : A
{
    public void SomeMethodInB() {  }
}

A instance_a = something_maybe_null;
B instance_b = instance_a as B;
instance_b?.SomeMethodInB();
</code>```

Body:
How can one convert from a nullable instance of class A to nullable instance of class B, while B is subclass of A, I tried this but it crashes:

class A
{
}

class B:A
{
}

A? instance_1=something_maybe_null;

if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1))?.some_method_in_B(paramters);
}

And if I move ? into parathesis, it doesn't compile:

...
if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1)?).some_method_in_B(paramters);
}

Body:
I am assuming this is a typo A? instance_1=something_maybe_null; because you cannot do nullable reference types (i.e. classes), at least in C# 6.

If I understand your intent correctly, you just want to conditionally call a method in B if the object is actually an instance of B. If so, then you can do this:

class A
{
}

class B : A
{
    public void SomeMethodInB() {  }
}

A instance_a = something_maybe_null;
B instance_b = instance_a as B;
instance_b?.SomeMethodInB();


问:
How do you change a column value after a certain time interval - Cassandra
I have a column family in Cassandra in which one of the column name is status with value  Y. This status has to be updated to a new value - X after 30 minutes if it wasn't updated to some other value say N within the 30 minutes.

Basically, I want to mark the column to Expired - X if there wasn't any update within the specified time interval.

Also, once this is expired, it needs to trigger off an event to notify another system(API) saying that it was expired.

答:
You can try Cassandra's TTL (Time to Live) Feature

You can set an optional expiration period called TTL (time to live) for data in a column, other than a counter column. The TTL value for a column is a number of seconds. After the number of seconds since the column's creation exceeds the TTL value, TTL data is considered expired and is included in results

Every time you update the field, use TTL of 30 min or 1800 seconds

Example :

```<code>UPDATE users USING TTL 1800 SET password = 'ch@ngem4a' WHERE user_name = 'cbrown';
</code>```

For first time insert, also use the above query.

So for above example, the password field will mark as deleted after 30 min, if it is not updated within 30 min.

But it is not possible to trigger off an event to notify your system.

Note : TTL or delete generate tombstone, Huge amount of tombstone can slow down your read performance

Read More about tombstone

Body:
You can try Cassandra's TTL (Time to Live) Feature

You can set an optional expiration period called TTL (time to live) for data in a column, other than a counter column. The TTL value for a column is a number of seconds. After the number of seconds since the column's creation exceeds the TTL value, TTL data is considered expired and is included in results

Every time you update the field, use TTL of 30 min or 1800 seconds

Example :

UPDATE users USING TTL 1800 SET password = 'ch@ngem4a' WHERE user_name = 'cbrown';

For first time insert, also use the above query.

So for above example, the password field will mark as deleted after 30 min, if it is not updated within 30 min.

But it is not possible to trigger off an event to notify your system.

Note : TTL or delete generate tombstone, Huge amount of tombstone can slow down your read performance

Read More about tombstone


问:
iOS upload live streaming
I'm working on the live steaming app that user can upload live streaming video and others can also watching the video streaming.

While i'm researching on the streaming protocol, I found out that, for App store submission, Apple only accept the app using only HTTP Living Streaming (HLS) protocol for steaming videos. https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StreamingMediaGuide/UsingHTTPLiveStreaming/UsingHTTPLiveStreaming.html#//apple_ref/doc/uid/TP40008332-CH102-SW5

However i'm not sure HLS should be used for both upload and download video or it's only for download.

if HLS is only for download, then what is the best solutions (or protocol) for uploading live streaming?

Also if it's possible to use HLS to upload the video, can anybody provide proper way of implementing uploading video with HLS with Swift? (Any tutorial site, sample code, or any guide should be okay)

答:
Your mov file need to be converted into HLS format and store at the server, after that, iOS APP can easily play HLS streaming video, and so does Safari.

There are several ways to do the convert task. Ex: FFMPEG library and AWS Elastic Transcoder.

For FFMPEG there's lots of documents online for ex: https://www.ffmpeg.org/ffmpeg-formats.html#hls-1

I've done a project using AWS Elastic Transcoder, working together with S3, Lambda, and CloudFront. Which works pretty good in my opinion.
For reference:
https://aws.amazon.com/elastictranscoder/?nc1=h_ls

Title: iOS upload live streaming


问:
Transparent background appears for the dynamic columns in grid
I am developing a grid structure using div layout in my application. The columns and rows are not fixed, they are dynamic, being fetched from the json data in AngularJS.

So, it should scroll both horizontally as well as vertically, if the columns or rows or both extend beyond the available width.

I have handled it using following CSS:

```<code>.wrapper {
  white-space: nowrap;
  overflow-x: auto;
}
</code>```

The issue is that, it doesn't applies the background to the columns and rows which are beyond the grid's width.

Expectation: Both the header i.e. column and data-list i.e. rows, should be able to inherit their respective background colors.

Demo

答:
The problem occurs because of the CSS you have used to calculate the width of your columns.  You have used width: calc(100%/3) for each .display-data column, but you actually have four of these columns.

This means you are setting a total width for the four columns of 133%.  However, the parent .header only covers 100%.  This means that the last 33% is not covered by the .header and, hence, is not blue.

To fix it, just change your .display-data style to width: calc(100%/4).

Body:
I am developing a grid structure using div layout in my application. The columns and rows are not fixed, they are dynamic, being fetched from the json data in AngularJS.

So, it should scroll both horizontally as well as vertically, if the columns or rows or both extend beyond the available width.

I have handled it using following CSS:

.wrapper {
  white-space: nowrap;
  overflow-x: auto;
}

The issue is that, it doesn't applies the background to the columns and rows which are beyond the grid's width.

Expectation: Both the header i.e. column and data-list i.e. rows, should be able to inherit their respective background colors.

Demo


问:
How to know if a date is in an interval using lubridate?
If I have a lubridate interval: "2010-02-20" %--% "2012-03-15"
How may I know if a date, say "2011-01-12", is in that range?

I am using lubridate and the tidyverse packages.

Body:
library(data.table)
ymd("2011-01-12") %between% c("2010-02-20", "2012-03-15")

library(dplyr)
between(ymd("2011-01-12"), "2010-02-20", "2012-03-15")


问:
FreeMarker conditional with spaces in value
I have a conditional if, which takes a field, and evaluate its value against a fixed string. In the case the string which is evaluated contains an string the validation does not return the correct value, only works with value without spaces
example

as you can see there is data on those variables and the conditional works with data without spaces or other data that is created, but not with the variables with yellow arrow.

Im missing something?, an additional conversion or something? This is done with FreeMarker v 2.3.20.

答: Looking at the image it should work, so I suspect there's some invisible character there. For example, there can be a trailing space that you don't see because there's nothing directly after the printed value, or maybe the space between the two words is not really a space (0x20) but an nbsp (0xA0) character. Try ${principal.name?url} to see those.


问:
How to split a string using Pattern in Java
I want to split a string using methods in Pattern,here is what i did

```<code>String s = "[[[0.093493,51.6037],[0.091015,51.5956]]]"
Pattern branchPattern = Pattern.compile("[...]");
String[] split = branchPattern.split(s);
</code>```

I want to get the result that String[] contains [0.093493,51.6037] and [0.091015,51.5956]. But the result of this code is not the result i want. How can i split this string?  Or is there any way like use matcher to split this string in the format i want?

答:
I am trying to answer with another perspective. Have a look.Suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

```<code>import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}
</code>```

Here list result will have parameters n1_1,n2_2,n4_4.

Body:
I want to split a string using methods in Pattern,here is what i did

String s = "[[[0.093493,51.6037],[0.091015,51.5956]]]"
Pattern branchPattern = Pattern.compile("[...]");
String[] split = branchPattern.split(s);

I want to get the result that String[] contains [0.093493,51.6037] and [0.091015,51.5956]. But the result of this code is not the result i want. How can i split this string?  Or is there any way like use matcher to split this string in the format i want?

Body:
I am trying to answer with another perspective. Have a look.Suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}

Here list result will have parameters n1_1,n2_2,n4_4.


问:
Retreive Displayed text field in SAP through macro with Excel
I tried to run the SAP script recording to gather a text that is displayed for several item numbers automatically. While I was checking it this is the code I got :

```<code>If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").text = "CS03"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtRC29N-STLAN").setFocus
session.findById("wnd[0]/usr/ctxtRC29N-STLAN").caretPosition = 0
session.findById("wnd[0]").sendVKey 4
session.findById("wnd[1]/usr/lbl[1,10]").setFocus
session.findById("wnd[1]/usr/lbl[1,10]").caretPosition = 0
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/ctxtRC29N-MATNR").text = "508546"
session.findById("wnd[0]/usr/ctxtRC29N-WERKS").text = "1000"
session.findById("wnd[0]/usr/ctxtRC29N-WERKS").setFocus
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/tblSAPLCSDITCALT/ctxtRC29K-STLST[1,15]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/tblSAPLCSDITCALT/ctxtRC29K-STLST[1,15]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCDO").select
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA").select
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA/ssubSUBPAGE:SAPLCSDI:0152/tblSAPLCSDITCMAT/txtRC29P-KTEXT[3,3]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITEM/tabpPDAT").select
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA/ssubSUBPAGE:SAPLCSDI:0152/tblSAPLCSDITCMAT/txtRC29P-KTEXT[3,6]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITEM/tabpPDAT/ssubSUBPAGE:SAPLCSDI:0840/btnRC29P-ICON1").press
session.findById("wnd[0]/usr/cntlSCMSW_CONTAINER_2102/shellcont/shell").setDocument 1,"e1xydGYxXGFkZWZsYW5nMTAyNVxhbnNpXGFuc2ljcGcxMjUyXHVjM="
</code>```

Obviously, I did not get the required result as I want to retrieve the displayed text and not the text field. Any ideas on how to get that?

答:
First of all instead of .setFocus method try to use .Text method. Then create variable like strMyText. After that assign text from SAP to this variable and at the end paste it somewhere.
So it will be something like this:

```<code>Sub SAPText()

Dim strMyText

If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").text = "CS03"
session.findById("wnd[0]").sendVKey 0

strMyText = session.findById("wnd[0]/usr/ctxtRC29N-STLAN").Text

Activecell.value = strMyText

End sub
</code>```

Body:
I tried to run the SAP script recording to gather a text that is displayed for several item numbers automatically. While I was checking it this is the code I got :

If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").text = "CS03"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtRC29N-STLAN").setFocus
session.findById("wnd[0]/usr/ctxtRC29N-STLAN").caretPosition = 0
session.findById("wnd[0]").sendVKey 4
session.findById("wnd[1]/usr/lbl[1,10]").setFocus
session.findById("wnd[1]/usr/lbl[1,10]").caretPosition = 0
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/ctxtRC29N-MATNR").text = "508546"
session.findById("wnd[0]/usr/ctxtRC29N-WERKS").text = "1000"
session.findById("wnd[0]/usr/ctxtRC29N-WERKS").setFocus
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/tblSAPLCSDITCALT/ctxtRC29K-STLST[1,15]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/tblSAPLCSDITCALT/ctxtRC29K-STLST[1,15]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCDO").select
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA").select
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA/ssubSUBPAGE:SAPLCSDI:0152/tblSAPLCSDITCMAT/txtRC29P-KTEXT[3,3]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITEM/tabpPDAT").select
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/tabsTS_ITOV/tabpTCMA/ssubSUBPAGE:SAPLCSDI:0152/tblSAPLCSDITCMAT/txtRC29P-KTEXT[3,6]").setFocus
session.findById("wnd[0]").sendVKey 2
session.findById("wnd[0]/usr/tabsTS_ITEM/tabpPDAT/ssubSUBPAGE:SAPLCSDI:0840/btnRC29P-ICON1").press
session.findById("wnd[0]/usr/cntlSCMSW_CONTAINER_2102/shellcont/shell").setDocument 1,"e1xydGYxXGFkZWZsYW5nMTAyNVxhbnNpXGFuc2ljcGcxMjUyXHVjM="

Obviously, I did not get the required result as I want to retrieve the displayed text and not the text field. Any ideas on how to get that?

Body:
First of all instead of .setFocus method try to use .Text method. Then create variable like strMyText. After that assign text from SAP to this variable and at the end paste it somewhere.
So it will be something like this:

Sub SAPText()

Dim strMyText

If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").text = "CS03"
session.findById("wnd[0]").sendVKey 0

strMyText = session.findById("wnd[0]/usr/ctxtRC29N-STLAN").Text

Activecell.value = strMyText

End sub


问:
node.js driver for mysql works in console but not in actual code
I have .js file with following code:

```<code>var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");
</code>```

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

答:
your code is wrong.

You have written

```<code>var mysql = require(‘mysql'); var connection = mysql.createConnection({host: ‘localhost';user: 'root',password: 'password',database: ‘databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
</code>```

It should be

```<code>var mysql = require('mysql'); var connection = mysql.createConnection({host: 'localhost';user: 'root',password: 'password',database: 'databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
</code>```

At many places, you have started strings with ‘ and ended with ' which might be causing the problem.

Body:
I have .js file with following code:

var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

Body:
your code is wrong.

You have written

var mysql = require(‘mysql'); var connection = mysql.createConnection({host: ‘localhost';user: 'root',password: 'password',database: ‘databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});

It should be

var mysql = require('mysql'); var connection = mysql.createConnection({host: 'localhost';user: 'root',password: 'password',database: 'databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});

At many places, you have started strings with ‘ and ended with ' which might be causing the problem.


问:
Displaying GIF in ImageView using Glide
I am using Glide for the very fist time to display GIF inside ImageView. I have coded it the way it is given across several sites. But it is not working. I have given all the code below:(Please let me know if I have mistaken anything)

Project level build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        classpath 'com.google.gms:google-services:2.1.0-alpha5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

App level build.gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.winner.myapplication"
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.1'
    //compile files('libs/ion-2.1.6.jar')
    //compile files('libs/androidasync-2.1.6.jar')
    compile 'com.github.bumptech.glide:glide:3.7.0'
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.winner.myapplication.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage1"
        android:orientation="vertical"
        android:layout_gravity="center"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage2"
        android:orientation="vertical"
        android:layout_below="@+id/layoutImage1"
        android:layout_gravity="center"
        >
        <ImageView
            android:id="@+id/test_image"
            android:layout_width="160dp"
            android:layout_height="90dp"
            android:scaleType="fitXY"
            android:layout_gravity="center"
            android:src="@drawable/test"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage3"
        android:orientation="vertical"
        android:layout_below="@+id/layoutImage2"
        android:layout_gravity="center"
        >
        <TextView android:text="Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="right"
            android:id="@+id/submit"
            android:text="Submit" />

    </LinearLayout>

</RelativeLayout>
</code>```

Activity Java code:

```<code>package com.example.winner.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button submit = (Button) findViewById(R.id.submit);
        submit.setOnClickListener(onClickSubmit);
    }

    View.OnClickListener onClickSubmit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iView = (ImageView) findViewById(R.id.test_image);
            Glide.with(getApplicationContext()).
                    load("http://i.imgur.com/1ALnB2s.gif").into(iView);

        }
    };
}
</code>```

I do not see the GIF image after clicking on the Submit button.

答:
To load the gif using glide,glide takes few seconds to process the gif. So, the image can only be loaded after that time.So, mean while u can use placeholder.

Glide.with(this).load("http://i.imgur.com/1ALnB2s.gif").asGif().placeHolder(R.drawable.any_normal_image.png).into(iView);

Title: Displaying GIF in ImageView using Glide

Body:
I am using Glide for the very fist time to display GIF inside ImageView. I have coded it the way it is given across several sites. But it is not working. I have given all the code below:(Please let me know if I have mistaken anything)

Project level build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        classpath 'com.google.gms:google-services:2.1.0-alpha5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App level build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.winner.myapplication"
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.1'
    //compile files('libs/ion-2.1.6.jar')
    //compile files('libs/androidasync-2.1.6.jar')
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.winner.myapplication.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage1"
        android:orientation="vertical"
        android:layout_gravity="center"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage2"
        android:orientation="vertical"
        android:layout_below="@+id/layoutImage1"
        android:layout_gravity="center"
        >
        <ImageView
            android:id="@+id/test_image"
            android:layout_width="160dp"
            android:layout_height="90dp"
            android:scaleType="fitXY"
            android:layout_gravity="center"
            android:src="@drawable/test"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:id="@+id/layoutImage3"
        android:orientation="vertical"
        android:layout_below="@+id/layoutImage2"
        android:layout_gravity="center"
        >
        <TextView android:text="Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="right"
            android:id="@+id/submit"
            android:text="Submit" />

    </LinearLayout>

</RelativeLayout>

Activity Java code:

package com.example.winner.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button submit = (Button) findViewById(R.id.submit);
        submit.setOnClickListener(onClickSubmit);
    }

    View.OnClickListener onClickSubmit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iView = (ImageView) findViewById(R.id.test_image);
            Glide.with(getApplicationContext()).
                    load("http://i.imgur.com/1ALnB2s.gif").into(iView);

        }
    };
}

I do not see the GIF image after clicking on the Submit button.


问:
Tkinter - Coordinates
I'm making a little project from a Pi2Go robot, where it will get data from the ultrasonic sensor, then place an X if it see's a object and O where it currently is, I've got two questions:
How do I set a coordinate position on tkinter? For example I wanted to insert text at 0,0, or 120,120.

Secondly:
How do I get tkinter to constantly update the map I'm building
Cheers!

答:
The best thing you can do is to use place method whit arguments of your X and Y coordinates.

```<code>label = Label(root, text = 'Placed On X and Y')
label.place(x= X,y = Y)
</code>```

or another way is to use pack method which will take arguments like:

```<code>label.pack(padx = W,pady = H)
</code>```

where W and H are the distances from center points to your coordinates X and Y.

Title: Tkinter - Coordinates

Body:
The best thing you can do is to use place method whit arguments of your X and Y coordinates.

label = Label(root, text = 'Placed On X and Y')
label.place(x= X,y = Y)

or another way is to use pack method which will take arguments like:

label.pack(padx = W,pady = H)

where W and H are the distances from center points to your coordinates X and Y.


问:
Android get Manifest merger failed Error on using tools:replace
in my project as far as i'm using more library i have to use tools:replace for overriding some features such as supportsRtl, when i add tools name space and use tools:replace="android:supportsRtl,android:allowBackup" on application tag i get this error:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs
</code>```

manifest content:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.myapp.androidapp">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".APP"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme"
        tools:replace="android:supportsRtl,android:allowBackup">

        <activity android:name=".Ui.ActivityStartUpApplication">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity
            android:name=".Ui.ApplicationRobot.view.ActivityRegisterRobot"
            android:configChanges="screenSize|orientation"/>

        <activity
            android:name=".Ui.ActivityChannelContent.view.ActivityChannelContent"
            android:configChanges="screenSize|orientation">

        </activity>

        <activity
            android:name=".Ui.ActivityMain.view.ActivityMain"
            android:configChanges="screenSize|orientation"/>

    </application>

</manifest>
</code>```

答:
problem resolved by adding

```<code>android:supportsRtl="false"
</code>```

before

```<code>tools:replace="android:supportsRtl,android:allowBackup"
</code>```

Body:
in my project as far as i'm using more library i have to use tools:replace for overriding some features such as supportsRtl, when i add tools name space and use tools:replace="android:supportsRtl,android:allowBackup" on application tag i get this error:

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

manifest content:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.myapp.androidapp">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".APP"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme"
        tools:replace="android:supportsRtl,android:allowBackup">

        <activity android:name=".Ui.ActivityStartUpApplication">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity
            android:name=".Ui.ApplicationRobot.view.ActivityRegisterRobot"
            android:configChanges="screenSize|orientation"/>

        <activity
            android:name=".Ui.ActivityChannelContent.view.ActivityChannelContent"
            android:configChanges="screenSize|orientation">

        </activity>

        <activity
            android:name=".Ui.ActivityMain.view.ActivityMain"
            android:configChanges="screenSize|orientation"/>

    </application>

</manifest>

Body:
problem resolved by adding

android:supportsRtl="false"

before

tools:replace="android:supportsRtl,android:allowBackup"


问:
PHP sum two different minutes
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

```<code>$default_time = "00:30";
 $extra_time   = "00:25";
</code>```

my expected output : 00:55

but now display 01:00

this is my code

```<code>$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
</code>```

答:
Use below code you will definitely get your answers.

```<code>$default_time = "00:30:00";
$extra_time = "00:25:00";

$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
</code>```

You can modify above code as per your need.

Title: PHP sum two different minutes

Body:
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

$default_time = "00:30";
 $extra_time   = "00:25";

my expected output : 00:55

but now display 01:00

this is my code

$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));

Body:
Use below code you will definitely get your answers.

$default_time = "00:30:00";
$extra_time = "00:25:00";

$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;

You can modify above code as per your need.


问:
Building msbuild 15 project programmatically

I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}
```

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

答:
If you just need the path to the latest MSBuild.exe, use Microsoft.Build.Utilities.Core from Nuget and use the following code:

```<code>ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
</code>```

This works whether just Build Tools are installed or the full Visual Studio installation.

Body:
I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

Body:
If you just need the path to the latest MSBuild.exe, use Microsoft.Build.Utilities.Core from Nuget and use the following code:

ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);

This works whether just Build Tools are installed or the full Visual Studio installation.


问:
SSIS load column number(precision,scale)
Hi I have a SSIS package which I use to load the monthly data. Every month vendor send us data in same format but they have changed this month. the price column in my MS sql server database is PRICE decimal(7,2) but client sent us data having price=210000.0000. I rounded to two decimal but I still can not load data. Please help!!!

答:
Use a derived column transformation with the following expression</p>

```<code>(DT_NUMERIC,7,2)ROUND([Column],2)
</code>```

Body:
Use a derived column transformation with the following expression

(DT_NUMERIC,7,2)ROUND([Column],2)


问:
How to make kill command faster
I have two processes running in two different cores and no any other user processes are running on these cores. Now I am trying to stop one process from another process by sending kill -STOP and kill -CONT in loop. But the kill -STOP command is taking more than 200 micro seconds to stop the process. Is there any way to reduce this time to less than 5 micro seconds

答:
```<code>sudo kill -9 process_id
</code>```

Hope this helps.

Title: How to make kill command faster

Body:
sudo kill -9 process_id

Hope this helps.


问:
How to add an array into mongodb by uing node js and angularjs?
My Code:</p>

```<code>var user = new User({
    fullname: req.body.fullname,
    mobile:req.body.mobile,
    email: req.body.email,
    gender: req.body.gender,
    state: req.body.state,
    city: req.body.city,
    pincode:req.body.pincode,
    college: req.body.college,
    course: req.body.course,
    descipline: req.body.descipline,
    semester: req.body.semester,
    university: req.body.university,
    month:req.body.month,
    worklocation:req.body.worklocation,
    members:members
});

user.save(function(err, data) {
    if(err) {
        return next(err);
    }
    res.status(201).json(data);
});
</code>```

答:
you can assign member array of object directly in your schema

```<code>var members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];

var user = new User({
            fullname: req.body.fullname,
            .....
            members:members
        });
</code>```

if you send same property name from angular then you can just use req.body like new User(req.body).

so you can send as req body from UI like

```<code>$scope.user = {
            fullname: 'xx',
            mobile: 'yy',
            members: [{degree_name:'xxx', degree_subject: 'yyy'},
                  {degree_name:'xxx1', degree_subject: 'yyy1'}]
};
</code>```

then in mongoose can use like

```<code>var user = new User(req.body);
</code>```

then automatically mapped according to you property name.

If anything different with req.body property name with schema then reassign that property.

```<code>var user = new User(req.body);
user.course = req.body.courseName
</code>```

Angular code:

```<code>$scope.members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];
  $scope.registerDetails = function() {
    $scope.user.members = $scope.members;
    $http.post('/api', $scope.user).success(function(data) {
      // your code
    }).error(function(status) {
      // your code
    });
  };
</code>```

Body:
My Code:

var user = new User({
    fullname: req.body.fullname,
    mobile:req.body.mobile,
    email: req.body.email,
    gender: req.body.gender,
    state: req.body.state,
    city: req.body.city,
    pincode:req.body.pincode,
    college: req.body.college,
    course: req.body.course,
    descipline: req.body.descipline,
    semester: req.body.semester,
    university: req.body.university,
    month:req.body.month,
    worklocation:req.body.worklocation,
    members:members
});

user.save(function(err, data) {
    if(err) {
        return next(err);
    }
    res.status(201).json(data);
});

Body:
you can assign member array of object directly in your schema

var members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];

var user = new User({
            fullname: req.body.fullname,
            .....
            members:members
        });

if you send same property name from angular then you can just use req.body like new User(req.body).

so you can send as req body from UI like

$scope.user = {
            fullname: 'xx',
            mobile: 'yy',
            members: [{degree_name:'xxx', degree_subject: 'yyy'},
                  {degree_name:'xxx1', degree_subject: 'yyy1'}]
};

then in mongoose can use like

var user = new User(req.body);

then automatically mapped according to you property name.

If anything different with req.body property name with schema then reassign that property.

var user = new User(req.body);
user.course = req.body.courseName

Angular code:

$scope.members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];
  $scope.registerDetails = function() {
    $scope.user.members = $scope.members;
    $http.post('/api', $scope.user).success(function(data) {
      // your code
    }).error(function(status) {
      // your code
    });
  };


问:
How change iOS TableView index Color?

How do I customise the Color and Font of the right side list.

答:
Use UITableView methods sectionIndexColor and sectionIndexBackgroundColor

Example

```<code>tableView.sectionIndexColor = UIColor.red
tableView.sectionIndexBackgroundColor = UIColor.clear
</code>```

Title: How change iOS TableView index Color?

Body:
Use UITableView methods sectionIndexColor and sectionIndexBackgroundColor

Example

tableView.sectionIndexColor = UIColor.red
tableView.sectionIndexBackgroundColor = UIColor.clear


问:
Passing a Tkinter Entry variable to a function
I am trying to learn how to save the data typed into a few entry fields into a text file but I'm obviously missing something.  I created a Print button to print these variables so I could test but only get PY_VAR0, PY_VAR1, and PY_VAR2.  What am I missing?  Why are the firstName, lastName and userAge variables not passing to the functions?

Thanks in advance :-)

This is my code:

```<code>from tkinter import *
from tkinter import ttk

# Function to exit app **********************************************************
def callbackExit():
    root.destroy()
# End of Function to exit app ***************************************************

# Function to save entries to file **********************************************
def callbackSaveToFile():
    fileName = 'data.txt'
    target = open (fileName, 'w')
    target.write(firstName)
    target.write(lastName)
    target.write(userAge)
    target.close()
# End of Function to save entries ***********************************************

def testPrint():
    print(firstName)
    print(lastName)
    print(userAge)

root = Tk()
root.config(height = 480, width = 640)
root.title('Name and Age App v.1.0')
root.resizable(False, False)

firstName = StringVar()
lastName = StringVar()
userAge = IntVar()

ttk.Label(root, text = 'First Name: ').place(x=20, y=20)
ttk.Entry(root, width = 30, textvariable = firstName).place(x=115, y=20)
ttk.Label(root, text = 'Last Name: ').place(x=20, y=50)
ttk.Entry(root, width = 30, textvariable=lastName).place(x=115, y=50)
ttk.Label(root, text = 'Age: ').place(x=20, y=80)
ttk.Entry(root, width = 3, textvariable=userAge).place(x=115, y=80)

buttonExitApp = ttk.Button(root, text = 'Exit', command=callbackExit).place(x=500, y=350)
buttonSaveData = ttk.Button(root,text = 'Save', command=callbackSaveToFile).place(x=400, y=350)
buttonTestPrint = ttk.Button(root, text = 'Print', command=testPrint).place(x=20, y=350)

root.mainloop()
</code>```

答:
In def use it like this

```<code>def something():
    global var1
    global var2
    global var3
</code>```

then you can begin because the dwf are looking for local variables so you will have to make it global for the def and you will have to do this with every def you have

Body:
I am trying to learn how to save the data typed into a few entry fields into a text file but I'm obviously missing something.  I created a Print button to print these variables so I could test but only get PY_VAR0, PY_VAR1, and PY_VAR2.  What am I missing?  Why are the firstName, lastName and userAge variables not passing to the functions?

Thanks in advance :-)

This is my code:

from tkinter import *
from tkinter import ttk

# Function to exit app **********************************************************
def callbackExit():
    root.destroy()
# End of Function to exit app ***************************************************

# Function to save entries to file **********************************************
def callbackSaveToFile():
    fileName = 'data.txt'
    target = open (fileName, 'w')
    target.write(firstName)
    target.write(lastName)
    target.write(userAge)
    target.close()
# End of Function to save entries ***********************************************

def testPrint():
    print(firstName)
    print(lastName)
    print(userAge)

root = Tk()
root.config(height = 480, width = 640)
root.title('Name and Age App v.1.0')
root.resizable(False, False)

firstName = StringVar()
lastName = StringVar()
userAge = IntVar()

ttk.Label(root, text = 'First Name: ').place(x=20, y=20)
ttk.Entry(root, width = 30, textvariable = firstName).place(x=115, y=20)
ttk.Label(root, text = 'Last Name: ').place(x=20, y=50)
ttk.Entry(root, width = 30, textvariable=lastName).place(x=115, y=50)
ttk.Label(root, text = 'Age: ').place(x=20, y=80)
ttk.Entry(root, width = 3, textvariable=userAge).place(x=115, y=80)

buttonExitApp = ttk.Button(root, text = 'Exit', command=callbackExit).place(x=500, y=350)
buttonSaveData = ttk.Button(root,text = 'Save', command=callbackSaveToFile).place(x=400, y=350)
buttonTestPrint = ttk.Button(root, text = 'Print', command=testPrint).place(x=20, y=350)

root.mainloop()

Body:
In def use it like this

def something():
    global var1
    global var2
    global var3

then you can begin because the dwf are looking for local variables so you will have to make it global for the def and you will have to do this with every def you have


问:
method calling architecture/definiton of printf() and format()
Below is code of printf() and format() methods present in java.io.PrintStream

```<code>  public java.io.PrintStream printf(java.lang.String, java.lang.Object...);
  public java.io.PrintStream printf(java.util.Locale, java.lang.String, java.lang.Object...);
  public java.io.PrintStream format(java.lang.String, java.lang.Object...);
  public java.io.PrintStream format(java.util.Locale, java.lang.String, java.lang.Object...);
</code>```

These methods consist of two format parameters.
But, when we pass a single argument to these methods and run the program, it ran successfully.

My question is where these methods are defined with single parameters similar to print() or println()  methods as these methods consist of single parameter(defined in java.io.PrintStream).

I tried to execute following code and it is running fine.

```<code>public class FormatAndPrintf {
public static void main(String args[]){
    System.out.printf("This is printed using printf() function.");
    System.out.format("This is printed using format() function.");
    System.out.println("++++++++++++++++++++++++++++++++++++++++==");
}
}
</code>```

答: The ... operator is a way to pass a (variable-sized) array of arguments to a method without having to manually create the array. Passing none, as you are doing in the enclosed snippet, means that the method will get an empty array.

Body:
Below is code of printf() and format() methods present in java.io.PrintStream

  public java.io.PrintStream printf(java.lang.String, java.lang.Object...);
  public java.io.PrintStream printf(java.util.Locale, java.lang.String, java.lang.Object...);
  public java.io.PrintStream format(java.lang.String, java.lang.Object...);
  public java.io.PrintStream format(java.util.Locale, java.lang.String, java.lang.Object...);

These methods consist of two format parameters.
But, when we pass a single argument to these methods and run the program, it ran successfully.

My question is where these methods are defined with single parameters similar to print() or println()  methods as these methods consist of single parameter(defined in java.io.PrintStream).

I tried to execute following code and it is running fine.

public class FormatAndPrintf {
public static void main(String args[]){
    System.out.printf("This is printed using printf() function.");
    System.out.format("This is printed using format() function.");
    System.out.println("++++++++++++++++++++++++++++++++++++++++==");
}
}


问:
Postgresql query a weeks worth of data based on a calendar day regardless which one
In PostgreSQL, how could I get the dates of all days in a week, using the date of a single day as input?  For example, imagine a user clicks on on a day in a calendar user interface widget.  That highlights the entire week.

I want to write a query that pulls all rows from a table where a date column matches the date from any day in the highlighted week, regardless of whether the user selected Monday, Wednesday, etc.

答:
You should combine the week and year to make the query stable even on the end/start of a year. E.g.:

```<code>select *
from some_table
where to_char(some_date_column, 'iyyy-iw') = to_char(date '2017-06-06', 'iyyy-iw')
</code>```

iyyy and iw is the ISO week numbering. The ISO week always starts on Monday.

or using the extract function:

```<code>select *
from some_table
where (extract(isoyear from some_date_column), extract(week from some_date_column))
      = (extract(isoyear from date '2017-06-06'), extract(week from date '2017-06-06'))
</code>```

Note that extract(week ...) is always the ISO week. There is no corresponding "non-iso" keyword for the extract() function

Body:
You should combine the week and year to make the query stable even on the end/start of a year. E.g.:

select *
from some_table
where to_char(some_date_column, 'iyyy-iw') = to_char(date '2017-06-06', 'iyyy-iw')

iyyy and iw is the ISO week numbering. The ISO week always starts on Monday.

or using the extract function:

select *
from some_table
where (extract(isoyear from some_date_column), extract(week from some_date_column))
      = (extract(isoyear from date '2017-06-06'), extract(week from date '2017-06-06'))

Note that extract(week ...) is always the ISO week. There is no corresponding "non-iso" keyword for the extract() function


问:
Remove the first par of bracket from an Array Swift 3
I have this array with double pairs of bracket [["0": 5, "2": 10]] and I want to convert it to ["5","10"] or [5,10]</p>

答:
I don't know what you are trying to achieve here. But this solution does exactly what you asked in your question. i.e. convert an Array of Array of Dictionary into an Array ( [["0": 5, "2": 10]] -> [5,10] )

```<code>let data = [["0": 5, "2": 10]]
var finalArray = Array<Any>()
for dictArr in data {
    for (key,value) in dictArr {
        finalArray.append(value)        //[5,10]
    }
}
</code>```

If you want to convert an Array of Array of Dictionary into an Array of Array of Element ( [["0": 5, "2": 10]] -> [[5,10]] ), use the following code.

```<code>let data = [["0": 5, "2": 10]]
var finalArray = Array<Any>()
for dictArr in data {
    var tempArr = [Int]()
    for (key,value) in dictArr {
        tempArr.append(value)
    }
    finalArray.append(tempArr)        //[[5,10]]
}
</code>```

Body:
I don't know what you are trying to achieve here. But this solution does exactly what you asked in your question. i.e. convert an Array of Array of Dictionary into an Array ( [["0": 5, "2": 10]] -> [5,10] )

let data = [["0": 5, "2": 10]]
var finalArray = Array<Any>()
for dictArr in data {
    for (key,value) in dictArr {
        finalArray.append(value)        //[5,10]
    }
}

If you want to convert an Array of Array of Dictionary into an Array of Array of Element ( [["0": 5, "2": 10]] -> [[5,10]] ), use the following code.

let data = [["0": 5, "2": 10]]
var finalArray = Array<Any>()
for dictArr in data {
    var tempArr = [Int]()
    for (key,value) in dictArr {
        tempArr.append(value)
    }
    finalArray.append(tempArr)        //[[5,10]]
}


问:
What does the Jenkins iLmBjh process do?
Today I noticed that several of our Jenkins jobs (which are independant, different projects and everything) failed.

I investigated an finally listed all processes on the machine that Jenkins uses with the top command. It showed me a very greedy process launched by Jenkins, which name is iLmBjh. Not very clear, isn't it?
I tried some things and finally killed it. But it appeared again when I launched a new Jenkins job.

Do someone know what this process does? It's the first time I see it on the processes list...

答:
Ok, I guess I found the problem and it's kind of surprising. On our Jenkins instance, we had the JiraTestReporter plugin installed. Our Jira licence ended today. And when I checked the Jenkins logs, it was full of Jira error messages.

What is disturbing is that we weren't using it at all... in any of our jobs!

I uninstalled it and was able to run my job again. The iLmBjh process did not come back.


问:
Notifications stacking behavior in iOS and Android
What is default notifications stacking behavior in case of Android and iOS meaning latest notification is shown at the top or bottom in notification panel?</p>

答: On iOS, latest notification is shown at the top.</p>


问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
Make configuration.properties file separate for stage and production. these configuration files will have corresponding properties. Now while Application startup you can first read Properties based on environment. environment value you can pass as argument in your application. You just need to write a simple ConfigurtionReader class which will read required configuration before application startup. Below is the code sample considering a very simple property file reading in plain java.

This will read a property file which is placed parallel to jar(current application).

```<code>public class ConfigurationReader {

    /** The job config prop. */
    private static final Properties JOB_CONFIG_PROP = new Properties();

    /**
     * Function is used to read configuration file that is placed in same place
     * where project jar is located.
     *
     */
    public void readConfiguration(final String jobName) {
        File jarPath;
        String propertiesPath = " ";
        String jobConfigFile = " ";
        try {
            jarPath = new File(ConfigurationReader.class.getProtectionDomain().getCodeSource().getLocation().getPath());
            propertiesPath = jarPath.getParentFile().getAbsolutePath();
            jobConfigFile = propertiesPath + File.separator + AppConstants.CONFIGURATION_FOLDER_NAME
                    + File.separator + jobName + AppConstants.PROP;
            JOB_CONFIG_PROP.load(new FileInputStream(jobConfigFile));
        } catch (FileNotFoundException fileNtFoundExep) {
            throw fileNtFoundExep;
        } catch (IOException iOException) {
            throw iOException;
        } catch (Exception exception) {
            throw exception;
        }
    }

    public static String getPropertyValue(final String key) {
        return JOB_CONFIG_PROP.getProperty(key);
    }

    public static void setPropertyValue(final String key, final String value) {
        JOB_CONFIG_PROP.setProperty(key, value);
    }
}
</code>```

You can then get/set the property value using...

```<code>ConfigurationReader.getPropertyValue("abc");
ConfigurationReader.setPropertyValue("abc","xyz");
</code>```

This is just a simple approach to achieve the reading of properties from a property file. You can do something like this.

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!

Body:
Make configuration.properties file separate for stage and production. these configuration files will have corresponding properties. Now while Application startup you can first read Properties based on environment. environment value you can pass as argument in your application. You just need to write a simple ConfigurtionReader class which will read required configuration before application startup. Below is the code sample considering a very simple property file reading in plain java.

This will read a property file which is placed parallel to jar(current application).

public class ConfigurationReader {

    /** The job config prop. */
    private static final Properties JOB_CONFIG_PROP = new Properties();

    /**
     * Function is used to read configuration file that is placed in same place
     * where project jar is located.
     *
     */
    public void readConfiguration(final String jobName) {
        File jarPath;
        String propertiesPath = " ";
        String jobConfigFile = " ";
        try {
            jarPath = new File(ConfigurationReader.class.getProtectionDomain().getCodeSource().getLocation().getPath());
            propertiesPath = jarPath.getParentFile().getAbsolutePath();
            jobConfigFile = propertiesPath + File.separator + AppConstants.CONFIGURATION_FOLDER_NAME
                    + File.separator + jobName + AppConstants.PROP;
            JOB_CONFIG_PROP.load(new FileInputStream(jobConfigFile));
        } catch (FileNotFoundException fileNtFoundExep) {
            throw fileNtFoundExep;
        } catch (IOException iOException) {
            throw iOException;
        } catch (Exception exception) {
            throw exception;
        }
    }

    public static String getPropertyValue(final String key) {
        return JOB_CONFIG_PROP.getProperty(key);
    }

    public static void setPropertyValue(final String key, final String value) {
        JOB_CONFIG_PROP.setProperty(key, value);
    }
}

You can then get/set the property value using...

ConfigurationReader.getPropertyValue("abc");
ConfigurationReader.setPropertyValue("abc","xyz");

This is just a simple approach to achieve the reading of properties from a property file. You can do something like this.


问:
Need suggestion for framework
I just went through https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why discussion and read about frameworks.

Till now I've been coding from scratch everytime I developer a new application, Now I want to start with a framework for new project. Things I am looking for in the framework

User Signup Process OAuth module for

List item Twitter (fetching tweets) (important)

OAuth module for Facebook (fetching wall-posts) (important)

MVC Architecture

Paypal module for payments

I dont know if such framework exists, and I am new to frameworks, so I am looking for suggestion for which framework to start with and what all modules/plugins to pick

Language: PHP

Backend: MySQL

Frontend: HTML5/CSS

Platform: OSX

答: I think the most solid php framework "base" you can use is ZEND. Then, as already said, you can easily add features/plugins! :)</p>

ContentLicense: CC BY-SA 2.5

Title: Need suggestion for framework


问:
How to use angularJs code inside of JSP file?
I am trying adding angular code inside of .jsp file but getting some error like :

"Multiple annotations found at this line:
    - Start tag of element
    - Undefined attribute name
     (ng-app)."

So can anyone help how to proceed with it !

答:
You can add the following code to your JSP/Html file to user angular code:</p>

```<code> <script>
 var myApp = angular.module('myApp', []);

 myApp.controller('anyController', function ($scope, $http)
 {
    // Write your angular code here

 });
 </script>
</code>```

Body:
You can add the following code to your JSP/Html file to user angular code:

 <script>
 var myApp = angular.module('myApp', []);

 myApp.controller('anyController', function ($scope, $http)
 {
    // Write your angular code here

 });
 </script>


问:
Shell: list directories ordered by file count (including in subdirectories)
I've nearly reached my limit for the permitted number of files in my Linux home directory, and I'm curious about where all the files are.

In any directory I can use for example find . -type f | wc -l to show a count of how many files are in that directory and in its subdirectories, but what I'd like is to be able to generate a complete list of all subdirectories (and sub-subdirectories etc) each with a count of all files contained in it and its subdirectories - if possible ranked by count, descending.

Eg if my file structure looks like this:

```<code>Home/
  file1.txt
  file2.txt
  Docs/
    file3.txt
    Notes/
      file4.txt
      file5.txt
    Queries/
      file6.txt
  Photos/
    file7.jpg
</code>```

The output would be something like this:

```<code>7  Home
4  Home/Docs
2  Home/Docs/Notes
1  Home/Docs/Queries
1  Home/Photos
</code>```

Any suggestions greatly appreciated. (Also a quick explanation of the answer, so I can learn from this!). Thanks.

Body:
I've nearly reached my limit for the permitted number of files in my Linux home directory, and I'm curious about where all the files are.

In any directory I can use for example find . -type f | wc -l to show a count of how many files are in that directory and in its subdirectories, but what I'd like is to be able to generate a complete list of all subdirectories (and sub-subdirectories etc) each with a count of all files contained in it and its subdirectories - if possible ranked by count, descending.

Eg if my file structure looks like this:

Home/
  file1.txt
  file2.txt
  Docs/
    file3.txt
    Notes/
      file4.txt
      file5.txt
    Queries/
      file6.txt
  Photos/
    file7.jpg

The output would be something like this:

7  Home
4  Home/Docs
2  Home/Docs/Notes
1  Home/Docs/Queries
1  Home/Photos

Any suggestions greatly appreciated. (Also a quick explanation of the answer, so I can learn from this!). Thanks.

Body:
See following example: sort by column 2 reversely. Use sort -k 2 -r. -k 2 means sort with column 2 (space separated), -r means reverse.

# ls -lF /mnt/sda1/var/lib/docker/165536.165536/aufs/mnt/ | sort -k 2 -r
total 972
drwxr-xr-x   65 165536   165536        4096 Jun  5 12:23 ad45ea3c6a03aa958adaa4d5ad6fc25d31778961266972a69291d3664e3f4d37/
drwxr-xr-x   19 165536   165536        4096 Jun  6 06:46 7fa7f957669da82a8750e432f034be6f0a9a7f5afc0a242bb00eb8024f77d683/
drwxr-xr-x    2 165536   165536        4096 May  8 02:20 49e067ffea226cfebc8b95410e90c4bad6a0e9bc711562dd5f98b7d755fe6efb/
drwxr-xr-x    2 165536   165536        4096 May  8 01:19 45ec026dd49c188c68b55dcf98fda27d1f9dd32f825035d94849b91c433b6dd3/
drwxr-xr-x    2 165536   165536        4096 Mar 13 06:08 0d6e95d4605ab34d1454de99e38af59a267960999f408f720d0299ef8d90046e/
drwxr-xr-x    2 165536   165536        4096 Mar 13 02:25 e9b252980cd573c78065e8bfe1d22f01b7ba761cc63d3dbad284f5d31379865a/
drwxr-xr-x    2 165536   165536        4096 Mar 13 02:24 f4aa333b9c208b18faf00b00da150b242a7a601693197c1f1ca78b9ab2403409/
drwxr-xr-x    2 165536   165536        4096 Mar 13 02:24 3946669d530695da2837b2b5ed43afa11addc25232b29cc085a19c769425b36b/
drwxr-xr-x    2 165536   165536        4096 Mar 11 11:11 44293f77f63806a58d9b97c3c9f7f1397b6f0935e236250e24c9af4a73b3e35b/


问:
JQuery click() on anchor tag not firing from an injected script inside WebBrowser control
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

```<code><li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
<a href="javascript:void(0)" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
</li>
</code>```

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.

答:
What my theory about this is that the click function was not actually bound to the element. This can be due to the html was not yet in the page when the script or binding of click is executed. Try checking the binded click in saveLink.click();

try to make it in the format

$(body).delegate(saveLink, 'click', function() {
    //try alert here to check
});

Body:
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

Save Record                [Ctrl+S]

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.


问:
Taking the second last row with only one select in SQL Server?
I was trying to select the second last row with SQL Server. So I wrote a query like this:

```<code>SELECT TOP 1 * From Cinema
WHERE CinemaID!=(SELECT TOP 1 CinemaID
                 FROM Cinema
                 ORDER BY CinemaID DESC)
ORDER BY CinemaID DESC
</code>```

and it did what I need. But I want to do the same thing with only one select.

I read that the LIMIT clause in MySql does that. But I couldn't find any equivalent
of that. So I appreciate any help about finding something useful.

答:
The easiest way to get second last row from sql table is user ORDER BY CinemaID DESC and set LIMIT 1,1

TRY THIS

```<code>SELECT * from `Cinema` ORDER BY `CinemaID` DESC LIMIT 1,1
</code>```

Body:
I was trying to select the second last row with SQL Server. So I wrote a query like this:

SELECT TOP 1 * From Cinema
WHERE CinemaID!=(SELECT TOP 1 CinemaID
                 FROM Cinema
                 ORDER BY CinemaID DESC)
ORDER BY CinemaID DESC

and it did what I need. But I want to do the same thing with only one select.

I read that the LIMIT clause in MySql does that. But I couldn't find any equivalent
of that. So I appreciate any help about finding something useful.

Body:
The easiest way to get second last row from sql table is user ORDER BY CinemaID DESC and set LIMIT 1,1

TRY THIS

SELECT * from `Cinema` ORDER BY `CinemaID` DESC LIMIT 1,1


问:
node.js driver for mysql works in console but not in actual code
I have .js file with following code:

```<code>var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");
</code>```

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

答:
You should use single quote or double quote to enclose string.you have used `  instead of '
Also remove semicolon after host:'localhost'. there should be a comma instead of semicolon

your code should be like this

```<code> var connection = mysql.createConnection({host:'localhost',user:'root',password:'password',database: 'databasename'});

function select(id,tablename){

  connection.connect();
  connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {
    var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */

  });
}
</code>```

Body:
I have .js file with following code:

var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

Body:
You should use single quote or double quote to enclose string.you have used `  instead of '
Also remove semicolon after host:'localhost'. there should be a comma instead of semicolon

your code should be like this

 var connection = mysql.createConnection({host:'localhost',user:'root',password:'password',database: 'databasename'});

function select(id,tablename){

  connection.connect();
  connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {
    var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */

  });
}


答:
You can use the properties file to solve your problem, like u can have two property files depending on the environment.

1) config_staging.properties
2) config_production.properties

and move your staging email configuration to  config_staging.properties, move your production configuration to  config_production.properties.

which will be configured while running the app.

for example,

config_staging.properties

```<code> smtp.username = "xx12@xyz.com";
 smtp.password = "15sss67$";
</code>```

config_production.properties

```<code>smtp.username = "AKYeeeELEQAGAA";
smtp.password = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
</code>```

then inject them into EmailUtility class,

```<code>@Value("${smtp.username}")
private String smtpUsername;

@Value("${smtp.password}")
private String smtpPassword;
</code>```

Title: How to dynamically choose the configurations based on the environment in JAVA?

Body:
You can use the properties file to solve your problem, like u can have two property files depending on the environment.

1) config_staging.properties
2) config_production.properties

and move your staging email configuration to  config_staging.properties, move your production configuration to  config_production.properties.

which will be configured while running the app.

for example,

config_staging.properties

 smtp.username = "xx12@xyz.com";
 smtp.password = "15sss67$";

config_production.properties

smtp.username = "AKYeeeELEQAGAA";
smtp.password = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";

then inject them into EmailUtility class,

@Value("${smtp.username}")
private String smtpUsername;

@Value("${smtp.password}")
private String smtpPassword;


问:
deploying to other Server gives ClassNotFoundException TIBCO JMS
I was able to deploy my app successfully in dev. I am using Spring JMS template to communicate with Tibco Client and in weblogic i have setup a foreign server with destination queue as Tibco queue and connection factory with Tibco connection factory. My JNDI Initial Context Factory: is tcp://name:port...I was able to publish the message and listen to it. No issues.

ISSUE:
When deploying to QA (the war from dev is taken and placed into QA) and during the deployment process we get this

```<code>Caused by: javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory]]
    at weblogic.utils.StackTraceDisabled.unknownMethod()
Caused by: javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory]
    ... 1 more
Caused by: java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory
    ... 1 more
</code>```

Any suggestions on what might be going wrong?

EDIT: People have suggested that this is a clear class path error. But in dev i did not include anything in class path on start server in weblogic.

答:
You need TibjmsInitialContextFactory Jar in order to make the above code work.

Below are the Maven Dependencies in case you are using Maven project:

```<code><dependency>
    <groupId>com.tibco</groupId>
    <artifactId>tibjms</artifactId>
    <version>8.3</version>
</dependency>
<dependency>
    <groupId>com.tibco</groupId>
    <artifactId>tibcrypt</artifactId>
    <version>8.3</version>
</dependency>
</code>```

Body:
I was able to deploy my app successfully in dev. I am using Spring JMS template to communicate with Tibco Client and in weblogic i have setup a foreign server with destination queue as Tibco queue and connection factory with Tibco connection factory. My JNDI Initial Context Factory: is tcp://name:port...I was able to publish the message and listen to it. No issues.

ISSUE:
When deploying to QA (the war from dev is taken and placed into QA) and during the deployment process we get this

Caused by: javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory]]
    at weblogic.utils.StackTraceDisabled.unknownMethod()
Caused by: javax.naming.NoInitialContextException: Cannot instantiate class: com.tibco.tibjms.naming.TibjmsInitialContextFactory [Root exception is java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory]
    ... 1 more
Caused by: java.lang.ClassNotFoundException: com.tibco.tibjms.naming.TibjmsInitialContextFactory
    ... 1 more

Any suggestions on what might be going wrong?

EDIT: People have suggested that this is a clear class path error. But in dev i did not include anything in class path on start server in weblogic.

Body:
You need TibjmsInitialContextFactory Jar in order to make the above code work.

Below are the Maven Dependencies in case you are using Maven project:

<dependency>
    <groupId>com.tibco</groupId>
    <artifactId>tibjms</artifactId>
    <version>8.3</version>
</dependency>
<dependency>
    <groupId>com.tibco</groupId>
    <artifactId>tibcrypt</artifactId>
    <version>8.3</version>
</dependency>


问:
How to split a '*' String in Java
i have problem to split string with 'split_', it seem my java netbean cant split when 'split_' is used.

any idea how we can overcame this?

i refer to this solution but it can only split without the used of '*'.       How to split a string in Java

```<code>    String echoPHP= "test*split_*test2";

    String[] strArray = echoPHP.split("*split_*");

    String part1 = strArray2[0]; // 004
    String part2 = strArray2[1]; // 034556

    System.out.println(strArray[0]);
    System.out.println(strArray[1]);
</code>```

error is:

```<code>    Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*split_*
</code>```

output supposed to be:

```<code>test
test2
</code>```

答:
Here are different cases to split string in java. You can use one which may fit in your application.

case 1 : Here is code to split string by a character "." :

```<code>String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
   system.out.println(imageNameArray[i]);
}
</code>```

And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.

```<code>String imageName = "picture1  . jpg";
    String [] imageNameArray = imageName.split("\\s*.\\s*");
        for(int i =0; i< imageNameArray.length ; i++)
        {
           system.out.println(imageNameArray[i]);
        }
</code>```

Here, \\s* is there to consider the spaces and give you only required splitted strings.

Now, suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

```<code>import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}
</code>```

Here list result will have parameters n1_1,n2_2,n4_4.

Title: How to split a '*' String in Java

Body:
i have problem to split string with 'split_', it seem my java netbean cant split when 'split_' is used.

any idea how we can overcame this?

i refer to this solution but it can only split without the used of '*'.       How to split a string in Java

    String echoPHP= "test*split_*test2";

    String[] strArray = echoPHP.split("*split_*");

    String part1 = strArray2[0]; // 004
    String part2 = strArray2[1]; // 034556

    System.out.println(strArray[0]);
    System.out.println(strArray[1]);

error is:

    Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*split_*

output supposed to be:

test
test2

Body:
Here are different cases to split string in java. You can use one which may fit in your application.

case 1 : Here is code to split string by a character "." :

String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
   system.out.println(imageNameArray[i]);
}

And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.

String imageName = "picture1  . jpg";
    String [] imageNameArray = imageName.split("\\s*.\\s*");
        for(int i =0; i< imageNameArray.length ; i++)
        {
           system.out.println(imageNameArray[i]);
        }

Here, \\s* is there to consider the spaces and give you only required splitted strings.

Now, suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}

Here list result will have parameters n1_1,n2_2,n4_4.