问:
Screen reader i.e. JAWS doesn't read text of a button when text is changed on click of that button?
I am facing one minor difficulty while making my software ARIA accessibility enabled. Any kind of help would be appreciated!

I have a div which works as a 'Edit' button with click event using jQuery. I am changing text of that button 'Save' on click event. Screen reader like JAWS reads "Edit button" when the focus comes to that button for the first time.

But I want JAWS to recognise the change happened after click event i.e. After click JAWS should read "Save button". Any help? (Note that even after click, focus stays on the same button)

HTML code for that div/button:

```<code><div role="button" class="js-btn" aria-label="Edit">Edit</div>
</code>```

jQuery code to handle click event:

```<code>$(document).on("click",".js-btn",function(e){
    $(this).innerHTML("Save");
    $(this).attr("aria-label","Save");
});
</code>```

答:
(Note that even after click, focus stays on the same button)

If it's your expected behaviour, this is the answer to your question : as long as the focus stays on the element the screenreader won't re-read its data.

Use two buttons, show the "Save" button after clicking on "Edit" and hide the "edit" button.

```<code><button id="edit">Edit</div>
<button id="save" class="hidden">Save</div>

$("#edit").on("click", function() {
    $(this).hide();
    $("#save").removeClass("hidden").focus();
});
</code>```

Body:
I am facing one minor difficulty while making my software ARIA accessibility enabled. Any kind of help would be appreciated!

I have a div which works as a 'Edit' button with click event using jQuery. I am changing text of that button 'Save' on click event. Screen reader like JAWS reads "Edit button" when the focus comes to that button for the first time.

But I want JAWS to recognise the change happened after click event i.e. After click JAWS should read "Save button". Any help? (Note that even after click, focus stays on the same button)

HTML code for that div/button:

Edit

jQuery code to handle click event:

$(document).on("click",".js-btn",function(e){
    $(this).innerHTML("Save");
    $(this).attr("aria-label","Save");
});

Body:
(Note that even after click, focus stays on the same button)

If it's your expected behaviour, this is the answer to your question : as long as the focus stays on the element the screenreader won't re-read its data.

Use two buttons, show the "Save" button after clicking on "Edit" and hide the "edit" button.

<button id="edit">Edit</div>
<button id="save" class="hidden">Save</div>

$("#edit").on("click", function() {
    $(this).hide();
    $("#save").removeClass("hidden").focus();
});


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: Sort block of numbers into columns

Body:
i have a file with alot of data written out of a simulation:

  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.93071889E-02
  0.14952319E-13  0.55746201E-11  0.89816722E-11  0.46833532E-11  0.14964636E-13
 -0.92995325E-47  0.79969902E-46  0.00000000E+00 -0.21442451-105 -0.86924526E-93
  0.00000000E+00 -0.85777333E-93  0.48179949-102  0.00000000E+00
  0.18614378E-01
  0.12050471E-12  0.44928328E-10  0.72404536E-10  0.37744496E-10  0.12066634E-12
  0.25848493E-36 -0.13804858E-35  0.56376226E-83  0.20648121E-74 -0.89608567E-66
 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

Desired Output is: Each Block of Data written in its own column and the column starts with the "header" of each block, which is the first number. For example the last block should look like this:

0.18614378E-01 0.12050471E-12  0.44928328E-10  0.72404536E-10 0.37744496E-10  0.12066634E-12 0.25848493E-36 -0.13804858E-35  0.56376226E-83 0.20648121E-74 -0.89608567E-66 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

I thought about using AWK with FS=' ', but i don’t know how to tell my bash script to stop after reading 15 numbers and how to save those 15 numbers and output them into a separate file (using printf maybe?)

Thanks!

Body:
awk solution:

awk 'BEGIN{ t="" }NR>1 && NF==1{ print t > "file"++c; t="" }
     { t=(t!="")? sprintf("%s  %s",t,$0) : sprintf("%s",$0) }
     END{ if (t) print t > "file"++c }' file

Results:

> cat file1
0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00

> cat file2
0.93071889E-02  0.14952319E-13  0.55746201E-11  0.89816722E-11  0.46833532E-11  0.14964636E-13  -0.92995325E-47  0.79969902E-46  0.00000000E+00 -0.21442451-105 -0.86924526E-93  0.00000000E+00 -0.85777333E-93  0.48179949-102  0.00000000E+00

> cat file3
0.18614378E-01  0.12050471E-12  0.44928328E-10  0.72404536E-10  0.37744496E-10  0.12066634E-12  0.25848493E-36 -0.13804858E-35  0.56376226E-83  0.20648121E-74 -0.89608567E-66  -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82


问:
java.lang.ClassNotFoundException: com.intellij.junit5.JUnit5IdeaTestRunner using spek in kotlin
I am very new using spek in kotlin testing. When using spek , got the following error on logcat. I don't why I got this

```<code>java.lang.ClassNotFoundException: com.intellij.junit5.JUnit5IdeaTestRunner
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.intellij.rt.execution.junit.JUnitStarter.getAgentClass(JUnitStarter.java:252)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
</code>```

I have following dependencies on gradle file

```<code>testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.0-beta3'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.0-beta3'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M3'
</code>```

Test file

```<code>import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.junit.Assert.assertEquals
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith

@RunWith(JUnitPlatform::class)
class ExampleUnitTest : Spek({
    val x = 2
    val y = 3

    given("x = $x and y = $y") {
        val sum = x + y

        it("should be that x + y = 5") {
            assertEquals(5, sum)
        }

        it("should be that x - y = -1") {
            val subtract = x - y
            assertEquals(-1, subtract)
        }

    }
})
</code>```

Can you please suggest, how to get this kind of error. I would appericate your valuable suggation or comments on this topic.

答:
You just have to add the library, which contains the runner (also see http://junit.org/junit5/docs/current/user-guide/#installation)

```<code>testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M3'
</code>```

I encourage you also to update your spek-libs to the most recent version:

```<code>testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M5'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M5'
</code>```

Update

Currently, the most recent junit lib is not compatible with whte M5-Milestone, so use the version M4

```<code>testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'
</code>```

Body:
I am very new using spek in kotlin testing. When using spek , got the following error on logcat. I don't why I got this

java.lang.ClassNotFoundException: com.intellij.junit5.JUnit5IdeaTestRunner
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.intellij.rt.execution.junit.JUnitStarter.getAgentClass(JUnitStarter.java:252)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

I have following dependencies on gradle file

testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.0-beta3'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.0-beta3'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M3'

Test file

import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.junit.Assert.assertEquals
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith

@RunWith(JUnitPlatform::class)
class ExampleUnitTest : Spek({
    val x = 2
    val y = 3

    given("x = $x and y = $y") {
        val sum = x + y

        it("should be that x + y = 5") {
            assertEquals(5, sum)
        }

        it("should be that x - y = -1") {
            val subtract = x - y
            assertEquals(-1, subtract)
        }

    }
})

Can you please suggest, how to get this kind of error. I would appericate your valuable suggation or comments on this topic.

Body:
You just have to add the library, which contains the runner (also see http://junit.org/junit5/docs/current/user-guide/#installation)

testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M3'

I encourage you also to update your spek-libs to the most recent version:

testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M5'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M5'

Update

Currently, the most recent junit lib is not compatible with whte M5-Milestone, so use the version M4

testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'


问:
RedisClusterException when trying to write using Celery
My environment:
I have three Ubuntu servers.
One server is used as a load balancer using Nginx.
The other two servers contain the exact same project (are identical apart from redis where one box is the master and other is the slave).

The Programs/Applications I'm using
Python,
Gunicorn,
Django,
Celery,
Redis,
Sentinel

What My project does:
I have a URL which takes in a GET request, does some logic regarding the request and saves into redis.

```<code>def save(key, value):
    conn = redis_cluster_connect()
    print conn
    conn.set(key, value)
    conn.set('bar','foo')
</code>```

This was working fine when my connection was:

```<code>def redis_connect():
    print 'redis connected'
    return redis.Redis(host="xxx.xx.xxx.x", port=6380, db=1) # CHANGE TO THE REDIS PORT THAT IS ACTIVE
</code>```

But when I use the cluster connection:

```<code>def redis_cluster_connect():
    startup_nodes = [{"host": "xxx.xx.xxx.x", "port": "6380"}]
    rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)

return rc
</code>```

The Error I get:

```<code>[2016-09-15 13:28:59,682: INFO/MainProcess] Received task: testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743]
    [2016-09-15 13:28:59,684: WARNING/Worker-1] Oh no! Task failed: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",)
    [2016-09-15 13:28:59,685: ERROR/MainProcess] Task testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743] raised unexpected: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",)
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
        R = retval = fun(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__
        return self.run(*args, **kwargs)
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 50, in mobilise_stops
        save(mobilise_stops.request.id, 'Success')
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 28, in save
        conn = redis_cluster_connect()
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 19, in redis_cluster_connect
        rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/client.py", line 157, in __init__
        **kwargs
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/connection.py", line 83, in __init__
        self.nodes.initialize()
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/nodemanager.py", line 148, in initialize
        raise RedisClusterException("ERROR sending 'cluster slots' command to redis server: {0}".format(node))
    RedisClusterException: ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}
</code>```

When I run redis-cli and set a variable on the master (on server 1) I can retrieve it on the slave (on server 2)

```<code>server 1:
xxx.xx.xxx.x:6380> set test 100
OK

server 2:
xxx.xx.xxx.x:6381> get test
"100"
</code>```

When I try doing the cluster slots command in the redis client I get the same error as the above.

```<code>xxx.xx.xxx.x:6380> cluster slots
(error) ERR unknown command 'cluster'
</code>```

One thing to consider is my redis config file doesn't have a tcp socket, when I tried using tcp redis would not work. It gave me an error when I tried running redis. This was changed to the default Unixsocket that comes in the default redis.conf file

From:

```<code>tcp-backlog 511
</code>```

To:

```<code>unixsocket /var/run/redis/redis.sock
unixsocketperm 700
</code>```

答: For my case the problem was in version redis-py-cluster (1.3.4), after reinstallation to version 1.3.1 everything works well for me. I guess there was some issue that version of python package.</p>

Body:
My environment:
I have three Ubuntu servers.
One server is used as a load balancer using Nginx.
The other two servers contain the exact same project (are identical apart from redis where one box is the master and other is the slave).

The Programs/Applications I'm using
Python,
Gunicorn,
Django,
Celery,
Redis,
Sentinel

What My project does:
I have a URL which takes in a GET request, does some logic regarding the request and saves into redis.

def save(key, value):
    conn = redis_cluster_connect()
    print conn
    conn.set(key, value)
    conn.set('bar','foo')

This was working fine when my connection was:

def redis_connect():
    print 'redis connected'
    return redis.Redis(host="xxx.xx.xxx.x", port=6380, db=1) # CHANGE TO THE REDIS PORT THAT IS ACTIVE

But when I use the cluster connection:

def redis_cluster_connect():
    startup_nodes = [{"host": "xxx.xx.xxx.x", "port": "6380"}]
    rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)

return rc

The Error I get:

[2016-09-15 13:28:59,682: INFO/MainProcess] Received task: testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743]
    [2016-09-15 13:28:59,684: WARNING/Worker-1] Oh no! Task failed: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",)
    [2016-09-15 13:28:59,685: ERROR/MainProcess] Task testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743] raised unexpected: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",)
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
        R = retval = fun(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__
        return self.run(*args, **kwargs)
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 50, in mobilise_stops
        save(mobilise_stops.request.id, 'Success')
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 28, in save
        conn = redis_cluster_connect()
      File "/var/www/gateway/venv/gateway/testapp/tasks.py", line 19, in redis_cluster_connect
        rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/client.py", line 157, in __init__
        **kwargs
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/connection.py", line 83, in __init__
        self.nodes.initialize()
      File "/usr/local/lib/python2.7/dist-packages/rediscluster/nodemanager.py", line 148, in initialize
        raise RedisClusterException("ERROR sending 'cluster slots' command to redis server: {0}".format(node))
    RedisClusterException: ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}

