问:
Ant classpath and junit.jar
I have the an build.xml that allows me to run junit tests. Here is the relevant part:

```<code><path id="JUnit 4.libraryclasspath">
    <pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
    <pathelement location="../../../../../eclipse/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
</path>
<path id="MyProject.classpath">
    <pathelement location="bin"/>
    <path refid="JUnit 4.libraryclasspath"/>
</path>

<target name="run_unit_tests" depends="build">
        <mkdir dir="${junit.output.dir}"/>
        <junit printsummary="yes" haltonfailure="no">
            <classpath refid="MyProject.classpath" />

            <formatter type="xml"/>
            <batchtest todir="${junit.output.dir}">
                    <fileset dir="${src}">
                            <include name="**/*Test*.java"/>
                    </fileset>
            </batchtest>
        </junit>
</target>
</code>```

If I replace the line:

```<code><pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
</code>```

with

```<code><pathelement location="${eclipse.home}/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
</code>```

The change breaks the classpath. I get the following error:

The <classpath> for <junit> must
  include junit.jar if not in Ant's own
  classpath

As far as I understand, the location attribute should hold the same value in both cases. So what can be the reason?

As a side question, this build file will not work on an environment with different junit version (the path will break). Is it possible to add a "general" path to junit.jar?

答:
You can always symlink your jar to another location if you are on linux.  This way you could symlink it to a path that does not include the version.  For example:

```<code> ln -s plugins/org.junit4_4.5.0.v20090824/junit.jar /wherever/junit.jar
</code>```

You may want to have a libraries folder outside of the eclipse subdirectories.  You could also consider using ivy or maven to manage your dependencies.

I'm not sure why your above example fails, but the error message implies that junit.jar is not found.  Are you sure that eclipse.home is set?  You could echo it with:

```<code> <echo message="${eclipse.home}">
</code>```

Title: Ant classpath and junit.jar

Body:
I have the an build.xml that allows me to run junit tests. Here is the relevant part:

<path id="JUnit 4.libraryclasspath">
    <pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
    <pathelement location="../../../../../eclipse/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
</path>
<path id="MyProject.classpath">
    <pathelement location="bin"/>
    <path refid="JUnit 4.libraryclasspath"/>
</path>

<target name="run_unit_tests" depends="build">
        <mkdir dir="${junit.output.dir}"/>
        <junit printsummary="yes" haltonfailure="no">
            <classpath refid="MyProject.classpath" />

            <formatter type="xml"/>
            <batchtest todir="${junit.output.dir}">
                    <fileset dir="${src}">
                            <include name="**/*Test*.java"/>
                    </fileset>
            </batchtest>
        </junit>
</target>

If I replace the line:

<pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>

with

<pathelement location="${eclipse.home}/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>

The change breaks the classpath. I get the following error:

The <classpath> for <junit> must
  include junit.jar if not in Ant's own
  classpath

As far as I understand, the location attribute should hold the same value in both cases. So what can be the reason?

As a side question, this build file will not work on an environment with different junit version (the path will break). Is it possible to add a "general" path to junit.jar?

Body:
You can always symlink your jar to another location if you are on linux.  This way you could symlink it to a path that does not include the version.  For example:

 ln -s plugins/org.junit4_4.5.0.v20090824/junit.jar /wherever/junit.jar

You may want to have a libraries folder outside of the eclipse subdirectories.  You could also consider using ivy or maven to manage your dependencies.

I'm not sure why your above example fails, but the error message implies that junit.jar is not found.  Are you sure that eclipse.home is set?  You could echo it with:

 <echo message="${eclipse.home}">


来源: stackexchange

问:
Laravel - JS [ajax] Var must be constant
i will be happy if someone know how to do this and why i m getting error , i would like to pass "var size" inside route() method inside forelse is it somehow passible ?

whot it do ?

based on radio box ( if size M and L are avaible there will be 2 radioboxes ), then if user click on add to card it gets Value of radio box for example ( 6 ) = L them pass it to ajax route

Error :

Use of undefined constant size - assumed 'size' (View: C:\xampp\htdocs\EcSc\resources\views\shop\home.blade.php)

JS :

```<code>        <script>
            var CartCount = {{ Session::has("cart") ? Session::get("cart")->totalQty : "0" }} ;
            var size;
            @forelse($products as $productsjs)
            $("#product-{{$productsjs->id}}").click(function () {
                var radios{{$productsjs->id}} = document.getElementsByName('radio-{{$productsjs->id}}');
                for (var i = 0, length = radios{{$productsjs->id}}.length; i < length; i++) {
                    if (radios{{$productsjs->id}}[i].checked) {
                        // do whatever you want with the checked radio
                        size = radios{{$productsjs->id}}[i].value;

                        // only one radio can be logically checked, don't check the rest
                        break;
                    }
                }
                $.ajax({
                    type: "get",
                    url: "{{route("product.addToCartAjax", $productsjs->id, size)}}", // insert product with specific size into session
                    success: function () {
                        CartCount++;
                        $("#shoppingCartCounter").html(CartCount);
                        console.log("Produkt bol pridani");
                        console.log("Velkost produktu je : " + size); // size contain value of checked radio box
                    }
                })
            });
            @empty
            @endforelse
        </script>
</code>```

答:
You can't print the javascript variable in PHP. Think of {{ }} as <?php ?>. If you just insert it in there, it may look like <?php echo size; ?> which won't work, as obviously size will look like a constant here, which of course is undefined (your error).

Instead, you need to declare the variable in php. However, since you're doing this after run time, there's no way that you're going to be able to assign a PHP variable after the page has been rendered. So what are your alternatives?

1 - Construct the route manually: (recommended, easiest)

```<code>url: '/products/' + {{$productsjs->id}} + '/add-to-cart-ajax/' + size
</code>```

2 - Use a client side route generator for Laravel, such as La Route (harder, but more dynamic and reusable)

```<code>laroute.route('product.{id}.addToCartAjax.{size}', {id: '{{$productsjs->id}}', size: size});
</code>```

3 - Other generic solutions such as generating the route ahead of time and dynamically modifying it with javascript (ugly, non-portable)

ContentLicense: CC BY-SA 3.0

Body:
You can't print the javascript variable in PHP. Think of {{ }} as <?php ?>. If you just insert it in there, it may look like <?php echo size; ?> which won't work, as obviously size will look like a constant here, which of course is undefined (your error).

Instead, you need to declare the variable in php. However, since you're doing this after run time, there's no way that you're going to be able to assign a PHP variable after the page has been rendered. So what are your alternatives?

1 - Construct the route manually: (recommended, easiest)

url: '/products/' + {{$productsjs->id}} + '/add-to-cart-ajax/' + size

2 - Use a client side route generator for Laravel, such as La Route (harder, but more dynamic and reusable)

laroute.route('product.{id}.addToCartAjax.{size}', {id: '{{$productsjs->id}}', size: size});

3 - Other generic solutions such as generating the route ahead of time and dynamically modifying it with javascript (ugly, non-portable)


问:
ES6 avoid that/self
I am trying to avoid "const that = this", "const self = this" etc. using es6.
However I am struggling with some constructs in combination of vue js and highcharts where you got something like this:

```<code>data () {
  let that = this
  return {
    highchartsConfiguration: {
      ... big configuration ...
      formatter: function () {
        return this.point.y + that.unit
      }
    }
  }
}
</code>```

I'd like to have the that defined just in formatter object if possible. Using arrow syntax () => {} would me allow to use this from data scope, but i would lose the power of giving the function an extra scope.

I do not want to modify the used libraries.

答:
The example illustrates the problem that persists in older libraries like Highcharts and D3 that emerged before current JS OOP practices and strongly rely on dynamic this context to pass data to callback functions. The problem results from the fact that data is not replicated as callback parameters, like it is usually done in vanilla JS event handlers or jQuery callbacks.

It is expected that one of this contexts (either lexical or dynamic) is chosen, and another one is assigned to a variable.

So

```<code>const that = this;
</code>```

is most common and simple way to overcome the problem.

However, it's not practical if lexical this is conventionally used, or if a callback is class method that is bound to class instance as this context. In this case this can be specified by a developer, and callback signature is changed to accept dynamic this context as first argument.

This is achieved with simple wrapper function that should be applied to old-fashioned callbacks:

```<code>function contextWrapper(fn) {
    const self = this;

    return function (...args) {
        return fn.call(self, this, ...args);
    }
}
</code>```