When I run redis-cli and set a variable on the master (on server 1) I can retrieve it on the slave (on server 2)

server 1:
xxx.xx.xxx.x:6380> set test 100
OK

server 2:
xxx.xx.xxx.x:6381> get test
"100"

When I try doing the cluster slots command in the redis client I get the same error as the above.

xxx.xx.xxx.x:6380> cluster slots
(error) ERR unknown command 'cluster'

One thing to consider is my redis config file doesn't have a tcp socket, when I tried using tcp redis would not work. It gave me an error when I tried running redis. This was changed to the default Unixsocket that comes in the default redis.conf file

From:

tcp-backlog 511

To:

unixsocket /var/run/redis/redis.sock
unixsocketperm 700


问:
I'm looking for a clone of Google Instant that dynamically changes the page as you continue to type (autocomplete)
I'm trying to find a tutorial or script that has most of the Google Instant functionality but I would be hit my API instead of Google and then displaying results from my domain. </p>

答: It's just an AJAX autocomplete. jQuery UI has a built-in autocompleter that's very easy to work with.</p>

ContentLicense: CC BY-SA 2.5


问:
Scanning multiple files and printing them alphabetically
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

```<code>File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}
</code>```

Output:

```<code>dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$
</code>```

Can I do it with the output being:

```<code>a.txt
b.txt
c.txt
</code>```

Thank you in advance!

答:
Thank you to those who answered. I thought of a very simple solution:

```<code>File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
Arrays.sort(listOfFiles);

for (File path : listOfFiles) {
    System.out.println(path);
}
</code>```

hahahaha my apologies everyone.

Body:
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}

Output:

dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$

Can I do it with the output being:

a.txt
b.txt
c.txt

Thank you in advance!

Body:
Thank you to those who answered. I thought of a very simple solution:

File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
Arrays.sort(listOfFiles);

for (File path : listOfFiles) {
    System.out.println(path);
}

hahahaha my apologies everyone.


问:
jquery getting icon from
 tag and place it to a dropdown icon in button
I have created dropdown with accordion using bootstrap. what im going to do is when they click dropdown header
 get icon and place it to dropdown button

```<code> <button class="btn btn-search catbutton dropdown" type="button" data-toggle="dropdown">
 span class="label-icon"><i class="fa fa-bars"></i></span>
    </button>

<ul class="dropdown-menu accordion" role="menu">
    <li role="presentation" class="have-child">
        <a class="link" role="menuitem">
            <i class="fa fa-building"></i>Properties<i class="fa fa-chevron-down"></i>
        </a>

        <ul id="properties" class="panel-collapse collapse submenu">
            <li><a>All</a></li>
            <li><a>Property For Sale</a></li>
            <li><a>Property For Rent</a></li>
            <li><a>Land For Sale</a></li>
        </ul>
    </li>
</ul>
</code>```

I have manage to get the text and place it there but not the icon down below

```<code>$(".dropdown-menu li a").click(function () {
    $(".catbutton").text($(this).text());
});
</code>```

Please help me to solve this

答:
You are just working with text not html ,if you want the icon onclick then

try this

```<code>$(".dropdown-menu li a").click(function () {
    $(".catbutton").html($(this).html());
});
</code>```

I thing it will help you.

Title: jquery getting icon from <li> tag and place it to a dropdown icon in button

Body:
I have created dropdown with accordion using bootstrap. what im going to do is when they click dropdown header
 get icon and place it to dropdown button

 <button class="btn btn-search catbutton dropdown" type="button" data-toggle="dropdown">
 span class="label-icon">
    </button>

            Properties

All

Property For Sale

Property For Rent

Land For Sale

I have manage to get the text and place it there but not the icon down below

$(".dropdown-menu li a").click(function () {
    $(".catbutton").text($(this).text());
});

Please help me to solve this

Body:
You are just working with text not html ,if you want the icon onclick then

try this

$(".dropdown-menu li a").click(function () {
    $(".catbutton").html($(this).html());
});

I thing it will help you.


问:
Nullify QString data bytes
I use QStrings to store passwords. If to be more precise, I use QStrings to fetch passwords from GUI.
The point is that after password usage/appliance I need to nullify (zero) internal QStrings data bytes with password to eliminate it from memory entirely.

Here are my investigations:

After QString destruction it's data remains in memory nonzeroed;

When I attempt to modify QString to fulfill it with zeroes it triggers copy-on-write idiom and allocates new memory for a modified variant of data. Old data remains untouched. Same happens even if I use QString::data() method. Not really sure why - probably because it returns not raw char * but QChar *;

QString::clear(), = "" does actually the same COW as described above.

Q: How can I implement proper QString cleanup to prevent passwords leaks?

答:
I've got two possible ways of bypassing copy-on-write. I've tried them and they seem to work - didn't use the Qt Creator's memory viewer, but the implicitly shared QStrings used in my code both pointed to the same zeroed data afterwards.

Using constData()

As written in the Qt docs for QString::data() method:

For read-only access, constData() is faster because it never causes a
  deep copy to occur.

So the possible solution looks like this:

```<code>QString str = "password";
QString str2 = str;
QChar* chars = const_cast<QChar*>(str.constData());
for (int i = 0; i < str.length(); ++i)
    chars[i] = '0';
// str and str2 are now both zeroed
</code>```

This is a legitimate use of const_cast since the underlying data is not really const, so no undefined behaviour here.

Using iterators

From the Qt docs for implicit sharing:

An implicitly shared class has control of its internal data. In any
  member functions that modify its data, it automatically detaches
  before modifying the data. Notice, however, the special case with
  container iterators; see Implicit sharing iterator problem.

So let's move to the section describing this iterator problem:

Implicit sharing has another consequence on STL-style iterators: you
  should avoid copying a container while iterators are active on that
  container. The iterators point to an internal structure, and if you
  copy a container you should be very careful with your iterators. E.g.:

```<code>QVector<int> a, b;
a.resize(100000); // make a big vector filled with 0.

QVector<int>::iterator i = a.begin();
// WRONG way of using the iterator i:
b = a;
/*
    Now we should be careful with iterator i since it will point to shared data
    If we do *i = 4 then we would change the shared instance (both vectors)
    The behavior differs from STL containers. Avoid doing such things in Qt.
*/

a[0] = 5;
/*
    Container a is now detached from the shared data,
    and even though i was an iterator from the container a, it now works as an iterator in b.
*/
</code>```

It is my understanding that, based on the above docs fragment, you should be able to exploit this "wrong usage" of iterators to manipulate your original string with iterators as they don't trigger copy-on-write. It's important that you "intercept" the begin() and end() before any copying occurs:

```<code>QString str = "password";
QString::iterator itr = str.begin();
QString::iterator nd = str.end();
QString str2 = str;

while (itr != nd)
{
    *itr = '0';
    ++itr;
} // str and str2 still point to the same data and are both zeroed
</code>```

Title: Nullify QString data bytes