For lexical this:

```<code>data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper((context) => {
        // `this` is lexical, other class members can be reached
        return context.point.y + this.unit
      })
    }
  }
}
</code>```

Or for class instance as this:

```<code>...

constructor() {
  this.formatterCallback = this.formatterCallback.bind(this);
}

formatterCallback(context) {
    // `this` is class instance, other class members can be reached
    return context.point.y + this.unit
  }
}

data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper(this.formatterCallback)
    }
  }
}
</code>```

Title: ES6 avoid that/self

Body:
I am trying to avoid "const that = this", "const self = this" etc. using es6.
However I am struggling with some constructs in combination of vue js and highcharts where you got something like this:

data () {
  let that = this
  return {
    highchartsConfiguration: {
      ... big configuration ...
      formatter: function () {
        return this.point.y + that.unit
      }
    }
  }
}

I'd like to have the that defined just in formatter object if possible. Using arrow syntax () => {} would me allow to use this from data scope, but i would lose the power of giving the function an extra scope.

I do not want to modify the used libraries.

Body:
The example illustrates the problem that persists in older libraries like Highcharts and D3 that emerged before current JS OOP practices and strongly rely on dynamic this context to pass data to callback functions. The problem results from the fact that data is not replicated as callback parameters, like it is usually done in vanilla JS event handlers or jQuery callbacks.

It is expected that one of this contexts (either lexical or dynamic) is chosen, and another one is assigned to a variable.

So

const that = this;

is most common and simple way to overcome the problem.

However, it's not practical if lexical this is conventionally used, or if a callback is class method that is bound to class instance as this context. In this case this can be specified by a developer, and callback signature is changed to accept dynamic this context as first argument.

This is achieved with simple wrapper function that should be applied to old-fashioned callbacks:

function contextWrapper(fn) {
    const self = this;

    return function (...args) {
        return fn.call(self, this, ...args);
    }
}

For lexical this:

data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper((context) => {
        // `this` is lexical, other class members can be reached
        return context.point.y + this.unit
      })
    }
  }
}

Or for class instance as this:

...

constructor() {
  this.formatterCallback = this.formatterCallback.bind(this);
}

formatterCallback(context) {
    // `this` is class instance, other class members can be reached
    return context.point.y + this.unit
  }
}

data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper(this.formatterCallback)
    }
  }
}


问:
Reverse right half of a linked list

reverse second half linkedlist

  example:

  even number:
  2->1->3->4->5->6->7->8 =====> 2->1->3->4->8->7->6->5 ；

odd number: 5->7->8->6->3->4->2 ======> 5->7->8->2->4->3->6, the
  middle one also need be reversed

```<code>class ListNode
{
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

class ReverseRightHalfLinkedList
{
    public static void main(String[] args)
    {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode res = reverse(node1);//line 31

//      ListNode node = node1;
//      while (node != null)
//      {
//          System.out.println(node.val);
//          node = node.next;
//      }

    }

    public static ListNode reverse(ListNode start)
    {
        int counter = 0;
        ListNode node = start;
        ListNode pre = start;

        while (node!= null)
        {
            counter += 1;
            node = node.next;
        }

        for (int i=0; i<counter/2; i++)
        {
            pre = start;
            start = start.next;
        }

        ListNode cur = start;

        if (counter%2 ==0)
        {
            while (cur != null)
            {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
            }
        }
        else
        {
            pre = pre.next;
            cur = start.next;

            System.out.println(pre.val);
            System.out.println(cur.val);

            while (cur != null)
            {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;

                System.out.println("-----");
                System.out.println(pre.val); // line 90
                System.out.println(cur.val);
                System.out.println("-----");
                System.out.println();
            }
        }

        return start;

    }
}
</code>```

Firstly, I got an error message.

Exception in thread "main" java.lang.NullPointerException     at
  ReverseRightHalfLinkedList.reverse(OA2.java:90)   at
  ReverseRightHalfLinkedList.main(OA2.java:31)

Secondly, I tried to print the order of reversed linked list, it is still in order. It was not reversed.

Please help me to figure out these two problems. Thanks a lot!

答:
Here's a way to reverse second half(right) of linked list.</p>

```<code>#include<stdio.h>
#include<stdlib.h>

struct Node{
int data;
struct Node* next;
};

void append(struct Node** head_ref, int new_data)
{

struct Node* new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=new_data;
new_node->next=NULL;

struct Node* last=*head_ref;

if(*head_ref==NULL){
    *head_ref=new_node;
    return;
}

while(last->next!=NULL)
    last=last->next;

last->next=new_node;
return;
}

int display(struct Node* n)
{
int m=0;
printf("\n");
while(n!=NULL)
{
    printf(" %d ",n->data);
    n=n->next;
    m=m+1;
}
return m;
}

void reverse(struct Node** head_ref, int mid)
{
if(*head_ref==NULL)
{
    printf("\nEmpty List cannot be reversed");
    return;
}

struct Node* last=*head_ref;
struct Node* second_last;
struct Node* beg=*head_ref;
int c=1;
while(c<=mid){
    second_last=last;
    last=last->next;
    c=c+1;
}

struct Node* prev=NULL;
struct Node* current=last;
struct Node* next;

while(current != NULL)
{
    next=current->next;
    current->next=prev;
    prev=current;
    current=next;
}
*head_ref=beg;
second_last->next=prev;

}

int main()
{
int size;
struct Node* head=NULL;
int i,mid;
for(i=0;i<11;i++)
{
    append(&head,rand()%19 +1);
}
size=display(head);
printf("\n Size of linked list: %d",size);

if(size%2==0)
    mid=(size+1)/2;
else
    mid=size/2;

reverse(&head, mid);
display(head);
return 0;

}
</code>```

Title: Reverse right half of a linked list

Body:
reverse second half linkedlist

  example:

  even number:
  2->1->3->4->5->6->7->8 =====> 2->1->3->4->8->7->6->5 ；

odd number: 5->7->8->6->3->4->2 ======> 5->7->8->2->4->3->6, the
  middle one also need be reversed

class ListNode
{
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

class ReverseRightHalfLinkedList
{
    public static void main(String[] args)
    {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode res = reverse(node1);//line 31

//      ListNode node = node1;
//      while (node != null)
//      {
//          System.out.println(node.val);
//          node = node.next;
//      }

    }

    public static ListNode reverse(ListNode start)
    {
        int counter = 0;
        ListNode node = start;
        ListNode pre = start;

        while (node!= null)
        {
            counter += 1;
            node = node.next;
        }

        for (int i=0; i<counter/2; i++)
        {
            pre = start;
            start = start.next;
        }

        ListNode cur = start;

        if (counter%2 ==0)
        {
            while (cur != null)
            {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
            }
        }
        else
        {
            pre = pre.next;
            cur = start.next;

            System.out.println(pre.val);
            System.out.println(cur.val);

            while (cur != null)
            {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;

                System.out.println("-----");
                System.out.println(pre.val); // line 90
                System.out.println(cur.val);
                System.out.println("-----");
                System.out.println();
            }
        }

        return start;

    }
}

Firstly, I got an error message.

Exception in thread "main" java.lang.NullPointerException     at
  ReverseRightHalfLinkedList.reverse(OA2.java:90)   at
  ReverseRightHalfLinkedList.main(OA2.java:31)

Secondly, I tried to print the order of reversed linked list, it is still in order. It was not reversed.

Please help me to figure out these two problems. Thanks a lot!

Body:
Here's a way to reverse second half(right) of linked list.

#include<stdio.h>
#include<stdlib.h>

struct Node{
int data;
struct Node* next;
};

void append(struct Node** head_ref, int new_data)
{

struct Node* new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=new_data;
new_node->next=NULL;

struct Node* last=*head_ref;

if(*head_ref==NULL){
    *head_ref=new_node;
    return;
}

while(last->next!=NULL)
    last=last->next;

last->next=new_node;
return;
}

int display(struct Node* n)
{
int m=0;
printf("\n");
while(n!=NULL)
{
    printf(" %d ",n->data);
    n=n->next;
    m=m+1;
}
return m;
}

void reverse(struct Node** head_ref, int mid)
{
if(*head_ref==NULL)
{
    printf("\nEmpty List cannot be reversed");
    return;
}

struct Node* last=*head_ref;
struct Node* second_last;
struct Node* beg=*head_ref;
int c=1;
while(c<=mid){
    second_last=last;
    last=last->next;
    c=c+1;
}

struct Node* prev=NULL;
struct Node* current=last;
struct Node* next;

while(current != NULL)
{
    next=current->next;
    current->next=prev;
    prev=current;
    current=next;
}
*head_ref=beg;
second_last->next=prev;

}

int main()
{
int size;
struct Node* head=NULL;
int i,mid;
for(i=0;i<11;i++)
{
    append(&head,rand()%19 +1);
}
size=display(head);
printf("\n Size of linked list: %d",size);

if(size%2==0)
    mid=(size+1)/2;
else
    mid=size/2;

reverse(&head, mid);
display(head);
return 0;

}


问:
How do I update a Python package?
I'm running Ubuntu 9:10 and a package called M2Crypto is installed (version is 0.19.1). I need to download, build and install the latest version of the M2Crypto package (0.20.2).

The 0.19.1 package has files in a number of locations including (/usr/share/pyshared and /usr/lib/pymodules.python2.6).

How can I completely uninstall version 0.19.1 from my system before installing 0.20.2?

答:
I think the best one-liner is:</p>

```<code>pip install --upgrade <package>==<version>
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I update a Python package?

Body:
I think the best one-liner is:

pip install --upgrade <package>==<version>


问:
Is there a public roadmap for Redhat JBoss Fuse 7?
Is there a public roadmap for Redhat JBoss Fuse 7? I mean other than the ones accessible with a Red Hat Login at https://access.redhat.com/solutions/3253531.

I ask here at SO since the old forum is readonly now, i.e. see https://developer.jboss.org/thread/273716.

答: The roadmap was presented at last year's Red Hat summit (see PDF slides at https://rh2017.smarteventscloud.com/connect/sessionDetail.ww?SESSION_ID=105088). This should give you a general idea about what will be included. Keep in mind that the specifics change from sprint to sprint so if you are interested about a particular feature or bug fix, please get in touch.</p>


问:
What is the purpose of ungetc (or ungetch from K&R)?
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

```<code> int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}
</code>```

(I've removed the ternary operator in getch to make it clearer.)

答:
Try running the program without spaces around operators. I don't recall precisely the format of that example and I don't have K&R handy, but instead of using "2 3 +" try "2 3+". The ungetch() is probably used when parsing numbers, as the number parser will read digits until it gets something that is a non-digit. If the non-digit is a space, then the next getch() will read the + and all is well. However, if the next non-digit is a +, then it will need to push that back onto the input stream so the main read loop can find it again.

Hope I'm remembering the example correctly.

OwnerDisplayName: Tyler

Body:
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

 int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}

(I've removed the ternary operator in getch to make it clearer.)

OwnerDisplayName: Greg Hewgill


问:
how do i make a button generate a random number and each time the button is clicked a new number is generated and added to the previous number
I need help making a button generate a random number in java script, i would like when the button is pressed for it to generate a random number between 1-10 and and then once the button is pressed again for it to generate a new random number but the sum of both number to show each time the button is presses. For example button is presses and the computer generates 3 button is presses and computer generates 2 but shows the sum of 2+3 so 5

```<code><!DOCTYPE html>

<html>

<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Merienda+One' rel='stylesheet' type='text/css'>

<title>
    Blackjack
</title>

<body>

    <head>
        <h1>
            <i>BLACKJACK</i>
        </h1>
        <h4>
            Computers Cards:
            <input type="text" id="computerscards">
            <br>Player 1 cards:
            <input type="text" id="playerscards">
        </h4>
    </head>

    <input type="button" value="start" onclick="document.getElementById('playerscards').value =
    random();document.getElementById('computerscards').value = 18">

    <input type="button" value="deal" onclick="document.getElementById('playerscards).value = dealcard">

    <input type="button" value="stand" onclick="">

    <input type="button" value="next" onclick="">

    <p>Press hit if you would like to draw another card
        <br> press stand if you do not wish to draw another card
        <br> press next if you want to start the next round</p>

</body>

<script src="java.js"></script>

</html>
</code>```

JAVASCRIPT

```<code>var total =
var randomnumber = Math.floor(Math.random() * 10 + 1);

function random() {
    return randomnumber;
}

function dealcard() { }
</code>```

答:
When you set var total = multiple times, you are overwriting that variable. Instead, you should be setting it as a static value of 0 to start with, and updating it inside of the function that you call on button click. You can add to the existing value with total +=, which is a shorthand way of saying total = total + ....

Here's a really stripped-down example showcasing this:

var total = 0;

function dealcard() {
  total += Math.floor(Math.random() * 10 + 1);
  document.getElementById('playerscards').value = total;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Player 1 cards: <input type="text" id="playerscards">
<br />
<button onclick="dealcard()">Deal</button></code>```

Hope this helps! :)

Body:
I need help making a button generate a random number in java script, i would like when the button is pressed for it to generate a random number between 1-10 and and then once the button is pressed again for it to generate a new random number but the sum of both number to show each time the button is presses. For example button is presses and the computer generates 3 button is presses and computer generates 2 but shows the sum of 2+3 so 5

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Merienda+One' rel='stylesheet' type='text/css'>

<title>
    Blackjack
</title>

            BLACKJACK

            Computers Cards:
            <input type="text" id="computerscards">

Player 1 cards:
            <input type="text" id="playerscards">

    <input type="button" value="start" onclick="document.getElementById('playerscards').value =
    random();document.getElementById('computerscards').value = 18">

    <input type="button" value="deal" onclick="document.getElementById('playerscards).value = dealcard">

    <input type="button" value="stand" onclick="">

    <input type="button" value="next" onclick="">

Press hit if you would like to draw another card

 press stand if you do not wish to draw another card

 press next if you want to start the next round

JAVASCRIPT

var total =
var randomnumber = Math.floor(Math.random() * 10 + 1);

function random() {
    return randomnumber;
}

function dealcard() { }

Body:
When you set var total = multiple times, you are overwriting that variable. Instead, you should be setting it as a static value of 0 to start with, and updating it inside of the function that you call on button click. You can add to the existing value with total +=, which is a shorthand way of saying total = total + ....

Here's a really stripped-down example showcasing this:

var total = 0;

function dealcard() {
  total += Math.floor(Math.random() * 10 + 1);
  document.getElementById('playerscards').value = total;
}

Player 1 cards: <input type="text" id="playerscards">
<br />
<button onclick="dealcard()">Deal</button>

Hope this helps! :)


问:
How to dynamically set button tooltip, text and icon simultaneously?
I have a button on a module pool screen. I need to change the icon, tooltip and text dynamically based on logic/a condition. I can successfully change the icon and text but am unable to change all three things (icon, text and tooltip) together.

Sample PBO code:

```<code>Data but(30) type c." here but is the name of button in screen.
write 'icon xxx' as ICON to but.
Concatenate but 'click here' into but separated by space.
</code>```

It does not set the value of the tooltip, which should show "Please Click here to proceed". How can I do this?

答:
Use ICON_CREATE FM instead.

Here is the sample how to change all three attributes on-the-fly:

```<code>PARAMETERS: p_icon  TYPE icon_d MATCHCODE OBJECT h_icon,
            p_text  TYPE string,
            p_toolt TYPE string.

SELECTION-SCREEN BEGIN OF SCREEN 500.
SELECTION-SCREEN PUSHBUTTON 49(30) but USER-COMMAND ret.
SELECTION-SCREEN END OF SCREEN 500.

AT SELECTION-SCREEN.
  CASE sy-ucomm.
    WHEN 'ONLI'.
       CALL FUNCTION 'ICON_CREATE'
        EXPORTING
          name       = p_icon
          text       = p_text
          info       = p_toolt
          add_stdinf = 'X'
        IMPORTING
          result     = but.
      CALL SELECTION-SCREEN 500.
    WHEN 'RET'.
      LEAVE TO SCREEN 0.
    WHEN OTHERS.
  ENDCASE.
</code>```

Body:
I have a button on a module pool screen. I need to change the icon, tooltip and text dynamically based on logic/a condition. I can successfully change the icon and text but am unable to change all three things (icon, text and tooltip) together.

Sample PBO code:

Data but(30) type c." here but is the name of button in screen.
write 'icon xxx' as ICON to but.
Concatenate but 'click here' into but separated by space.