Body:
I've got two possible ways of bypassing copy-on-write. I've tried them and they seem to work - didn't use the Qt Creator's memory viewer, but the implicitly shared QStrings used in my code both pointed to the same zeroed data afterwards.

Using constData()

As written in the Qt docs for QString::data() method:

For read-only access, constData() is faster because it never causes a
  deep copy to occur.

So the possible solution looks like this:

QString str = "password";
QString str2 = str;
QChar* chars = const_cast<QChar*>(str.constData());
for (int i = 0; i < str.length(); ++i)
    chars[i] = '0';
// str and str2 are now both zeroed

This is a legitimate use of const_cast since the underlying data is not really const, so no undefined behaviour here.

Using iterators

From the Qt docs for implicit sharing:

An implicitly shared class has control of its internal data. In any
  member functions that modify its data, it automatically detaches
  before modifying the data. Notice, however, the special case with
  container iterators; see Implicit sharing iterator problem.

So let's move to the section describing this iterator problem:

Implicit sharing has another consequence on STL-style iterators: you
  should avoid copying a container while iterators are active on that
  container. The iterators point to an internal structure, and if you
  copy a container you should be very careful with your iterators. E.g.:

QVector<int> a, b;
a.resize(100000); // make a big vector filled with 0.

QVector<int>::iterator i = a.begin();
// WRONG way of using the iterator i:
b = a;
/*
    Now we should be careful with iterator i since it will point to shared data
    If we do *i = 4 then we would change the shared instance (both vectors)
    The behavior differs from STL containers. Avoid doing such things in Qt.
*/

a[0] = 5;
/*
    Container a is now detached from the shared data,
    and even though i was an iterator from the container a, it now works as an iterator in b.
*/

It is my understanding that, based on the above docs fragment, you should be able to exploit this "wrong usage" of iterators to manipulate your original string with iterators as they don't trigger copy-on-write. It's important that you "intercept" the begin() and end() before any copying occurs:

QString str = "password";
QString::iterator itr = str.begin();
QString::iterator nd = str.end();
QString str2 = str;

while (itr != nd)
{
    *itr = '0';
    ++itr;
} // str and str2 still point to the same data and are both zeroed


问:
Is bulk update faster than single update in db2?
I have a Table with 10 columns and in that table I have thousands/millions of rows.
In some scenario, I want to update more than 10K records at a time. currently my scenario code works sequentially like,

```<code>for i in (primary key ids for all records to be updated)
     executeupdate(i)
</code>```

what I thought is instead of running same query 10K times, I will add all ids in a string and run a single update query like,

```<code>executeupdate(all ids)
</code>```

actual DB queries can be like this,

suppose I have primary key ids like,

```<code>10001,10002,10003,10004,10005
</code>```

so in first case My queries will be like

```<code>update tab1 set status="xyz" where Id="10001"
update tab1 set status="xyz" where Id="10002"
update tab1 set status="xyz" where Id="10003"
update tab1 set status="xyz" where Id="10004"
update tab1 set status="xyz" where Id="10005"
</code>```

and My bulk update query will be like,

```<code>update tab1 set status="xyz" where id in ("10001","10002","10003","10004","10005")
</code>```

so My question is, will I get any Performance improvement (executime time) by doing bulk update
or total query execution time will be same as for each record index scan will happen and update will take place?

Note : I am using DB2 9.5 as database

Thanks.

答:
I came here with same question a week back. Then I faced a situation where I had to update a table with around 3500 rows in mySQL database through JDBC.
I updated same table twice: once through a For loop, by iterating through a collection of objects, and once using a bulk update query. Here are my findings:

When I updated the data in the database through iteration, it took around 7.945 seconds to execute completely.

When I came up with a rather gigantic (where 'gigantic' means 183 pages long) update query and executed the same, it took around 2.24 seconds to complete the update process.

clearly, bulk update wins by a huge margin.

Why this Difference?

To answer this, let's see how a query actually gets executed in DBMS.

Unlike procedural languages, you instruct the DBMS what to do, but not how to do. The DBMS then does the followings.

Syntax checking, or more commonly called 'Parsing'. And parsing comprises of steps like Lexical Analysis, Syntactic Analysis, Semantic Parsing.

A series of optimization (Although the definition of 'optimization' itself may vary from product to product. At least that's what I learned while surfing through the internet. I don't have much knowledge about it though.).

execution.

Now, when you update a table in database row by row, each of the queries you execute goes through parsing, optimization and execution. In stead if you write a loop to create a rather long query, and then execute the same, it is parsed only once. And the amount of time you save by using batch update in place of iterative approach increases almost linearly with number of rows you update.

A few tips that might come handy while updating data in your database

It is always a good practice to use indexed columns as reference while writing Any query.

Try to use integers or numbers and not strings for sorting or searching data in database. Your server is way more comfortable in comparing two numbers than comparing two strings.

Avoid using views and 'in' clause. they make your task easier, but slows down your database. Use joins in stead.

Body:
I have a Table with 10 columns and in that table I have thousands/millions of rows.
In some scenario, I want to update more than 10K records at a time. currently my scenario code works sequentially like,

for i in (primary key ids for all records to be updated)
     executeupdate(i)

what I thought is instead of running same query 10K times, I will add all ids in a string and run a single update query like,

executeupdate(all ids)

actual DB queries can be like this,

suppose I have primary key ids like,

10001,10002,10003,10004,10005

so in first case My queries will be like

update tab1 set status="xyz" where Id="10001"
update tab1 set status="xyz" where Id="10002"
update tab1 set status="xyz" where Id="10003"
update tab1 set status="xyz" where Id="10004"
update tab1 set status="xyz" where Id="10005"

and My bulk update query will be like,

update tab1 set status="xyz" where id in ("10001","10002","10003","10004","10005")

so My question is, will I get any Performance improvement (executime time) by doing bulk update
or total query execution time will be same as for each record index scan will happen and update will take place?

Note : I am using DB2 9.5 as database

Thanks.


问:
Converting Curl command to PHP not working
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

```<code>[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#
</code>```

Here is the curl command in PHP:

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
</code>```

This is response: 400 Bad Request

Here is the Verbose Output:

```<code>Verbose information:
</code>```

```* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6
```

400 Bad Request

答:
Add this line, as your API will respond only to POST requests, and 400 error means you are asking API with Non-POST method,

Add this line and it should work ...

```<code>curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
</code>```

Body:
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#

Here is the curl command in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

This is response: 400 Bad Request

Here is the Verbose Output:

Verbose information:

* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6

400 Bad Request

Body:
Add this line, as your API will respond only to POST requests, and 400 error means you are asking API with Non-POST method,

Add this line and it should work ...

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");


问:
DOM parser settings to avoid XML Injection attack
What are the below settings for a DOM parser used for? Anything wrong in setting these attributes? Could they cause any exceptions?</p>

```<code> DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
  dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