It does not set the value of the tooltip, which should show "Please Click here to proceed". How can I do this?

Body:
Use ICON_CREATE FM instead.

Here is the sample how to change all three attributes on-the-fly:

PARAMETERS: p_icon  TYPE icon_d MATCHCODE OBJECT h_icon,
            p_text  TYPE string,
            p_toolt TYPE string.

SELECTION-SCREEN BEGIN OF SCREEN 500.
SELECTION-SCREEN PUSHBUTTON 49(30) but USER-COMMAND ret.
SELECTION-SCREEN END OF SCREEN 500.

AT SELECTION-SCREEN.
  CASE sy-ucomm.
    WHEN 'ONLI'.
       CALL FUNCTION 'ICON_CREATE'
        EXPORTING
          name       = p_icon
          text       = p_text
          info       = p_toolt
          add_stdinf = 'X'
        IMPORTING
          result     = but.
      CALL SELECTION-SCREEN 500.
    WHEN 'RET'.
      LEAVE TO SCREEN 0.
    WHEN OTHERS.
  ENDCASE.


问:
Parse a binary file with Regular Expressions?
I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable

```<code>ciphertext = re.match(b'\S', ciphertext)
</code>```

It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong?

edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult

答:
Why are you using regex to do this?. You should take a look at the struct module:

```<code>In [1]: import struct

In [2]: magic = b'\xcf\xfa\xed\xfe'

In [3]: decoded = struct.unpack('<I', magic)[0]

In [4]: hex(decoded)
Out[4]: '0xfeedfacf'
</code>```

Also, you can use this recipe for decoding binary files

Body:
I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable

ciphertext = re.match(b'\S', ciphertext)

It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong?

edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult

Body:
Why are you using regex to do this?. You should take a look at the struct module:

In [1]: import struct

In [2]: magic = b'\xcf\xfa\xed\xfe'

In [3]: decoded = struct.unpack('<I', magic)[0]

In [4]: hex(decoded)
Out[4]: '0xfeedfacf'

Also, you can use this recipe for decoding binary files


问:
Selenium- "Waiting for xxxx"- Chrome
Website I am testing needs to load libraries from xxxx server.

Sometimes it takes to long and website display information Waiting for xxxx (I am using Chrome WebDriver).

Is it possible to treat it as an error and catch it using Selenium?

答:
Sometimes when it takes to long and you see website display information Waiting for xxxx it is not actually an error. It means the the JavaScripts and the AJAX Calls associated with the Website are getting executed while the Page Loads. Once the JS & AJAX Calls gets executed completely, the Page Loading completes.

Now as per your question Is it possible to treat it as an error and catch it? the Answer is Yes.

This can be achieved by using the pageLoadTimeout method which Sets the amount of time to wait for a page load to complete before throwing an error.

Defined as pageLoadTimeout(long time, java.util.concurrent.TimeUnit unit), an example will be as follows :

```<code>driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
</code>```

The error thrown is as follows :

```<code>Exception in thread "main" org.openqa.selenium.TimeoutException: Timeout loading page after 2000ms
</code>```

You can find a detailed  implementation of pageLoadTimeout in pageLoadTimeout in Selenium not working discussion.

Title: Selenium- "Waiting for xxxx"- Chrome

Body:
Sometimes when it takes to long and you see website display information Waiting for xxxx it is not actually an error. It means the the JavaScripts and the AJAX Calls associated with the Website are getting executed while the Page Loads. Once the JS & AJAX Calls gets executed completely, the Page Loading completes.

Now as per your question Is it possible to treat it as an error and catch it? the Answer is Yes.

This can be achieved by using the pageLoadTimeout method which Sets the amount of time to wait for a page load to complete before throwing an error.

Defined as pageLoadTimeout(long time, java.util.concurrent.TimeUnit unit), an example will be as follows :

driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);

The error thrown is as follows :

Exception in thread "main" org.openqa.selenium.TimeoutException: Timeout loading page after 2000ms

You can find a detailed  implementation of pageLoadTimeout in pageLoadTimeout in Selenium not working discussion.


问:
Ajv keywords and custom error messages
I have written a schema but it does not seem to be validating as I was expecting. I'm assuming there is something wrong with my schema syntax but cannot figure it out. I expect not to see error messages for title or target until fundraiser is complete since they are only required if fundraiser is completed. I've tried many combinations but none of them are working as expected, these two are the closest I've come to what I need.

Schema attempt one: shows 4 error messages, 3 required errors and 1 error saying data should match "then" schema.

```<code>const schema = {
  required: ['fundraiser'],
  if: {
    properties: {
      fundraiser: { type: 'string' },
    },
  },
  then: {
    required: ['title', 'target'],
  },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};
</code>```

Schema attempt two: shows 2 error messages, 1 required error and 1 error saying data should match "then" schema which is correct but then when I complete fundraiser valid becomes true which is when I expect to then see required errors for title and target. Also no errors have my defined custom error messages.

```<code>const scema = {
  if: {
    properties: { fundraiser: { minLength: 2 } },
    then: { required: ['title', 'target'] },
  },
  then: { required: ['fundraiser'] },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};
</code>```

I am pretty sure that I am doing something wrong with my schema but it is not clear from the documentation how to use if/then in combination with custom error messages using ajv-errors. Any help would be greatly appreciated! Thanks!

答:
The problem with the first schema is that subschema inside “if” is valid, unless fundraiser property is present and not a string. It would probably work as you expect if you add type: 'object' to the root schema and move required inside “if” subschema.

The problem with the second subschema is that the first “then” that has no  “if” in the same schema object is ignored (unless you are using ajv-keywords that implemented if/then/else somewhat differently from how it is defined in draft-07 of JSON Schema spec) and the subschema inside “if is valid even if fundraiser property is absent and the second “then” can only pass if fundraiser is present.

Title: Ajv keywords and custom error messages

Body:
I have written a schema but it does not seem to be validating as I was expecting. I'm assuming there is something wrong with my schema syntax but cannot figure it out. I expect not to see error messages for title or target until fundraiser is complete since they are only required if fundraiser is completed. I've tried many combinations but none of them are working as expected, these two are the closest I've come to what I need.

Schema attempt one: shows 4 error messages, 3 required errors and 1 error saying data should match "then" schema.

const schema = {
  required: ['fundraiser'],
  if: {
    properties: {
      fundraiser: { type: 'string' },
    },
  },
  then: {
    required: ['title', 'target'],
  },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};

Schema attempt two: shows 2 error messages, 1 required error and 1 error saying data should match "then" schema which is correct but then when I complete fundraiser valid becomes true which is when I expect to then see required errors for title and target. Also no errors have my defined custom error messages.

const scema = {
  if: {
    properties: { fundraiser: { minLength: 2 } },
    then: { required: ['title', 'target'] },
  },
  then: { required: ['fundraiser'] },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};

I am pretty sure that I am doing something wrong with my schema but it is not clear from the documentation how to use if/then in combination with custom error messages using ajv-errors. Any help would be greatly appreciated! Thanks!


问:
How to separate out @types within project?
I had a TypeScript project that uses React and Webpack:

```<code>npm install react react-dom @types/react @types/react-dom --save
npm install webpack ts-loader --save-dev
</code>```

I have a typical webpack.config.js to build the project. Everything works well.

Then I converted webpack.config.js from .js to .ts following this article:

```<code>npm install ts-node @types/node @types/webpack --save-dev
</code>```

Indeed, webpack.config.ts works great.

However, the typedefs between node/webpack and react are seen as in the same space (ie both local and web). For example in my webpack.config.ts I should be referencing @types/node and not @types/react, and in my src/components/app.tsx file I should be referencing @types/react and not @types/node, but in both places the compiler and IDE thinks I use both (at runtime it will blow up). How can I separate these type definitions, so that the right ones are visible to the right files?

Conceptually, I think I just want @types from devDependencies to only be visible to dev scripts, like webpack.config.ts, and files in src can only see @types from dependencies. Is that kind of setup possible?

答:
You should be able to do this with two separate tsconfig.json files, something like:

```<code> /webpack.config.ts
 /tsconfig.json
 /src/components/app.tsx
 /src/tsconfig.json
</code>```

Your /tsconfig.json is then specific for a Node environment (for building):

```<code>{
    "compilerOptions": {
        "lib": ["es2015"], // no DOM
        "types": ["node"]
    }
}
</code>```