Document doc = dbf.newDocumentBuilder().parse(new InputSource(byteArrayInputStream));
</code>```

答:
That helps to avoid the XML External Entity Injection.

I was using HP Fortify SCA(Source Code Analyzer), It  was able to find these kind of issues if you are not specifying these attributes.

You can find more information here:https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet

Body:
What are the below settings for a DOM parser used for? Anything wrong in setting these attributes? Could they cause any exceptions?

 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
  dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
Document doc = dbf.newDocumentBuilder().parse(new InputSource(byteArrayInputStream));


问:
For loop without incrementing in iteration statement
I just wanted to ask whether this is valid as this is the only way my script works as expected:

```<code>for (var j = 0; j < items.length; j) {
    for (var k = 1; k <= 3; k++) {
        $(items.eq(j)).appendTo('.col'+k);
        j++;
    }
}
</code>```

notice the j that is not incrementing inside the for statement.

If I increment j, the loop ignores every 4th div for some reason and I can't explain the reason.

Here's a demo of this script.

My main question is whether this is a valid method, and if it's not, do you have a better solution for distributing the divs in each column?

答:
I am answering to the question in Title. If you want to increment for loop depending on a case you can use the following code.</p>

```<code>for (int i =1 ;i<10;i=i+0){
if (case)
 do your work here.
  i++;
else
  do nothing here
}
</code>```

Body:
I just wanted to ask whether this is valid as this is the only way my script works as expected:

for (var j = 0; j < items.length; j) {
    for (var k = 1; k <= 3; k++) {
        $(items.eq(j)).appendTo('.col'+k);
        j++;
    }
}

notice the j that is not incrementing inside the for statement.

If I increment j, the loop ignores every 4th div for some reason and I can't explain the reason.

Here's a demo of this script.

My main question is whether this is a valid method, and if it's not, do you have a better solution for distributing the divs in each column?

Body:
I am answering to the question in Title. If you want to increment for loop depending on a case you can use the following code.

for (int i =1 ;i<10;i=i+0){
if (case)
 do your work here.
  i++;
else
  do nothing here
}


问:
Find rows from table A without record in joined table B
I have two tables called Employee (columns: Id, Name) and DataSource (columns: Id, EmployeeId, DataSourceName).

Each employee can be exported to zero or multiple datasources and imagine following situation:

Employee table

```<code>+----+-------------+
| Id | Name        |
+----+-------------+
| 1  | Ivan        |
| 2  | Adam        |
+----+-------------+
</code>```

DataSource table:

```<code>+----+---------------------------------+
| Id | EmplpoyeeId   | DataSourceName  |
+----+---------------------------------+
| 1  | 1             | Source1         |
| 2  | 1             | Source2         |
| 3  | 2             | Source2         |
+----+---------------------------------+
</code>```

I need a query to determine which employee is not exported to 'Source1' (the result should be 'Adam' in this case as he is exported to 'Source2' only).

Tables Employee and DataSource can have large amount of records (thousands).

There are a few techniques to determine it and we need to find the one with best performance. There are few which came to my mind:

Left JOIN:

```<code>SELECT Employee.Id
FROM Employee
LEFT JOIN DataSource ON DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1'
WHERE DataSource.Id IS NULL
</code>```

INNER SELECT:

```<code>SELECT Employee.Id
FROM Employee
WHERE NOT EXIST (SELECT NULL FROM DataSource WHERE DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1')
</code>```

EXCEPTION:

```<code>SELECT Employee.ID
FROM Employee

EXCEPT

SELECT Employee.Id
FROM Employee
INNER JOIN DataSource ON DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1'
</code>```

Before starting benchmarking them I'd like to ask whether there are more ways which I should take into account (and might perform well). Could you please share your ideas for the best performant query.

答:
If you require further reading on the subject this article is good;

http://www.sqlinthewild.co.za/index.php/2010/03/23/left-outer-join-vs-not-exists/

It suggests that the NOT EXISTS will perform better as it doesn't need to complete the full join (does an Anti-Semi join instead of a Semi Join);

"That’s the major difference between these two. When using the LEFT OUTER JOIN … IS NULL technique, SQL can’t tell that you’re only doing a check for nonexistance. Optimiser’s not smart enough (yet). Hence it does the complete join and then filters. The NOT EXISTS filters as part of the join."

Body:
I have two tables called Employee (columns: Id, Name) and DataSource (columns: Id, EmployeeId, DataSourceName).

Each employee can be exported to zero or multiple datasources and imagine following situation:

Employee table

+----+-------------+
| Id | Name        |
+----+-------------+
| 1  | Ivan        |
| 2  | Adam        |
+----+-------------+

DataSource table:

+----+---------------------------------+
| Id | EmplpoyeeId   | DataSourceName  |
+----+---------------------------------+
| 1  | 1             | Source1         |
| 2  | 1             | Source2         |
| 3  | 2             | Source2         |
+----+---------------------------------+

I need a query to determine which employee is not exported to 'Source1' (the result should be 'Adam' in this case as he is exported to 'Source2' only).

Tables Employee and DataSource can have large amount of records (thousands).

There are a few techniques to determine it and we need to find the one with best performance. There are few which came to my mind:

Left JOIN:

SELECT Employee.Id
FROM Employee
LEFT JOIN DataSource ON DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1'
WHERE DataSource.Id IS NULL

INNER SELECT:

SELECT Employee.Id
FROM Employee
WHERE NOT EXIST (SELECT NULL FROM DataSource WHERE DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1')

EXCEPTION:

SELECT Employee.ID
FROM Employee

EXCEPT

SELECT Employee.Id
FROM Employee
INNER JOIN DataSource ON DataSource.EmployeeId = Employee.Id AND DataSource.DataSourceName = 'Source1'

Before starting benchmarking them I'd like to ask whether there are more ways which I should take into account (and might perform well). Could you please share your ideas for the best performant query.


问:
Clearest way to build html elements in jQuery
I've seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and also if any particular method is objectively better than another for any reason. Below are some examples of the styles and methods that I've seen.

```<code>var title = "Title";
var content = "Lorem ipsum";

// escaping endlines for a multi-line string
// (aligning the slashes is marginally prettier but can add a lot of whitespace)
var $element1 = $("\
    <div><h1>" + title + "</h1>\
        <div class='content'>  \
        " + content + "        \
        </div>                 \
    </div>                     \
");

// all in one
// obviously deficient
var $element2 = $("<div><h1>" + title + "</h1><div class='content'>" + content + "</div></div>");

// broken on concatenation
var $element3 = $("<div><h1>" +
                title +
                "</h1><div class='content'>" +
                content +
                "</div></div>");

// constructed piecewise
// (I've seen this with nested function calls instead of temp variables)
var $element4 = $("<div></div>");
var $title = $("<h1></h1>").html(title);
var $content = $("<div class='content'></div>").html(content);
$element4.append($title, $content);

$("body").append($element1, $element2, $element3, $element4);
</code>```

Please feel free to demonstrate any other methods/styles you might use.

答:
Here's an example that uses $(htmlString) and mimics the standard layout of HTML code:</p>

```<code>function getPage(title, contents) {
  return (
    $("<div>", {id: "container", class: "box"}).append(
      $("<div>", {class: "title"}).append(
        $("<h1>").text(title)
      ),
      $("<div>").html(contents)
    )
  );
}
</code>```

Body:
I've seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and also if any particular method is objectively better than another for any reason. Below are some examples of the styles and methods that I've seen.

var title = "Title";
var content = "Lorem ipsum";

// escaping endlines for a multi-line string
// (aligning the slashes is marginally prettier but can add a lot of whitespace)
var $element1 = $("\

" + title + "
\

  \
        " + content + "        \

                 \

                     \
");

// all in one
// obviously deficient
var $element2 = $("

" + title + "

" + content + "

");

// broken on concatenation
var $element3 = $("

" +
                title +
                "

" +
                content +
                "

");

// constructed piecewise
// (I've seen this with nested function calls instead of temp variables)
var $element4 = $("

");
var $title = $("

").html(title);
var $content = $("

").html(content);
$element4.append($title, $content);

$("body").append($element1, $element2, $element3, $element4);

Please feel free to demonstrate any other methods/styles you might use.

Body:
Here's an example that uses $(htmlString) and mimics the standard layout of HTML code:

function getPage(title, contents) {
  return (
    $("<div>", {id: "container", class: "box"}).append(
      $("<div>", {class: "title"}).append(
        $("<h1>").text(title)
      ),
      $("<div>").html(contents)
    )
  );
}


问:
How to get max element from list in Jinja2 (Flask)
I use Flask and Jinja2. Now, I need to set value for some foo variable to zero if bar is negative, otherwise leave it unchanged. There are several approaches, but I'd like to make something like:

```<code>foo = max(0, bar)
</code>```

The problem is that I can't find max filter in Jinja2. To resolve this issue I use:

```<code>{% set foo = [0, request.args.get('bar')|int - 25]|sort|last %}
</code>```

So the questions are:

1. Are there any max-like filters in Jinja2?

2. If no, then should I create a custom one?

3. And what about approach that I've used?

答:
Probably not. I couldn't find it in their documentation.

Python already has a native max() function, returning maximum of a list.

I would suggest a simple if statement. Set foo to 0 and if bar - 25 is positive, set foo to that. Perhaps more readable that way.

Body:
I use Flask and Jinja2. Now, I need to set value for some foo variable to zero if bar is negative, otherwise leave it unchanged. There are several approaches, but I'd like to make something like:

foo = max(0, bar)

The problem is that I can't find max filter in Jinja2. To resolve this issue I use:

{% set foo = [0, request.args.get('bar')|int - 25]|sort|last %}

So the questions are:

1. Are there any max-like filters in Jinja2?

2. If no, then should I create a custom one?

3. And what about approach that I've used?


问:
Mongo string query to MongoTemplate (java, springframework)
i have query

```<code>db.getCollection('collectionName').aggregate([
{
    $project: {
        '_id':1,
        'arrayField': {
            $filter: {
                input: '$arrayField',
                as: 'arrayField',
                cond: { $or: [
                    {$eq: [ [LUUID("********-****-****-****-************")],['$$arrayField._id'] ] },
                    {$eq: [ [LUUID("********-****-****-****-************")],['$$arrayField._id'] ] }
                  ] }
            }
        }
    }
}])
</code>```

How will it look in MongoTemplate? And it is possible to rewrite the cond?

Body:
i have query

db.getCollection('collectionName').aggregate([
{
    $project: {
        '_id':1,
        'arrayField': {
            $filter: {
                input: '$arrayField',
                as: 'arrayField',
                cond: { $or: [
                    {$eq: [ [LUUID("********-****-****-****-************")],['$$arrayField._id'] ] },
                    {$eq: [ [LUUID("********-****-****-****-************")],['$$arrayField._id'] ] }
                  ] }
            }
        }
    }
}])

How will it look in MongoTemplate? And it is possible to rewrite the cond?

Body:
cond rewritten as:

 db.getCollection('collectionName').aggregate([
    {
        $project: {
            '_id':1,
            'arrayField': {
                $filter: {
                    input: '$arrayField',
                    as: 'arrayField',
                    cond:
                        { "$setIsSubset": [
                            { "$map": {
                                "input": ["$$arrayField._id"],
                                "as": "el",
                                "in": "$$el"
                            }},
                            [ LUUID("********-****-****-****-************") ,LUUID("********-****-****-****-************")],
                        ]}
                }
            }
        }
    }])


问:
Mysql column with null values - what are the space requirements?
I have a table with quite a lot entries.
I need an additional column with an integer value or null.
The thing is that only very few rows will have that field populated.

So i wonder whether its better to create a seperate table where i link the entries in an 1:1 relation.

I know one integer entry takes 4 bytes in mysql/myisam. If I have the column set to allow null values, and only 100 of 100 000 rows have the field populated, will the rest still consume 4 bytes for every null value?

Or is mysql intelligent enough to set the value where it is populated and just regard everything as null, where nothing is set?

答:
As far as my understanding goes, once you declare a field as int, 4 bytes will be set aside for it. So, for 100,000 rows you are looking at ~ 400 KB of space.

If space is a constraint, then separate table will be better. On the other hand, if performance is a criteria, then you'll have to take into account how many times that field is queried and whether it is checked for existence or non-existence. In either case, you'll need a join. If you want to check whether the field is set you can use inner join, which will be slower than single table query. If you want to check for non-existence, you'll need left/right outer join which will be slower than inner join.


问:
How to convert viewbag string to int in mvc
In mvc view page i have a view bag name passed from controller.

```<code> <p class="plan-price">@item.Currency@item.Amount
   <span class="plan-unit">
     per month
   </span>
 </p>
</code>```

For example, here Amount is 2900 means how to display 29 ?

答:
You can check null on the requisite string(in your case it is Amount), and then convert it using razor syntax: </p>

```<code>@(string.IsNullOrEmpty(Amount) ? string.Empty : (Convert.ToInt32(Amount) / 100).ToString())
</code>```

Body:
In mvc view page i have a view bag name passed from controller.

@item.Currency@item.Amount

     per month

For example, here Amount is 2900 means how to display 29 ?

Body:
You can check null on the requisite string(in your case it is Amount), and then convert it using razor syntax:

@(string.IsNullOrEmpty(Amount) ? string.Empty : (Convert.ToInt32(Amount) / 100).ToString())


问:
Jquery Not Loading ReactNative WebView In Android
In my project i am using ReactNative WebView.My WebView Page Contain Lots of jquery Functions When i link That Page Only Designs are Displayed in Mobile, Functionalities are Not Working Properly.</p>

答:
Did you linked to the CDN of Jquery maybe?
because you need to have it local and load it by this methode:

```<code><script src="assets/js/jquery-3.2.0.min.js"></script>
</code>```

and did you do this in your mainActivity.java?

```<code>view.getSettings().setJavaScriptEnabled(true);
</code>```

Body:
Did you linked to the CDN of Jquery maybe?
because you need to have it local and load it by this methode:

<script src="assets/js/jquery-3.2.0.min.js"></script>

and did you do this in your mainActivity.java?

view.getSettings().setJavaScriptEnabled(true);


问:
show div after scrolling in mobile devices
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

```<code>$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}
</code>```

can somebody help me to fix this problem.

thank you

答:
You should not use bind but on instead. And use both resize and load in the same function.

bind is an old version of new added on see here > bind vs on

See jsfiddle

or snippet below ( i used 700 for example purposes only. so it works in snippet )

$(window).on("load resize", checkPosition)
var phonebox = $(".phonebox");

function checkPosition() {
  if ($(window).width() < 700) {
    $(window).scroll(function() {
      if ($(window).scrollTop() > 100) {
        $(phonebox).show();
      } else {
        $(phonebox).hide();
      }
    });
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.phonebox {
 top:200px;
 height:300px;
 width:100px;
 position:absolute;
 background:red;
 display:none;
}
.for_scroll {
 height:1000px
}</code>```

```

Body:
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}

can somebody help me to fix this problem.

thank you

Body:
You should not use bind but on instead. And use both resize and load in the same function.

bind is an old version of new added on see here > bind vs on

See jsfiddle

or snippet below ( i used 700 for example purposes only. so it works in snippet )

$(window).on("load resize", checkPosition)
var phonebox = $(".phonebox");

function checkPosition() {
  if ($(window).width() < 700) {
    $(window).scroll(function() {
      if ($(window).scrollTop() > 100) {
        $(phonebox).show();
      } else {
        $(phonebox).hide();
      }
    });
  }
}

.phonebox {
 top:200px;
 height:300px;
 width:100px;
 position:absolute;
 background:red;
 display:none;
}
.for_scroll {
 height:1000px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="phonebox">

</div>
<div class="for_scroll">

</div>


问:
Combining content types into a single PDF in Drupal 6
So, I'm working on a Drupal 6 project that ultimately replaces a big, complex Excel spreadsheet with a workflow as such:

Customer books an appointment via the Bookings API

Employee goes to customer and does a bunch of measurements

Employee enters measurements into either an uploaded Excel spreadsheet or a web-based form

Website generates a PDF with measurement sheet and the output from the Invoice module

Customer receives an email with link to watermarked version of PDF.

Customer pays online and receives link to unwatermarked PDF.

My questions are:

What is the best way to go about Part 3 (Such that the data can be used by Parts 4-6)? CCK fields and a custom content type?

What is the best way to combine content types (I.e., "Measurements" custom content type with "Invoice" content type) into a single PDF?

Bonus Marks: Any way to auto-populate Invoice module content types?

Any help will be muchly appreciated!

答:
You are actyally trying to sell a product with customisable input (comparable to a t-shirt with a custom print, but instead of using a custom picture, you use custom data).

Here is what I did for a comparable project:

Use ubercart: http://www.ubercart.org/

Use the UC Node Checkout extension, this allows you to link a node to an ubercart product and use the information in the node for your customised product: http://drupal.org/project/uc_node_checkout

Here's an excellent walkthrough for UC Node Checkout: http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart

You can use FileField for uploading the Excel file: http://drupal.org/project/filefield

Make sure you use the Transliteration module: http://drupal.org/project/transliteration

The PECL upload progress is also nice to have

You will also need a csv reader, but haven't tried this yet

Finally, to give a link to the file, you can use the Ubercart selling files mechanism: http://www.ubercart.org/docs/user/3345/selling_files

Bonus:

You can use the Automatic node tite module to autoname a node: http://drupal.org/project/auto_nodetitle

For other fields, you can use the token mechanism: http://drupal.org/project/token


问:
Return Ajax data on Index() in MVC 5
I have Index() which return empty view() like below

```<code>public ActionResult Index()
    {
        return View();
    }
</code>```

And GetDashboardSummaryData() which accept int parameter.

```<code>[HttpPost]
public ContentResult GetDashboardSummaryData(int year)
{
  ContentResult json = new ContentResult();
  json.Content = JsonConvert.SerializeObject(dashboardSummaryListViewModels);
  json.ContentType = "application/json";
  json.ContentEncoding = Encoding.UTF8;
  return json;

}
</code>```

On my cshtml page

```<code> $(document).ready(function () {
    year = new Date().getFullYear();
    GetDashboardSummaryData(year);
 });