And /src/tsconfig.json is then for a browser environment:

```<code>{
    "compilerOptions": {
        "lib": ["es2015", "dom"],
        "types": ["react"]
    }
}
</code>```

Body:
I had a TypeScript project that uses React and Webpack:

npm install react react-dom @types/react @types/react-dom --save
npm install webpack ts-loader --save-dev

I have a typical webpack.config.js to build the project. Everything works well.

Then I converted webpack.config.js from .js to .ts following this article:

npm install ts-node @types/node @types/webpack --save-dev

Indeed, webpack.config.ts works great.

However, the typedefs between node/webpack and react are seen as in the same space (ie both local and web). For example in my webpack.config.ts I should be referencing @types/node and not @types/react, and in my src/components/app.tsx file I should be referencing @types/react and not @types/node, but in both places the compiler and IDE thinks I use both (at runtime it will blow up). How can I separate these type definitions, so that the right ones are visible to the right files?

Conceptually, I think I just want @types from devDependencies to only be visible to dev scripts, like webpack.config.ts, and files in src can only see @types from dependencies. Is that kind of setup possible?

Body:
You should be able to do this with two separate tsconfig.json files, something like:

 /webpack.config.ts
 /tsconfig.json
 /src/components/app.tsx
 /src/tsconfig.json

Your /tsconfig.json is then specific for a Node environment (for building):

{
    "compilerOptions": {
        "lib": ["es2015"], // no DOM
        "types": ["node"]
    }
}

And /src/tsconfig.json is then for a browser environment:

{
    "compilerOptions": {
        "lib": ["es2015", "dom"],
        "types": ["react"]
    }
}


问:
Using assembler inside C from converted c file
im new to using asm into C code ,so sorry if my question is too dumb.
The thing is I wrote a program in C  which codes a text file based on a code rule file.But im trying to make some methods in asm.So I made the compiler(Visual compiler) to make a asm file of my code.The thing is when I see the asm code for one method there are things like this. And if I try to paste it over my method add, inside the __asm{} ,i get errors even though is the same asm output.
How can I put this asm code inside my function?
Thanks...

```<code>_movement$ = -20                                        ; size = 4
_leftBits$ = -16                                        ; size = 4
_hexa$ = -12                                            ; size = 4
_actualByte$ = -8                                 ; size = 4
_character$ = -2                                        ; size = 1
_temp$ = -1                                   ; size = 1
_data$ = 8                                          ; size = 4
_code$ = 12                                   ; size = 1
_longg$ = 16                                            ; size = 4
_positionBit$ = 20                                  ; size = 4
add PROC
        push     ebp
        mov      ebp, esp
        sub      esp, 20              ; 00000014H
        mov      eax, DWORD PTR _positionBit$[ebp]
        cdq
        and      edx, 7
        add      eax, edx
        sar      eax, 3
        mov      DWORD PTR _actualByte$[ebp], eax
        mov      eax, DWORD PTR _positionBit$[ebp]
        and      eax, -2147483641 ; 80000007H
        jns      SHORT $LN4@add
        dec      eax
        or       eax, -8                    ; fffffff8H
        inc      eax
$LN4@add:
        mov      DWORD PTR _leftBits$[ebp], eax
        mov      ecx, DWORD PTR _data$[ebp]
        add      ecx, DWORD PTR _actualByte$[ebp]
        mov      dl, BYTE PTR [ecx]
        mov      BYTE PTR _character$[ebp], dl
        mov      DWORD PTR _hexa$[ebp], 255 ; 000000ffH
        mov      eax, 8
        sub      eax, DWORD PTR _longg$[ebp]
        mov      DWORD PTR _movement$[ebp], eax
        mov      edx, DWORD PTR _hexa$[ebp]
        mov      ecx, DWORD PTR _movement$[ebp]
        sar      edx, cl
        mov      DWORD PTR _hexa$[ebp], edx
        movzx    eax, BYTE PTR _code$[ebp]
        and      eax, DWORD PTR _hexa$[ebp]
        mov      BYTE PTR _code$[ebp], al
        mov      cl, BYTE PTR _code$[ebp]
        mov      BYTE PTR _temp$[ebp], cl
        mov      edx, 8
        sub      edx, DWORD PTR _longg$[ebp]
        add      edx, 1
        cmp      DWORD PTR _leftBits$[ebp], edx
        jge      SHORT $LN1@add
        mov      ecx, 8
        sub      ecx, DWORD PTR _leftBits$[ebp]
        mov      eax, 255   ; 000000ffH
        shl      eax, cl
        mov      ecx, DWORD PTR _data$[ebp]
        add      ecx, DWORD PTR _actualByte$[ebp]
        movzx    edx, BYTE PTR [ecx]
        and      edx, eax
        mov      eax, DWORD PTR _data$[ebp]
        add      eax, DWORD PTR _actualByte$[ebp]
        mov      BYTE PTR [eax], dl
        movzx    edx, BYTE PTR _temp$[ebp]
        mov      ecx, 8
        sub      ecx, DWORD PTR _longg$[ebp]
        sub      ecx, DWORD PTR _leftBits$[ebp]
        shl      edx, cl
        mov      eax, DWORD PTR _data$[ebp]
        add      eax, DWORD PTR _actualByte$[ebp]
        movzx    ecx, BYTE PTR [eax]
        or       ecx, edx
        mov      edx, DWORD PTR _data$[ebp]
        add      edx, DWORD PTR _actualByte$[ebp]
        mov      BYTE PTR [edx], cl
$LN1@add:
        mov      esp, ebp
        pop      ebp
        ret      0
add ENDP
</code>```

this is the error log when trying to compile.

```<code>simple.c(185): error C2059: syntax error: '__asm'
simple.c(201): error C2059: syntax error: 'bad suffix on number'
simple.c(209): error C2059: syntax error: 'bad suffix on number'
simple.c(210): error C2018: unknown character '0x40'
simple.c(214): error C2018: unknown character '0x40'
simple.c(220): error C2059: syntax error: 'bad suffix on number'
simple.c(237): error C2018: unknown character '0x40'
simple.c(240): error C2059: syntax error: 'bad suffix on number'
simple.c(261): error C2018: unknown character '0x40'
</code>```

答:
I know very little about Assembly (what I do know about it comes from C/Linux) so I'll try to suggest something that helps.

Does your function need any parameters passed to it? Does it need to return something to its caller? You could write a short C source file, that only defines a little function like this.

```<code>void butts(void) {
    printf("butts\n");
}
</code>```

And then convert that single file to assembly the way you did. Name it what you want, but remember it. This should give you an assembler source file with the function name butts. Then, you could put the code you posted in your question, into that assembly file. Make sure it can be called with the name you set. I don't think the __asm{} will work the way you want it to.

Then, I believe, you could compile that assembly file as an object, and link it with the C-sourced compiled objects, so you could compile the whole thing together. Make sure you define whatever this function is in a C (or header) file, without writing the body of the function. Use the prototype like this:

```<code>void butts(void);
</code>```

Sorry if this is hogwash or doesn't help at all. Just brainstorming and something like this might work for you.

Body:
im new to using asm into C code ,so sorry if my question is too dumb.
The thing is I wrote a program in C  which codes a text file based on a code rule file.But im trying to make some methods in asm.So I made the compiler(Visual compiler) to make a asm file of my code.The thing is when I see the asm code for one method there are things like this. And if I try to paste it over my method add, inside the __asm{} ,i get errors even though is the same asm output.
How can I put this asm code inside my function?
Thanks...

_movement$ = -20                                        ; size = 4
_leftBits$ = -16                                        ; size = 4
_hexa$ = -12                                            ; size = 4
_actualByte$ = -8                                 ; size = 4
_character$ = -2                                        ; size = 1
_temp$ = -1                                   ; size = 1
_data$ = 8                                          ; size = 4
_code$ = 12                                   ; size = 1
_longg$ = 16                                            ; size = 4
_positionBit$ = 20                                  ; size = 4
add PROC
        push     ebp
        mov      ebp, esp
        sub      esp, 20              ; 00000014H
        mov      eax, DWORD PTR _positionBit$[ebp]
        cdq
        and      edx, 7
        add      eax, edx
        sar      eax, 3
        mov      DWORD PTR _actualByte$[ebp], eax
        mov      eax, DWORD PTR _positionBit$[ebp]
        and      eax, -2147483641 ; 80000007H
        jns      SHORT $LN4@add
        dec      eax
        or       eax, -8                    ; fffffff8H
        inc      eax