function GetDashboardSummaryData(year) {
    var url = "@Url.Content("~/Dashboard/GetDashboardSummaryData")";
    url = url + "?year=" + year;
    $.ajax
      ({
          type: "POST",
          url: url,
          success: function (data) {
            //Populating chart data using data
        });

}
</code>```

Above all functionality is working as expected but when I debug my code first it goes to the Index() which basically return empty view and on document.ready event it again does AJAX call to fetch data from server side.

Is it possible that retrieve data for the current year on page load event(i.e. in Index()) itself instead of another separate ajax call to get initial data.

答:
I manage to solve this issue.

```<code>public ActionResult Index()
{
  return View(GetDashboardSummaryData(DateTime.Today.Year));
}
</code>```

Here is my GetDashboardSummaryData()

```<code>[HttpPost]
public JsonResult GetDashboardSummaryData(int year)
{
  return Json(dashboardSummaryListViewModels, JsonRequestBehavior.AllowGet);
}
</code>```

cshtml page

```<code> $(document).ready(function () {
    year = new Date().getFullYear();
    var data = @Html.Raw(Json.Encode(Model.Data));
    PopulateChart(data);
 });
</code>```

Title: Return Ajax data on Index() in MVC 5

Body:
I have Index() which return empty view() like below

public ActionResult Index()
    {
        return View();
    }

And GetDashboardSummaryData() which accept int parameter.

[HttpPost]
public ContentResult GetDashboardSummaryData(int year)
{
  ContentResult json = new ContentResult();
  json.Content = JsonConvert.SerializeObject(dashboardSummaryListViewModels);
  json.ContentType = "application/json";
  json.ContentEncoding = Encoding.UTF8;
  return json;

}

On my cshtml page

 $(document).ready(function () {
    year = new Date().getFullYear();
    GetDashboardSummaryData(year);
 });

function GetDashboardSummaryData(year) {
    var url = "@Url.Content("~/Dashboard/GetDashboardSummaryData")";
    url = url + "?year=" + year;
    $.ajax
      ({
          type: "POST",
          url: url,
          success: function (data) {
            //Populating chart data using data
        });

}

Above all functionality is working as expected but when I debug my code first it goes to the Index() which basically return empty view and on document.ready event it again does AJAX call to fetch data from server side.

Is it possible that retrieve data for the current year on page load event(i.e. in Index()) itself instead of another separate ajax call to get initial data.

Body:
I manage to solve this issue.

public ActionResult Index()
{
  return View(GetDashboardSummaryData(DateTime.Today.Year));
}

Here is my GetDashboardSummaryData()

[HttpPost]
public JsonResult GetDashboardSummaryData(int year)
{
  return Json(dashboardSummaryListViewModels, JsonRequestBehavior.AllowGet);
}

cshtml page

 $(document).ready(function () {
    year = new Date().getFullYear();
    var data = @Html.Raw(Json.Encode(Model.Data));
    PopulateChart(data);
 });


问:
Prefix for testing methods in Unit: "test" vs "should"
It is a common practice to prefix the tests method names in JUnit with "test". But in the last few years, some people changed this to the prefix "should".

If I want to test the customer creation in a database, I would normally name the method "testCustomerCreation". However, some people would name "shouldCreateCustomer".

This is a lot of personal taste when I am the only person in the project or when everyone else in the project agrees with me. But when/where this is not the case, some divergences or inconsistent mixes starts to shows up.

I readed somewhere an article of a guy that named his methods like "testShouldCreateCustomer", and for this reason he decided to drop the "test" prefix. But in fact he wasn't prefixing with "test", he was using "testShould" and changed to "should". Obviously, this did not convinced me.

I am personally strongly inclined to stick to "test" prefix because the methods names normally starts with verbs in the infinitive form ("get", "set", "add", "remove", "clear", "send", "receive", "open", "close", "read", "write", "create", "list", "pop", "print", etc, so is "test"). So, prefixing a method name with "should" makes it sound really very strange for me, looks wrong.

So, what is the real good reason to use "should" instead of "test"? What are the great advantages and disadvantages?

答:
I would say the 'test' prefix is simply a holdover from the pre annotation days when that was required.  I would suggest you simply use meaningful names for your test cases (and that may mean with or without 'test').

I prefer to name the test method so that it is clear what is being tested.  i.e.

```<code>checkNullParameter()
runSimpleQuery()
runQueryWithBadParam()
</code>```

All the test cases are located in a test directory anyway and all actual tests are annotated, so the 'test' prefix is rather redundant.

Body:
I would say the 'test' prefix is simply a holdover from the pre annotation days when that was required.  I would suggest you simply use meaningful names for your test cases (and that may mean with or without 'test').

I prefer to name the test method so that it is clear what is being tested.  i.e.

checkNullParameter()
runSimpleQuery()
runQueryWithBadParam()

All the test cases are located in a test directory anyway and all actual tests are annotated, so the 'test' prefix is rather redundant.


问:
Dynamically add or remove dimensions with D3js parallel sets
I'm trying to change the dimensions of my parallel sets chart dynamically, as previously asked in this question.

I'm using the reusable chart created by Jason Davies:
http://www.jasondavies.com/parallel-sets/

I create my chart using this code:

```<code>var chart = d3.parsets()
      .dimensions(["Survived", "Sex", "Age", "Class"]);

var vis = d3.select("#vis").append("svg")
    .attr("width", chart.width())
    .attr("height", chart.height());

d3.csv("titanic.csv", function(error, csv) {
  vis.datum(csv).call(chart);
});
</code>```

I have created a button that when clicked should call a function change that should change the dimensions to ["Survived", "Sex", "Class"].

The function:

```<code>function change() {
    vis.call(chart.dimensions(["Survived", "Sex", "Class"]));
}
</code>```

When the function is called I get the error Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined on line 90 which is within the updateDimensions function in the reusable chart.

Anyone has a solution for this or should I solve it by using the workaround by creating a new svg object with the new dimensions and remove the old one as user1386906 mentions in a comment in the previously asked question?

答:
Is there a way to make the parallel set take different values which are in json for a data entity
I have did with some random number generator

```<code> svg.datum(data)
      .call(chart
        .value(function(d, i) {
            var v1, v2, v3;
            v1 = d["Valu"];
            v2 = d["Val"];enter code here
            v3 = d["Value"];
            console.log(v1);
            console.log(v2);
            console.log(v3);
            var x = Math.floor((Math.random() * 10) + 1);
            if (x < 5) {
                return v2;
            } else {
                return v3;
            }

        })
        .mapLevel(levelMap)
        .dimensions(arrayOfDimensions)
        //dimensions to be displayed by chart. (i.e "Cost Item", "Location" etc)
    );
</code>```

There is three different values named, Value, val, valu , I want nodes to take different values for parallel nodes , So that each set of parallel node has different size of nodes
example :

```<code>nodeP        node Parallel to nodeP
]             ]
]
</code>```

has different size so ribbon connecting them has varying size from source node to destination node.

Body:
I'm trying to change the dimensions of my parallel sets chart dynamically, as previously asked in this question.

I'm using the reusable chart created by Jason Davies:
http://www.jasondavies.com/parallel-sets/

I create my chart using this code:

var chart = d3.parsets()
      .dimensions(["Survived", "Sex", "Age", "Class"]);

var vis = d3.select("#vis").append("svg")
    .attr("width", chart.width())
    .attr("height", chart.height());

d3.csv("titanic.csv", function(error, csv) {
  vis.datum(csv).call(chart);
});

I have created a button that when clicked should call a function change that should change the dimensions to ["Survived", "Sex", "Class"].

The function:

function change() {
    vis.call(chart.dimensions(["Survived", "Sex", "Class"]));
}

When the function is called I get the error Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined on line 90 which is within the updateDimensions function in the reusable chart.

Anyone has a solution for this or should I solve it by using the workaround by creating a new svg object with the new dimensions and remove the old one as user1386906 mentions in a comment in the previously asked question?

Body:
Is there a way to make the parallel set take different values which are in json for a data entity
I have did with some random number generator

 svg.datum(data)
      .call(chart
        .value(function(d, i) {
            var v1, v2, v3;
            v1 = d["Valu"];
            v2 = d["Val"];enter code here
            v3 = d["Value"];
            console.log(v1);
            console.log(v2);
            console.log(v3);
            var x = Math.floor((Math.random() * 10) + 1);
            if (x < 5) {
                return v2;
            } else {
                return v3;
            }

        })
        .mapLevel(levelMap)
        .dimensions(arrayOfDimensions)
        //dimensions to be displayed by chart. (i.e "Cost Item", "Location" etc)
    );

There is three different values named, Value, val, valu , I want nodes to take different values for parallel nodes , So that each set of parallel node has different size of nodes
example :

nodeP        node Parallel to nodeP
]             ]
]

has different size so ribbon connecting them has varying size from source node to destination node.


问:
Scrollable canvasjs chart
I'm trying to make scrollable vertical canvasjs chart.

This is html:

```<code><div style="height:300px; width: 100%; overflow-y:scroll">
    <div id="dataContainer" style="width: 100%;"></div>
</div>
</code>```

This is javascript:

```<code>var chart = new CanvasJS.Chart("dataContainer",
{
    title:{
        text: data['name']
    },
    axisY:{
       gridThickness: 0,
     },
    data: [{
        animationEnabled: false,
        indexLabelPlacement: "inside",
        indexLabelFontColor: "white",
        indexLabelFontWeight: 600,
        indexLabelFontFamily: "Verdana",
        type: "bar",
        dataPoints: dataPoints[0]
    },
    {
        animationEnabled: false,
        indexLabelPlacement: "inside",
        indexLabelFontColor: "white",
        indexLabelFontWeight: 600,
        indexLabelFontFamily: "Verdana",
        type: "bar",
        dataPoints: dataPoints[1]
    }
    ]
});