$LN4@add:
        mov      DWORD PTR _leftBits$[ebp], eax
        mov      ecx, DWORD PTR _data$[ebp]
        add      ecx, DWORD PTR _actualByte$[ebp]
        mov      dl, BYTE PTR [ecx]
        mov      BYTE PTR _character$[ebp], dl
        mov      DWORD PTR _hexa$[ebp], 255 ; 000000ffH
        mov      eax, 8
        sub      eax, DWORD PTR _longg$[ebp]
        mov      DWORD PTR _movement$[ebp], eax
        mov      edx, DWORD PTR _hexa$[ebp]
        mov      ecx, DWORD PTR _movement$[ebp]
        sar      edx, cl
        mov      DWORD PTR _hexa$[ebp], edx
        movzx    eax, BYTE PTR _code$[ebp]
        and      eax, DWORD PTR _hexa$[ebp]
        mov      BYTE PTR _code$[ebp], al
        mov      cl, BYTE PTR _code$[ebp]
        mov      BYTE PTR _temp$[ebp], cl
        mov      edx, 8
        sub      edx, DWORD PTR _longg$[ebp]
        add      edx, 1
        cmp      DWORD PTR _leftBits$[ebp], edx
        jge      SHORT $LN1@add
        mov      ecx, 8
        sub      ecx, DWORD PTR _leftBits$[ebp]
        mov      eax, 255   ; 000000ffH
        shl      eax, cl
        mov      ecx, DWORD PTR _data$[ebp]
        add      ecx, DWORD PTR _actualByte$[ebp]
        movzx    edx, BYTE PTR [ecx]
        and      edx, eax
        mov      eax, DWORD PTR _data$[ebp]
        add      eax, DWORD PTR _actualByte$[ebp]
        mov      BYTE PTR [eax], dl
        movzx    edx, BYTE PTR _temp$[ebp]
        mov      ecx, 8
        sub      ecx, DWORD PTR _longg$[ebp]
        sub      ecx, DWORD PTR _leftBits$[ebp]
        shl      edx, cl
        mov      eax, DWORD PTR _data$[ebp]
        add      eax, DWORD PTR _actualByte$[ebp]
        movzx    ecx, BYTE PTR [eax]
        or       ecx, edx
        mov      edx, DWORD PTR _data$[ebp]
        add      edx, DWORD PTR _actualByte$[ebp]
        mov      BYTE PTR [edx], cl
$LN1@add:
        mov      esp, ebp
        pop      ebp
        ret      0
add ENDP

this is the error log when trying to compile.

simple.c(185): error C2059: syntax error: '__asm'
simple.c(201): error C2059: syntax error: 'bad suffix on number'
simple.c(209): error C2059: syntax error: 'bad suffix on number'
simple.c(210): error C2018: unknown character '0x40'
simple.c(214): error C2018: unknown character '0x40'
simple.c(220): error C2059: syntax error: 'bad suffix on number'
simple.c(237): error C2018: unknown character '0x40'
simple.c(240): error C2059: syntax error: 'bad suffix on number'
simple.c(261): error C2018: unknown character '0x40'

Body:
I know very little about Assembly (what I do know about it comes from C/Linux) so I'll try to suggest something that helps.

Does your function need any parameters passed to it? Does it need to return something to its caller? You could write a short C source file, that only defines a little function like this.

void butts(void) {
    printf("butts\n");
}

And then convert that single file to assembly the way you did. Name it what you want, but remember it. This should give you an assembler source file with the function name butts. Then, you could put the code you posted in your question, into that assembly file. Make sure it can be called with the name you set. I don't think the __asm{} will work the way you want it to.

Then, I believe, you could compile that assembly file as an object, and link it with the C-sourced compiled objects, so you could compile the whole thing together. Make sure you define whatever this function is in a C (or header) file, without writing the body of the function. Use the prototype like this:

void butts(void);

Sorry if this is hogwash or doesn't help at all. Just brainstorming and something like this might work for you.


问:
Get the latest file from a bunch of similar named files in a directory - powershell
I need to get the latest file from the below list.There are 3 types of files created everyday and I just need 1 from the 3 types.

Example:

```<code>my_file_dob_6545d.txt   12/3/2017 5:00 PM
my_file_csm_6545d.txt   12/3/2017 5:00 PM
my_file_6545d.txt       12/3/2017 5:00 PM  <--- Need to get this.
my_file_dob_6544d.txt   12/2/2017 5:00 PM
my_file_csm_6544d.txt   12/2/2017 5:00 PM
my_file_6544d.txt       12/2/2017 5:00 PM
my_file_dob_6543d.txt   12/1/2017 5:00 PM
my_file_csm_6543d.txt   12/1/2017 5:00 PM
my_file_6543d.txt       12/1/2017 5:00 PM
</code>```

I have the following script from here

```<code>$dir = "c:\my_folder\"
$filter="my_file_*d.txt" <--How can modify this to get only  my_file_XXXXd.txt files? XXXX keeps incrementing everyday
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
</code>```

答:
Nevermind, Figured it out myself from an example here</p>

```<code>$dir = "c:\my_folder\"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Where-object { $_.Name -match "my_file_[0-9][0-9][0-9][0-9]d.txt"} | Select-Object -First 1
</code>```

Body:
I need to get the latest file from the below list.There are 3 types of files created everyday and I just need 1 from the 3 types.

Example:

my_file_dob_6545d.txt   12/3/2017 5:00 PM
my_file_csm_6545d.txt   12/3/2017 5:00 PM
my_file_6545d.txt       12/3/2017 5:00 PM  <--- Need to get this.
my_file_dob_6544d.txt   12/2/2017 5:00 PM
my_file_csm_6544d.txt   12/2/2017 5:00 PM
my_file_6544d.txt       12/2/2017 5:00 PM
my_file_dob_6543d.txt   12/1/2017 5:00 PM
my_file_csm_6543d.txt   12/1/2017 5:00 PM
my_file_6543d.txt       12/1/2017 5:00 PM

I have the following script from here

$dir = "c:\my_folder\"
$filter="my_file_*d.txt" <--How can modify this to get only  my_file_XXXXd.txt files? XXXX keeps incrementing everyday
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name

Body:
Nevermind, Figured it out myself from an example here

$dir = "c:\my_folder\"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Where-object { $_.Name -match "my_file_[0-9][0-9][0-9][0-9]d.txt"} | Select-Object -First 1


问:
Cannot access model property on class definition
I send value to model as attribute

```<code>Views.App = Backbone.View.extend({
    initialize: function () {
        this.items = new Models.Items()
            .on('sync:subitems', function (item) {
                this.subitems = new Models.Subitems({itemId: item.attributes.id});
</code>```

And successfully receive it in initilize of model

```<code>var Subitems = Models.Subitems = Backbone.Collection.extend({
    initialize: function(attributes, options) {
        this.itemId = attributes.itemId;
        console.log(this.itemId);
    },
    model: Subitem,
    url: './subitems?item_id=' + encodeURIComponent(this.itemId)
});
</code>```

console.log returns the value of attribute in initialize.

But request is sent like:

```<code>'./subitems?item_id=undefined'
</code>```

Why do I have undefined if I have access to the property in initialize? How can it be fixed?

答: Change url to a function and you'll be in the context of the backbone collection as appose to the window.</p>

Body:
I send value to model as attribute