chart.render();
</code>```

This is the result:

I have added dataPointWidth:

```<code>var chart = new CanvasJS.Chart("dataContainer",
{
    dataPointWidth: 20,
    title:{
        text: data['name']
    },
 ...
};
</code>```

This is the result (looks like a bug):

How to make chart with scroller and columns of normal size?

答: google charts library works fine. </p>

Title: Scrollable canvasjs chart

Body:
I'm trying to make scrollable vertical canvasjs chart.

This is html:

This is javascript:

var chart = new CanvasJS.Chart("dataContainer",
{
    title:{
        text: data['name']
    },
    axisY:{
       gridThickness: 0,
     },
    data: [{
        animationEnabled: false,
        indexLabelPlacement: "inside",
        indexLabelFontColor: "white",
        indexLabelFontWeight: 600,
        indexLabelFontFamily: "Verdana",
        type: "bar",
        dataPoints: dataPoints[0]
    },
    {
        animationEnabled: false,
        indexLabelPlacement: "inside",
        indexLabelFontColor: "white",
        indexLabelFontWeight: 600,
        indexLabelFontFamily: "Verdana",
        type: "bar",
        dataPoints: dataPoints[1]
    }
    ]
});

chart.render();

This is the result:

I have added dataPointWidth:

var chart = new CanvasJS.Chart("dataContainer",
{
    dataPointWidth: 20,
    title:{
        text: data['name']
    },
 ...
};

This is the result (looks like a bug):

How to make chart with scroller and columns of normal size?

Body: google charts library works fine.


问:
access powershell dataset data
Hi Guys thanks for help really appreciate it.
Iam new to powershell, using powershell iam accessing data of sql server
my query is getting executed, but output of query is 10 that data is getting filled in dataset
i want that data to be concatenated in path like 10, 20 in $version

```<code>$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt
</code>```

Please find code below

```<code>param([string]$servername)

$filePath = "c:\temp\result.txt"

try
{

$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$version = $DataSet.Tables[0].rows[0].data

#$version=System.Data.DataSet.Tables[1].Rows[0][0]
Write-Host $version
$DataSet.Tables[0] | out-file "C:\temp\version.csv"
$defaultdata = $DataSet.Tables[0].rows[0].data
Write-Host $defaultdata

$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt
$select1=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' |Out-File D:\temp\pattern.txt
write-host($select.Line.Length)

if( $select.Line.Length -gt 0 )
{
   Write-Host 'Contains String'
   $select2=Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

   if($select.Line.Length -gt 0)
   {
    #out-File c:\temp\result.txt $filePath -Append
    New-Item $filePath -ItemType file
    'Success'| Out-File -FilePath $filePath -Append
   }
   else
   {
    New-Item $filePath -ItemType file
    'Failed'| Out-File -FilePath $filePath -Append
   }

}
else
{
   Write-Host 'Does not contain String'
}

}
catch

{
Write-Host -BackgroundColor Red -ForegroundColor White "Fail"

        $errText =  $Error[0].ToString()

            if ($errText.Contains("network-related"))

        {Write-Host "Connection Error. Check server name, port, firewall."}

        Write-Host $errText

        continue

}
</code>```

i want $version=10 as query has output 10, somehow iam not able to get it,
though iam getting same data in csv file but i want same data in $version variable.

答:
There is a provlem when you call data there is no data column in the data set you can do two thing
1:
$version = $DataSet.Tables[0].rows[0].data

Replace

$version = $DataSet.Tables[0].rows[0].Column1

or
2:
You can change the SQLquery and name the column you select like this:
$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0)) as data"

Title: access powershell dataset data

Body:
Hi Guys thanks for help really appreciate it.
Iam new to powershell, using powershell iam accessing data of sql server
my query is getting executed, but output of query is 10 that data is getting filled in dataset
i want that data to be concatenated in path like 10, 20 in $version

$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt

Please find code below

param([string]$servername)

$filePath = "c:\temp\result.txt"

try
{

$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$version = $DataSet.Tables[0].rows[0].data

#$version=System.Data.DataSet.Tables[1].Rows[0][0]
Write-Host $version
$DataSet.Tables[0] | out-file "C:\temp\version.csv"
$defaultdata = $DataSet.Tables[0].rows[0].data
Write-Host $defaultdata

$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt
$select1=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' |Out-File D:\temp\pattern.txt
write-host($select.Line.Length)

if( $select.Line.Length -gt 0 )
{
   Write-Host 'Contains String'
   $select2=Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

   if($select.Line.Length -gt 0)
   {
    #out-File c:\temp\result.txt $filePath -Append
    New-Item $filePath -ItemType file
    'Success'| Out-File -FilePath $filePath -Append
   }
   else
   {
    New-Item $filePath -ItemType file
    'Failed'| Out-File -FilePath $filePath -Append
   }

}
else
{
   Write-Host 'Does not contain String'
}

}
catch

{
Write-Host -BackgroundColor Red -ForegroundColor White "Fail"

        $errText =  $Error[0].ToString()

            if ($errText.Contains("network-related"))

        {Write-Host "Connection Error. Check server name, port, firewall."}

        Write-Host $errText

        continue

}

i want $version=10 as query has output 10, somehow iam not able to get it,
though iam getting same data in csv file but i want same data in $version variable.


问:
Nginx location which rewrites and serves a file from different root
Stuck with an nginx config block.
I want to remove the /holding_page_error part of the request and then attempt to serve a file back from the remaining path requested (which will match a file directly).

I also want this to be the last rule applied to this request as I have other location blocks which will pick this up and cause further errors.

```<code>location /holding_page_error {
    root /usr/share/nginx/maintenance;
    rewrite ^/holding_page_error/(.*)$ /$1 last;
}
</code>```

答:
The rewrite...last will commence the search for another location block to match the rewritten URI. Perhaps you meant to use a rewrite...break. See this document for more.

```<code>location /holding_page_error {
    root /usr/share/nginx/maintenance;
    rewrite ^/holding_page_error/(.*)$ /$1 break;
}
</code>```

Which is similar to this:

```<code>location /holding_page_error {
    alias /usr/share/nginx/maintenance;
}
</code>```

See this document for more.

Body:
Stuck with an nginx config block.
I want to remove the /holding_page_error part of the request and then attempt to serve a file back from the remaining path requested (which will match a file directly).

I also want this to be the last rule applied to this request as I have other location blocks which will pick this up and cause further errors.

location /holding_page_error {
    root /usr/share/nginx/maintenance;
    rewrite ^/holding_page_error/(.*)$ /$1 last;
}

Body:
The rewrite...last will commence the search for another location block to match the rewritten URI. Perhaps you meant to use a rewrite...break. See this document for more.

location /holding_page_error {
    root /usr/share/nginx/maintenance;
    rewrite ^/holding_page_error/(.*)$ /$1 break;
}

Which is similar to this:

location /holding_page_error {
    alias /usr/share/nginx/maintenance;
}

See this document for more.


问:
JSON ValueError: Expecting property name: line 1 column 2 (char 1)
I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is

```<code>ValueError: Expecting property name: line 1 column 2 (char 1)
</code>```

Here is my code:

```<code>from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
from kafka.producer import SimpleProducer, KeyedProducer
import pymongo
from pymongo import MongoClient
import json

c = MongoClient("54.210.157.57")
db = c.test_database3
collection = db.tweet_col

kafka = KafkaClient("54.210.157.57:9092")

consumer = SimpleConsumer(kafka,"myconsumer","test")
for tweet in consumer:
    print tweet.message.value
    jsonTweet=json.loads(({u'favorited': False, u'contributors': None})
    collection.insert(jsonTweet)
</code>```

I'm pretty sure that the error is occuring at the 2nd to last line

```<code>jsonTweet=json.loads({u'favorited': False, u'contributors': None})
</code>```

but I do not know what to do to fix it. Any advice would be appreciated.

答:
All other answers may answer your query, but I faced same issue which was due to stray , which I added at the end of my json string like this:

```<code>{
 "key":"123sdf",
 "bus_number":"asd234sdf",
}
</code>```

I finally got it working when I removed extra , like this:

```<code>{
 "key":"123sdf",
 "bus_number":"asd234sdf"
}
</code>```

Hope this help! cheers.

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is

ValueError: Expecting property name: line 1 column 2 (char 1)

Here is my code:

from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
from kafka.producer import SimpleProducer, KeyedProducer
import pymongo
from pymongo import MongoClient
import json

c = MongoClient("54.210.157.57")
db = c.test_database3
collection = db.tweet_col

kafka = KafkaClient("54.210.157.57:9092")

consumer = SimpleConsumer(kafka,"myconsumer","test")
for tweet in consumer:
    print tweet.message.value
    jsonTweet=json.loads(({u'favorited': False, u'contributors': None})
    collection.insert(jsonTweet)

I'm pretty sure that the error is occuring at the 2nd to last line

jsonTweet=json.loads({u'favorited': False, u'contributors': None})

but I do not know what to do to fix it. Any advice would be appreciated.

Body:
All other answers may answer your query, but I faced same issue which was due to stray , which I added at the end of my json string like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf",
}

I finally got it working when I removed extra , like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf"
}

Hope this help! cheers.


问:
Why do HTML5 Web Workers have a high startup latency?
According to an article by a Mozilla engineer Web Workers take about ~40ms to startup (latency).

How fast are Web Workers?
https://hacks.mozilla.org/2015/07/how-fast-are-web-workers/

Web workers take about 40 ms to be instantiated. Also, this time is
  pretty stable with variations of only a few milliseconds.

In a JSFiddle test I notice a varying startup latency between 15ms to 70ms. The latency does not appear to be stable around ~40ms. Chrome appears to be faster (6ms to 25ms).

```<code>var workerCode = URL.createObjectURL(blob); // no download latency
var worker = new Worker(workerCode);
</code>```

https://jsfiddle.net/pvr5xroh/1/

Why do Web Workers have such a high startup latency?

答:
When you load a webworker like :

```<code>worker = new Worker('path/to/js');
</code>```

The browser need to download 'path/to/js' before. Remember that JS is downloaded from the backend and executed in the frontend.

Body:
According to an article by a Mozilla engineer Web Workers take about ~40ms to startup (latency).

How fast are Web Workers?
https://hacks.mozilla.org/2015/07/how-fast-are-web-workers/

Web workers take about 40 ms to be instantiated. Also, this time is
  pretty stable with variations of only a few milliseconds.

In a JSFiddle test I notice a varying startup latency between 15ms to 70ms. The latency does not appear to be stable around ~40ms. Chrome appears to be faster (6ms to 25ms).

var workerCode = URL.createObjectURL(blob); // no download latency
var worker = new Worker(workerCode);

https://jsfiddle.net/pvr5xroh/1/

Why do Web Workers have such a high startup latency?

Body:
When you load a webworker like :

worker = new Worker('path/to/js');

The browser need to download 'path/to/js' before. Remember that JS is downloaded from the backend and executed in the frontend.


问:
splitting vector every two indices
Given vector of N elements:

```<code>LETTERS[1:10]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
</code>```

How can one get a data.table/frame  (df) as follows?

```<code> >df
 one two
 A   B
 C   D
 E   F
 G   H
 I   J
</code>```

EDIT

Generalizing I would like to know given a vector to split as follows:

```<code>   [A B C],[D E],[F G H I J]
</code>```

and obtaining:

```<code>     V1 V2 V3 V4 V5
      A  B  C NA NA
      D  E NA NA NA
      F  G  H  I  J
</code>```

答:
One option is the matrix way

```<code>as.data.frame(matrix(LETTERS[1:10], ncol=2,byrow=TRUE,
      dimnames = list(NULL, c('one', 'two'))), stringsAsFactors=FALSE)
#  one two
#1   A   B
#2   C   D
#3   E   F
#4   G   H
#5   I   J
</code>```

f we need to create an index, we can use gl to split the vector and rbind

```<code>do.call(rbind, split(v1, as.integer(gl(length(v1), 2, length(v1)))))
</code>```

where

```<code>v1 <- LETTERS[1:10]
</code>```

Update

Based on the update in OP's post

```<code>lst <- split(v1, rep(1:3, c(3, 2, 5)))
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
#   [,1] [,2] [,3] [,4] [,5]
#1 "A"  "B"  "C"  NA   NA
#2 "D"  "E"  NA   NA   NA
#3 "F"  "G"  "H"  "I"  "J"
</code>```

Or otherwise

```<code>library(stringi)
stri_list2matrix(lst, byrow = TRUE)
</code>```

Update2

If we are using a 'splitVec'

```<code>lst <- split(v1, cumsum(seq_along(v1) %in% splitVec))
</code>```

and then proceed as above

Title: splitting vector every two indices

Body:
Given vector of N elements:

LETTERS[1:10]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

How can one get a data.table/frame  (df) as follows?

 >df
 one two
 A   B
 C   D
 E   F
 G   H
 I   J

EDIT

Generalizing I would like to know given a vector to split as follows:

   [A B C],[D E],[F G H I J]

and obtaining:

     V1 V2 V3 V4 V5
      A  B  C NA NA
      D  E NA NA NA
      F  G  H  I  J

Body:
One option is the matrix way

as.data.frame(matrix(LETTERS[1:10], ncol=2,byrow=TRUE,
      dimnames = list(NULL, c('one', 'two'))), stringsAsFactors=FALSE)
#  one two
#1   A   B
#2   C   D
#3   E   F
#4   G   H
#5   I   J

f we need to create an index, we can use gl to split the vector and rbind

do.call(rbind, split(v1, as.integer(gl(length(v1), 2, length(v1)))))

where

v1 <- LETTERS[1:10]

Update

Based on the update in OP's post

lst <- split(v1, rep(1:3, c(3, 2, 5)))
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
#   [,1] [,2] [,3] [,4] [,5]
#1 "A"  "B"  "C"  NA   NA
#2 "D"  "E"  NA   NA   NA
#3 "F"  "G"  "H"  "I"  "J"

Or otherwise

library(stringi)
stri_list2matrix(lst, byrow = TRUE)

Update2

If we are using a 'splitVec'

lst <- split(v1, cumsum(seq_along(v1) %in% splitVec))

and then proceed as above


问:
How Do I get A Script To Open Itself?
I have created a VBScript file, and I want it to open itself again. I currently have

```<code>CreateObject("WScript.Shell").Run("W:\\Downloads\\FileName.vbs")
</code>```

But I want it to open itself without a specific path, because I don't know where the file will be. Is that possible?

答:
Try this one

```<code>CreateObject ("WScript.Shell").Run(".\filename.vbs")
</code>```

It will open the file which is in the same folder in which the VBS file is , no need to specify the rest of the path.
You can add a MsgBox "text" so that the program does not terminates or else only one program will run oneat a time.

Title: How Do I get A Script To Open Itself?

Body:
I have created a VBScript file, and I want it to open itself again. I currently have

CreateObject("WScript.Shell").Run("W:\\Downloads\\FileName.vbs")

But I want it to open itself without a specific path, because I don't know where the file will be. Is that possible?

Body:
Try this one

CreateObject ("WScript.Shell").Run(".\filename.vbs")

It will open the file which is in the same folder in which the VBS file is , no need to specify the rest of the path.
You can add a MsgBox "text" so that the program does not terminates or else only one program will run oneat a time.


问:
Issue while trying to append route parameter in js
Below is my js code that is appending the route and its parameter in anchor tag.

```<code>var href = "{!! route('ShowUserMainForm', ['RoleID'=>" + row.RoleID + "]) !!}";

var UserColumn = "<td><a href=' " + href + "'><button>Users</button></a></td>";
</code>```

It gives below url

http://localhost:1234/public/system-users/%20+%20row.RoleID%20+%20

I am expecting below.

http://localhost:1234/public/system-users/1

Am I missing anything?

答:
No. of ways to do it:

Because {!! !!} block codes render before JavaScript code so you need to create route and then concat RoleID outside {!! !!} .

if row.RoleID is json :

```<code>var href = "public/system-users/" + row.RoleID
</code>```

or

```<code>var href = "{!! route('ShowUserMainForm') !!}" + row.RoleID;
</code>```

or

```<code>var href = "{!! route('ShowUserMainForm', ['RoleID'=>'']) !!}" + row.RoleID;
</code>```

Body:
Below is my js code that is appending the route and its parameter in anchor tag.

var href = "{!! route('ShowUserMainForm', ['RoleID'=>" + row.RoleID + "]) !!}";

var UserColumn = "<button>Users</button>	";

It gives below url

http://localhost:1234/public/system-users/%20+%20row.RoleID%20+%20

I am expecting below.

http://localhost:1234/public/system-users/1

Am I missing anything?

Body:
No. of ways to do it:

Because {!! !!} block codes render before JavaScript code so you need to create route and then concat RoleID outside {!! !!} .

if row.RoleID is json :

var href = "public/system-users/" + row.RoleID

or

var href = "{!! route('ShowUserMainForm') !!}" + row.RoleID;

or

var href = "{!! route('ShowUserMainForm', ['RoleID'=>'']) !!}" + row.RoleID;


问:
Select element with specific data by using jQuery
Is it possible to set some data by using the jQuery data method and then later query it? Something like ... find all elements with data foo == true?</p>

答:
You can use .filter() to select the elements you want, like this:

```<code>$("someSelector").filter(function() { return $.data(this, "foo"); });
</code>```

In this case since you're checking a boolean it's very simple, for checking against a value just add the comparison, like this:

```<code>$("someSelector").filter(function() { return $.data(this, "foo") == "value"; });
</code>```

Body:
You can use .filter() to select the elements you want, like this:

$("someSelector").filter(function() { return $.data(this, "foo"); });

In this case since you're checking a boolean it's very simple, for checking against a value just add the comparison, like this:

$("someSelector").filter(function() { return $.data(this, "foo") == "value"; });


问:
My JQuery post data to 'textbox' how to post it to 'div'?
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});
```

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

答: I'm not sure what you are asking about but if you want to send the result to a div, just use $("#divId").html(result)

Body:
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?


答:
You can use this to merge date and time into the same column of dataframe.

```<code>import pandas as pd
data_file = 'data.csv' #path of your file
</code>```

Reading .csv file with merged columns Date_Time:

```<code>data = pd.read_csv(data_file, parse_dates=[['Date', 'Time']])
</code>```

You can use this line to keep both other columns also.

```<code>data.set_index(['Date', 'Time'], drop=False)
</code>```

Title: Combine Date and Time columns using pandas

Body:
I have a pandas dataframe with the following columns:

data = {'Date': ['01-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '04-06-2013'],
        'Time': ['23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00']}
df = pd.DataFrame(data)

         Date      Time
0  01-06-2013  23:00:00
1  02-06-2013  01:00:00
2  02-06-2013  21:00:00
3  02-06-2013  22:00:00
4  02-06-2013  23:00:00
5  03-06-2013  01:00:00
6  03-06-2013  21:00:00
7  03-06-2013  22:00:00
8  03-06-2013  23:00:00
9  04-06-2013  01:00:00

How do I combine data['Date'] & data['Time']  to get the following? Is there a way of doing it using pd.to_datetime?

Date
01-06-2013 23:00:00
02-06-2013 01:00:00
02-06-2013 21:00:00
02-06-2013 22:00:00
02-06-2013 23:00:00
03-06-2013 01:00:00
03-06-2013 21:00:00
03-06-2013 22:00:00
03-06-2013 23:00:00
04-06-2013 01:00:00

Body:
You can use this to merge date and time into the same column of dataframe.

import pandas as pd
data_file = 'data.csv' #path of your file

Reading .csv file with merged columns Date_Time:

data = pd.read_csv(data_file, parse_dates=[['Date', 'Time']])

You can use this line to keep both other columns also.

data.set_index(['Date', 'Time'], drop=False)


问:
How to set DisplayField and ValueFiled of combobox
How to set DisplayField and ValueFiled of combobox with store response like ex: [1,2,3,4,5]

```<code>Ext.create('Ext.form.ComboBox', {
id: 'combo',
width: 400,
fieldLabel: 'distinct value',
emptyText: 'select',
store: '',
displayField: 'name',
valueField: 'id',
renderTo:"viewFilter" ,
triggerAction: 'all',
editable: false,
pageSize:10,
});
</code>```

store code

```<code>    var store = Ext.create('Ext.data.Store', {
    pageSize: 50,
    model: 'Model',
    remoteSort: true,
    proxy: {
        type: 'ajax',
        url: 'dynamicAjax.exc?action=getDistinctValues',
        simpleSortMode: true
    }
});
</code>```

I am going to do lazy loading on combo box ,If you have any alternate solution just drive me.

答:
As far as I know, a store cannot work with a response of [1,2,3,4,5] out of the box.

You will have to convert the response to objects in the model. When you do that, you can set the field name to text, so you don't have to define the displayField.

I have made a working fiddle for you here:

https://fiddle.sencha.com/#view/editor&fiddle/22k4

Body:
How to set DisplayField and ValueFiled of combobox with store response like ex: [1,2,3,4,5]

Ext.create('Ext.form.ComboBox', {
id: 'combo',
width: 400,
fieldLabel: 'distinct value',
emptyText: 'select',
store: '',
displayField: 'name',
valueField: 'id',
renderTo:"viewFilter" ,
triggerAction: 'all',
editable: false,
pageSize:10,
});

store code

    var store = Ext.create('Ext.data.Store', {
    pageSize: 50,
    model: 'Model',
    remoteSort: true,
    proxy: {
        type: 'ajax',
        url: 'dynamicAjax.exc?action=getDistinctValues',
        simpleSortMode: true
    }
});

I am going to do lazy loading on combo box ,If you have any alternate solution just drive me.