Views.App = Backbone.View.extend({
    initialize: function () {
        this.items = new Models.Items()
            .on('sync:subitems', function (item) {
                this.subitems = new Models.Subitems({itemId: item.attributes.id});

And successfully receive it in initilize of model

var Subitems = Models.Subitems = Backbone.Collection.extend({
    initialize: function(attributes, options) {
        this.itemId = attributes.itemId;
        console.log(this.itemId);
    },
    model: Subitem,
    url: './subitems?item_id=' + encodeURIComponent(this.itemId)
});

console.log returns the value of attribute in initialize.

But request is sent like:

'./subitems?item_id=undefined'

Why do I have undefined if I have access to the property in initialize? How can it be fixed?


问:
Cut String by maxLines parameter, and by number of characters
I'm writing a class with a method that takes a summary string and breaks it down into a maximum number of lines (maxLines Parameter) and maximum number of characters per line (width parameter). All lines except the first line should be indented (they should start with a space character), but the second character in an indented line should not be another space (so that second space must not be included). The program should still work if you change the maxLine parameter r width.

Also, the code should check whether some special characters are in the String, like:

```<code> \' , \" , \\ , \t , \b , \r , \f , \n
</code>```

How can I inspect is many spaces in String like below? If there are many spaces in the String, I want to trim them, but I don't know how to. (These underscores represent spaces.)

```<code>"9:00 John_____________________________Doe until 10 30 at Office"

9:00 Jo
_hn____
_______
_____Do
</code>```

With my code, I get this result:

```<code> 9:00 Jo
 _hn Doe
 _until 1
 _0 30 at
</code>```

But I want THIS this output:

```<code>9:00 Jo
_hn Doe
_until_
_10 30_
</code>```

Here is my code:

```<code>public static void main(String[] args) {

    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine) {
    List<String> parts = new LinkedList<>();
    int count = 0;
    int len = str.length();
    String indent = "";
    for (int i = 0; i < len; i += width) {
        parts.add(indent + str.substring(i, Math.min(len, i + width)).trim());
        count++;
        indent = " ";
        if (count == maxLine)
            break;
    }
    return parts;
}
</code>```

答:
So this is what you want? I really hope you don't have to implement this in something because I had to mangle this to make it work.  Hopefully this is homework

```<code>public static void main(String[] args) {
    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine){
    List<String> parts = new LinkedList<>();
    int endedAt = 0;
    boolean firstLine = true;
    boolean secondLine = true;
    String indent = " ";
    for (int i = 0; i < maxLine; i++) {
        if(endedAt<=str.length()) {
            String holder;
            if(firstLine) {
                holder = str.substring(endedAt, endedAt + width);
                firstLine = false;
            }
            else {
                if(secondLine){
                    width = width -1;
                    secondLine = false;
                }
                holder = indent + str.substring(endedAt, endedAt + width).trim();
            }
            parts.add(holder);
            endedAt = endedAt + width;
        }
    }
    return parts;
}
</code>```

The output is

```<code>9:00 Jo
 hn Doe
 until
 10 30
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a class with a method that takes a summary string and breaks it down into a maximum number of lines (maxLines Parameter) and maximum number of characters per line (width parameter). All lines except the first line should be indented (they should start with a space character), but the second character in an indented line should not be another space (so that second space must not be included). The program should still work if you change the maxLine parameter r width.

Also, the code should check whether some special characters are in the String, like:

 \' , \" , \\ , \t , \b , \r , \f , \n

How can I inspect is many spaces in String like below? If there are many spaces in the String, I want to trim them, but I don't know how to. (These underscores represent spaces.)

"9:00 John_____________________________Doe until 10 30 at Office"

9:00 Jo
_hn____
_______
_____Do

With my code, I get this result:

 9:00 Jo
 _hn Doe
 _until 1
 _0 30 at

But I want THIS this output:

9:00 Jo
_hn Doe
_until_
_10 30_

Here is my code:

public static void main(String[] args) {

    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine) {
    List<String> parts = new LinkedList<>();
    int count = 0;
    int len = str.length();
    String indent = "";
    for (int i = 0; i < len; i += width) {
        parts.add(indent + str.substring(i, Math.min(len, i + width)).trim());
        count++;
        indent = " ";
        if (count == maxLine)
            break;
    }
    return parts;
}

Body:
So this is what you want? I really hope you don't have to implement this in something because I had to mangle this to make it work.  Hopefully this is homework

public static void main(String[] args) {
    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine){
    List<String> parts = new LinkedList<>();
    int endedAt = 0;
    boolean firstLine = true;
    boolean secondLine = true;
    String indent = " ";
    for (int i = 0; i < maxLine; i++) {
        if(endedAt<=str.length()) {
            String holder;
            if(firstLine) {
                holder = str.substring(endedAt, endedAt + width);
                firstLine = false;
            }
            else {
                if(secondLine){
                    width = width -1;
                    secondLine = false;
                }
                holder = indent + str.substring(endedAt, endedAt + width).trim();
            }
            parts.add(holder);
            endedAt = endedAt + width;
        }
    }
    return parts;
}

The output is

9:00 Jo
 hn Doe
 until
 10 30


问:
Netbeans Java Desktop Database application with login connecting to users from mysql
I wanted to create a java desktop database application with the combination of the login window so that I will be able to display the user different types of options depending on their level assigned by mysql db. For example, some users may just have add rows privilege to specified tables and read on all others only. Is there any built in login swing window in netbeans?</p>

答: Not in the default JDK, but there are third party libs that have them.  I have used SwingLabs Login Form before and it has worked nicely for me.</p>


问:
What's a good toolchain and deployment process for GIT and Deployment for a Windows user working on a LAMP Stack?
I run a custom PHP site on a Managed VPS (LAMP stack) and am the solo developer, but want to start using GIT so freelancers can contribute. Currently I don't use GIT.

GIT

For GIT, I wanted to use Visual Studio Online (VSO) since I've used it before but am open to suggestions if it's better for the suggested deployment process.

Deployment

I kept a "Dev" folder and a "Live" folder on the web server and simply did all of my dev in the Dev folder, tested there, then ran rsync to push it to the Live folder. I couldn't easily run it locally since it has things like Linux symlinks, and I work on a Windows computer.

The Goal

I want to start adding GIT to this process, integrate that into a decent build process, and still use a Windows IDE for development. Though maybe I should install a Linux VM on my Windows machine so I can start running the site directly from pulling the latest version from GIT?

I need a setup that would be easy for other developers to join on as I find freelancers to help out.

Suggestions?

答:
here's what I do for

Git deployment

For deployment, I follow a very-simple git-flow technique (http://nvie.com/posts/a-successful-git-branching-model/#the-main-branches) with 2 branches:

master for prod

dev for new features

You always develop new features on dev branch, so dev is always ahead of master in term of functionnalities.

When you want to deploy, you SSH on your server, you git pull dev branch, and if everything works fine, you git merge with master.

You can always switch on the prod server between prod and dev version with git branch master and git branch dev. No need of 2 folders, git handles this !

If you have a bug on prod environment, you can switch branch to master on your local computer and fix the bug. Then you upload it via ssh.

Multi collaborator development (developers with windows/linux/mac but 1 production server)

I personally use docker, it creates a single VM which you can customize to match your prod environment (linux version, apache version, php version and my sql version). You create 1 docker image, and then every collaborator can download this image and run it on his computer.


问:
Perform search based on seperate table data in PostgreSQL
I have a table which looks like this:

```<code>deals
id     vendorid     name
1      52           '25% Off'
2      34           '10% Off'
</code>```

-

```<code>vendors
id     name
52     'Walmart'
34     'Home Depot'
</code>```

I'm trying to do a search of the database that also searches based on the vendor id.

I was able to do this to get the vendor data in the query:

```<code>SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
</code>```

Now I want to add a search to it, here is something I tried

```<code>SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
WHERE vendor.name ILIKE '%wal%'
</code>```

In the above example the user would be starting a search for walmart however it says that the vendor.name column does not exist, what would the correct way to do this be?

The output I'm expecting from the above query is:

```<code>[
 {
   id: 1,
   vendorid: 52,
   name: '25% Off',
   vendor: [
      {
        id: 52,
        name: 'Walmart'
      }
   ]
 }
]
</code>```

答:
I was able to get it done by using this.

```<code>SELECT
      *,
      (SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
    FROM
      deals
    where (SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id).name ILIKE '%wal%'
</code>```

It's pretty ugly but get the work done. I am not really familiar with postgree but you can store it in a variable somehow.

Body:
I have a table which looks like this:

deals
id     vendorid     name
1      52           '25% Off'
2      34           '10% Off'

-

vendors
id     name
52     'Walmart'
34     'Home Depot'

I'm trying to do a search of the database that also searches based on the vendor id.

I was able to do this to get the vendor data in the query:

SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals

Now I want to add a search to it, here is something I tried

SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
WHERE vendor.name ILIKE '%wal%'

In the above example the user would be starting a search for walmart however it says that the vendor.name column does not exist, what would the correct way to do this be?

The output I'm expecting from the above query is:

[
 {
   id: 1,
   vendorid: 52,
   name: '25% Off',
   vendor: [
      {
        id: 52,
        name: 'Walmart'
      }
   ]
 }
]

Body:
I was able to get it done by using this.

SELECT
      *,
      (SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
    FROM
      deals
    where (SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id).name ILIKE '%wal%'

It's pretty ugly but get the work done. I am not really familiar with postgree but you can store it in a variable somehow.


问:
Create object of type specified in a string
I have a bunch of classes generated by EF that are simple tables and have similar structures:

```<code>public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}
</code>```

I've also got a method for returning an object of a specified type:

```<code>public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}
</code>```

What I want to do is something like this:

```<code>public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}
</code>```

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

```<code>List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
</code>```

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

答:
Try using the CreateInstance method

```<code>SomeObject someObject = new SomeObject();
Type type = someObject.GetType();

Type listType = typeof(List<>).MakeGenericType(new [] { type });
IList list = (IList)Activator.CreateInstance(listType);
</code>```

Body:
I have a bunch of classes generated by EF that are simple tables and have similar structures:

public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}

I've also got a method for returning an object of a specified type:

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

What I want to do is something like this:

public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

Body:
Try using the CreateInstance method

SomeObject someObject = new SomeObject();
Type type = someObject.GetType();

Type listType = typeof(List<>).MakeGenericType(new [] { type });
IList list = (IList)Activator.CreateInstance(listType);


问:
How to apply custom sort to WooCommerce product loop
My client has a WooCommerce online store which currently displays his products (approx. 600) in reverse chronological order (newest first, oldest last).

The problem is that the older products are not selling because they are always at the bottom of the page and his customers very rarely scroll to the bottom of the (very long 600 products!) page.

Unfortunately, the client is not prepared to split the products into categories or onto separate pages. He is also against a random product sort fired every time the shop page is displayed.

He has however agreed to the following:

always display the NEWEST products at the top of the page (we already mark these using a post_meta '_product_new');

split the REMAINING products into two blocks (the oldest 50% and the newest 50%) and display these blocks alternately according to the current month - even months oldest 50% block first, odd months newest 50% block first.

IMPORTANT is that the post_meta marked products are ALWAYS at the top of the page.

I think it should be possible to apply a custom product sort using the 'pre_get_post' hook:

```<code>add_action( 'pre_get_posts', 'custom_vtp_shop_order' );

function custom_vtp_shop_order($q){
    if ( ! $q->is_main_query() ) return;
    if (! is_admin() && (is_shop() || is_archive) ) {

        ...do the magic here...

    }

    remove_action( 'pre_get_posts', 'custom_vtp_shop_order' );
}
</code>```

but I'm not sure how.

This is what I need to happen:

Block 1: get all products with post_meta '_product_new';

Block 2: get all other products and sort them in reverse chronological order (newest first, oldest last);

Split Block 2 in the middle creating a Block 3 and Block 4;

4a. On even months (February, April, June etc) order my products by Block 1, Block 3, Block 4;

4b. On odd months (January, March, May etc) order my products by Block 1, Block 4, Block 3.

Thanks in advance for any help!

答:
It sounds like you will need three separate queries using WP_Query.

```<code>1st - products, filtered by '_product_new', sorted newest to oldest
2nd - products, sorted newest to oldest, limit to half of posts
3rd - products, sorted oldest to newest, limit to half of posts.
</code>```

You will more than likely have to re-write the archive-product.php. I think this would be the easiest way. The code will be pretty extensive, but I can't think of any other way you would do this properly.

Body:
My client has a WooCommerce online store which currently displays his products (approx. 600) in reverse chronological order (newest first, oldest last).

The problem is that the older products are not selling because they are always at the bottom of the page and his customers very rarely scroll to the bottom of the (very long 600 products!) page.

Unfortunately, the client is not prepared to split the products into categories or onto separate pages. He is also against a random product sort fired every time the shop page is displayed.

He has however agreed to the following:

always display the NEWEST products at the top of the page (we already mark these using a post_meta '_product_new');

split the REMAINING products into two blocks (the oldest 50% and the newest 50%) and display these blocks alternately according to the current month - even months oldest 50% block first, odd months newest 50% block first.

IMPORTANT is that the post_meta marked products are ALWAYS at the top of the page.

I think it should be possible to apply a custom product sort using the 'pre_get_post' hook:

add_action( 'pre_get_posts', 'custom_vtp_shop_order' );

function custom_vtp_shop_order($q){
    if ( ! $q->is_main_query() ) return;
    if (! is_admin() && (is_shop() || is_archive) ) {

        ...do the magic here...

    }

    remove_action( 'pre_get_posts', 'custom_vtp_shop_order' );
}

but I'm not sure how.

This is what I need to happen:

Block 1: get all products with post_meta '_product_new';

Block 2: get all other products and sort them in reverse chronological order (newest first, oldest last);

Split Block 2 in the middle creating a Block 3 and Block 4;

4a. On even months (February, April, June etc) order my products by Block 1, Block 3, Block 4;

4b. On odd months (January, March, May etc) order my products by Block 1, Block 4, Block 3.

Thanks in advance for any help!

Body:
It sounds like you will need three separate queries using WP_Query.

1st - products, filtered by '_product_new', sorted newest to oldest
2nd - products, sorted newest to oldest, limit to half of posts
3rd - products, sorted oldest to newest, limit to half of posts.

You will more than likely have to re-write the archive-product.php. I think this would be the easiest way. The code will be pretty extensive, but I can't think of any other way you would do this properly.


问:
Why is my code so slow?
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

```<code>loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop
</code>```

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

```
   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();
```

update:

```
Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;

```

答: Additional to the Larry Lustig answer, consider using data-aware controls instead, like the  TDbGrid component.

Title: Why is my code so slow?

Body:
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();

update:

Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;


问:
primeng calendar - display in client timezone
Using p-calendar datetime selector, how can you display UTC stored dates in the client's timezone?

I logged the value using onSelect and it shows this:

Mon Dec 04 2017 14:17:00 GMT-0500 (Eastern Standard Time)

And then when I send the value to the DB, it converts to UTC, which is totally fine, however, say I refresh the page and display the value in the p-calendar element, it's displaying Mon Dec 04 2017 19:17:00 (UTC).

I poured through the docs and found no mention of timezone whatsoever. It seems odd that it would consider the timezone while selecting, but not when loading from storage.

In my package.json, I am selecting "primeng": "^4.3.0".

The app I'm creating is to be used globally, so the time should always be shown in the client's timezone.

答:
Figured it out... also realized I left out a bunch of details that were involved.

Using Typescript, the field in question was of type Date. When the fetch was mapped to this field, it instanced a new Date object that by default applied my browser's timezone. Good one to realize. So where the value was Mon Dec 04 2017 14:17:00 (UTC), the Date object created from that was Mon Dec 04 2017 14:17:00 GMT-0500 : no time shift, just took the value as is and applied my timezone.

So to solve my problem, I had to shift the date values over to a new Date instance where I explicitly set the timezone to UTC. p-calendar took care of the rest and converted it to my current timezone for display.


问:
Need a string with a $ in powershell inside ' '
I am trying to write a PS script to find a share named C$$ but PS is interpreting the $ sign and I want to pass it into the filter.
Normally \ stops this but after googling I cant get a working solution.

```<code>$string = "Name='C\$\$'"
Write-Host $string
get-wmiobject -Class Win32_share -filter $string
</code>```

The write host returns Name='C\$\$'
I need it to return C$$

答:
You can use the backtick to escape characters in a string.

```<code>$string = "Name='C`$`$'"
</code>```

That should return Name='C$$'

Body:
I am trying to write a PS script to find a share named C$$ but PS is interpreting the $ sign and I want to pass it into the filter.
Normally \ stops this but after googling I cant get a working solution.

$string = "Name='C\$\$'"
Write-Host $string
get-wmiobject -Class Win32_share -filter $string

The write host returns Name='C\$\$'
I need it to return C$$

Body:
You can use the backtick to escape characters in a string.

$string = "Name='C`$`$'"

That should return Name='C$$'


问:
How to list all RALLY-Projects by Kanban board or Scrum board using API?
I wanted to know the list of projects that uses the Kanban-Board , and the list of projects that uses the Scrum-Board under a workspace in Rally, suggest me a query that can prepare the result.

答: There is currently no way to gather metrics on usage of specific apps/custom pages in your subscription.  This would be a neat feature request though.</p>