问:
interactive stack which can have checkbox and select the options for stack
I am trying to make working model of Stack in which user can select the stack s1 or s2 and can perform operations like push and pop.

  <title>Stack With Constructor </title>

Stack

      stack

    <input type="checkbox" name="stack1" value="s1">s1

    <input type="checkbox" name="stack2" value="s2">s2

    <textarea id="tdisplay"></textarea>

  <textarea id="tpush"></textarea>
  <button onclick="doJob()">push</button>
  <button onclick="doJob1()">pop</button>
  <textarea id="tpop"></textarea>

```

I'm getting problems as follows:

I cannot get the output for pop value. This means when I press button of pop it should give me the remaining items in the array.

I don't know how to use checkbox method. It means when i select s1 checkbox it should create s1 stack and I can do operations on it and same as for s2.

The result should be proper browser functions for interactive stack so it can work like in following steps:

User select s1 or s2 stack

If he/she selects s1 then they can work for all operations for s1.

User can switch between s2 too and can perform all operations.

I am having issues on the pop function and checkbox working.

答:
This would help you get started in the right direction:

Things I noticed:

Incorrect usage of checkbox's boolean value. (use .checked).

Also, checkboxes' names were stack1/2 not id(s).

```<code><body>
<div>Stack</div>
<div>
    <p id="p1">
        stack
    </p>
    <input type="checkbox" id="stack1" value="s1">s1
    <br>
    <input type="checkbox" id="stack2" value="s2">s2
    <br>
    <textarea id="tdisplay"></textarea>
</div>
<textarea id="tpush"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
<textarea id="tpop"></textarea>

<script>
    var s1, s2;

    function myfunction() {
        if (document.getElementById("stack1").checked == true) {
            console.log('myFunction called!');
            s1 = new MyStack();
        }
        if (document.getElementById("stack2").checked == true) {
            s2 = new MyStack();
        }
    }

    function push(v) {
        if (this.st === 0) {
            console.log("Stack Overflow");
        } else {
            this.st = this.st - 1;
            this.stk[this.st] = v;
            document.getElementById("tdisplay").value = this.print();
            ;
        }
    }

    function pop() {
        if (this.st === 10) {
            console.log("Stack Underflow");
        } else {
            document.getElementById("tdisplay").innerHTML = "";
            var temp = this.stk[this.st];
            this.st = this.st + 1;

            return temp;
        }
    }

    function print() {
        console.log("Printing Stack");
        return this.stk.reduce((acc, cv, i, arr, ) = > {
            console.log(cv);
        return (i) ? acc + " " + "\n" + cv : cv;
    },
        ''
    )
        ;
    }

    function MyStack() {
        this.st = 10;
        this.stk = new Array(10);
        this.push = push;
        this.pop = pop;
        this.print = print;
    }

    function doJob() {
        console.log('push pressed!');

        myfunction();
        console.log(s1);
        var x = document.getElementById("tpush").value;
        s1.push(x);

        document.getElementById("tpush").value = "";
    }

    function doJob1() {
        console.log('pop pressed!');
        var y = s1.pop();
        document.getElementById("tpop").value = y;
        document.getElementById("tdisplay").value = s1.print();
    }
</script>
</code>```

Body:
I am trying to make working model of Stack in which user can select the stack s1 or s2 and can perform operations like push and pop.

  <title>Stack With Constructor </title>

Stack

      stack

    <input type="checkbox" name="stack1" value="s1">s1

    <input type="checkbox" name="stack2" value="s2">s2

    <textarea id="tdisplay"></textarea>

  <textarea id="tpush"></textarea>
  <button onclick="doJob()">push</button>
  <button onclick="doJob1()">pop</button>
  <textarea id="tpop"></textarea>

I'm getting problems as follows:

I cannot get the output for pop value. This means when I press button of pop it should give me the remaining items in the array.

I don't know how to use checkbox method. It means when i select s1 checkbox it should create s1 stack and I can do operations on it and same as for s2.

The result should be proper browser functions for interactive stack so it can work like in following steps:

User select s1 or s2 stack

If he/she selects s1 then they can work for all operations for s1.

User can switch between s2 too and can perform all operations.

I am having issues on the pop function and checkbox working.

Body:
This would help you get started in the right direction:

Things I noticed:

Incorrect usage of checkbox's boolean value. (use .checked).

Also, checkboxes' names were stack1/2 not id(s).

<body>
<div>Stack</div>
<div>
    <p id="p1">
        stack
    </p>
    <input type="checkbox" id="stack1" value="s1">s1
    <br>
    <input type="checkbox" id="stack2" value="s2">s2
    <br>
    <textarea id="tdisplay"></textarea>
</div>
<textarea id="tpush"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
<textarea id="tpop"></textarea>

<script>
    var s1, s2;

    function myfunction() {
        if (document.getElementById("stack1").checked == true) {
            console.log('myFunction called!');
            s1 = new MyStack();
        }
        if (document.getElementById("stack2").checked == true) {
            s2 = new MyStack();
        }
    }

    function push(v) {
        if (this.st === 0) {
            console.log("Stack Overflow");
        } else {
            this.st = this.st - 1;
            this.stk[this.st] = v;
            document.getElementById("tdisplay").value = this.print();
            ;
        }
    }

    function pop() {
        if (this.st === 10) {
            console.log("Stack Underflow");
        } else {
            document.getElementById("tdisplay").innerHTML = "";
            var temp = this.stk[this.st];
            this.st = this.st + 1;

            return temp;
        }
    }

    function print() {
        console.log("Printing Stack");
        return this.stk.reduce((acc, cv, i, arr, ) = > {
            console.log(cv);
        return (i) ? acc + " " + "\n" + cv : cv;
    },
        ''
    )
        ;
    }

    function MyStack() {
        this.st = 10;
        this.stk = new Array(10);
        this.push = push;
        this.pop = pop;
        this.print = print;
    }

    function doJob() {
        console.log('push pressed!');

        myfunction();
        console.log(s1);
        var x = document.getElementById("tpush").value;
        s1.push(x);

        document.getElementById("tpush").value = "";
    }

    function doJob1() {
        console.log('pop pressed!');
        var y = s1.pop();
        document.getElementById("tpop").value = y;
        document.getElementById("tdisplay").value = s1.print();
    }
</script>


来源: stackexchange

问:
Why isn't this swap program working in C?
I'm completely new to C and I'm trying to create a basic swap program, can someone please explain why the code below isn't working.

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

void swap (int *p1, int *p2);
    int *temp = *p1;
    *p1 = *p2;
    *p2 = temp;

int main ()
{
    int x = 10;
    int y = 20;
    int *p1 = &x, *p2 = &y;
    swap (p1, p2);

    printf ("x: %d, y: %d\n", x, y);
}
</code>```

Thanks in advance.

答:
The void is a sub-process, it must be enclosed in braces and must not end in a semicolon.
on the other hand as the community says int * temp = * p1; is a constaint violation, it must be int temp = * p1;

Nor was exchanging values, it showed only as when they were entered.

Finally, the main returns an int, you must specify that you return a 0, that is done with return 0;

The whole program would be like that

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

void swap (int *p1, int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main ()
{
    int x = 10;
    int y = 20;
    swap (p1, p2);

    printf ("x: %d, y: %d\n", x, y);
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm completely new to C and I'm trying to create a basic swap program, can someone please explain why the code below isn't working.

#include <stdio.h>

void swap (int *p1, int *p2);
    int *temp = *p1;
    *p1 = *p2;
    *p2 = temp;

int main ()
{
    int x = 10;
    int y = 20;
    int *p1 = &x, *p2 = &y;
    swap (p1, p2);

    printf ("x: %d, y: %d\n", x, y);
}

Thanks in advance.

Body:
The void is a sub-process, it must be enclosed in braces and must not end in a semicolon.
on the other hand as the community says int * temp = * p1; is a constaint violation, it must be int temp = * p1;

Nor was exchanging values, it showed only as when they were entered.

Finally, the main returns an int, you must specify that you return a 0, that is done with return 0;

The whole program would be like that

#include <stdio.h>

void swap (int *p1, int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main ()
{
    int x = 10;
    int y = 20;
    swap (p1, p2);

    printf ("x: %d, y: %d\n", x, y);
    return 0;
}


问:
Python//tkinter label update data
i'm doing an exercise to learn python.
Basically i'm supposed to create 2 circles using tkinter and calculate the distance between them while i'm moving them using buttons.
The 'change' button is to swap circles.
my problem is that the distance shows when i first launch the code, but it doesn't update when i'm moving the circles( and it should)
to show the distance on screen i use a label class.
code below:</p>

```<code>from tkinter import *
from math import sqrt
# procédure générale de déplacement :
def avance(lat1=0, vert1=0,lat2=0,vert2=0):
     global x1, y1,x2,y2,dist
     x1, y1 = x1 +lat1, y1 +vert1
     x2, y2 = x2 +lat2, y2 +vert2
     if flag==0:
        can1.coords(oval1, x1,y1, x1+60,y1+60)
     else:
        can1.coords(oval2, x2, y2, x2 + 30, y2 + 30)

     dist=calculdist(x1,y1,x2,y2)
     return dist

def calculdist(x1,y1,x2,y2):
    dist=sqrt((x2-x1)**2+(y2-y1)**2)
    dist= str(dist)
    return dist

# gestionnaires d'événements :
def depl_gauche():
    if flag==0:
        avance(-10, 0)
    else:
        avance(0,0,-10,0)
def depl_droite():
    if flag==0:
        avance(10, 0)
    else:
        avance(0,0,10,0)
def depl_haut():
    if flag==0:
        avance(0, -10)
    else:
        avance(0,0,0,-10)
def depl_bas():
     if flag==0:
         avance(0, 10)
     else:
         avance(0,0,0,10)

def which():
    global flag
    if flag==0:
        flag=1
    elif flag==1:
        flag=0

#------ Programme principal ------
# les variables suivantes seront utilisées de manière globale :
x1, y1,x2,y2 =100,100,300,300 # coordonnées initiales
flag=0

fen1 = Tk()
fen1.title("Exercice d'animation avec tkinter")

can1 = Canvas(fen1,bg='light grey',height=500,width=500)
oval1 = can1.create_oval(x1,y1,x1+60,y1+60,width=2,fill='red')
oval2 = can1.create_oval(x2,y2,x2+30,y2+30,width=2,fill='blue')

can1.pack(side=LEFT)
Button(fen1,text='Quitter',command=fen1.quit).pack(side=BOTTOM)
Button(fen1,text='Gauche',command=depl_gauche).pack()
Button(fen1,text='Droite',command=depl_droite).pack()
Button(fen1,text='Haut',command=depl_haut).pack()
Button(fen1,text='Bas',command=depl_bas).pack()
Button(fen1,text='Change',command=which).pack()
Label(fen1, text = 'distance :'+calculdist(x1,y1,x2,y2)).pack()

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

答:
Label will not update automatically if you don't use textvariable= with StringVar().

But you can update text manually without textvariable and StringVar

First you have to assign Label to variable to have access to it.

```<code>lab = Label(fen1, text = 'distance :'+calculdist(x1,y1,x2,y2))
lab.pack()
</code>```

And later in avance you can change text using

```<code>lab['text'] = 'distance :'+calculdist(x1,y1,x2,y2)
</code>```

EDIT: full code with better formatting to make it more readable

```<code>import tkinter as tk
from math import sqrt

def avance(lat1=0, vert1=0, lat2=0, vert2=0):
     global x1, y1, x2, y2

     x1 += lat1
     y1 += vert1
     x2 += lat2
     y2 += vert2

     if flag == 0:
        can1.coords(oval1, x1, y1, x1+60, y1+60)
     else:
        can1.coords(oval2, x2, y2, x2+30, y2+30)

     lab['text'] = 'distance: '+calculdist(x1,y1,x2,y2)

def calculdist(x1, y1, x2, y2):
    dist = sqrt((x2-x1)**2+(y2-y1)**2)
    #dist = str(dist)
    dist = "{:10.5f}".format(dist)
    return dist

def depl_gauche():
    if flag == 0:
        avance(-10, 0)
    else:
        avance(0, 0, -10, 0)

def depl_droite():
    if flag == 0:
        avance(10, 0)
    else:
        avance(0, 0, 10, 0)

def depl_haut():
    if flag == 0:
        avance(0, -10)
    else:
        avance(0, 0, 0, -10)

def depl_bas():
     if flag == 0:
         avance(0, 10)
     else:
         avance(0, 0, 0, 10)

def which():
    global flag

    if flag == 0:
        flag = 1
    elif flag == 1:
        flag = 0

#------

x1 = 100
y1 = 100
x2 = 300
y2 = 300
flag = 0

fen1 = tk.Tk()
fen1.title("Exercice d'animation avec tkinter")

can1 = tk.Canvas(fen1, bg='light grey', height=500, width=500)
oval1 = can1.create_oval(x1, y1, x1+60, y1+60, width=2, fill='red')
oval2 = can1.create_oval(x2, y2, x2+30, y2+30, width=2, fill='blue')

can1.pack(side='left')

tk.Button(fen1, text='Quitter', command=fen1.destroy).pack(side='bottom')
tk.Button(fen1, text='Gauche', command=depl_gauche).pack()
tk.Button(fen1, text='Droite', command=depl_droite).pack()
tk.Button(fen1, text='Haut', command=depl_haut).pack()
tk.Button(fen1, text='Bas', command=depl_bas).pack()
tk.Button(fen1, text='Change', command=which).pack()

lab = tk.Label(fen1, text='distance: '+calculdist(x1, y1, x2, y2))
lab.pack()

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

BTW: see PEP 8 -- Style Guide for Python Code

Title: Python//tkinter label update data

Body:
i'm doing an exercise to learn python.
Basically i'm supposed to create 2 circles using tkinter and calculate the distance between them while i'm moving them using buttons.
The 'change' button is to swap circles.
my problem is that the distance shows when i first launch the code, but it doesn't update when i'm moving the circles( and it should)
to show the distance on screen i use a label class.
code below:

from tkinter import *
from math import sqrt
# procédure générale de déplacement :
def avance(lat1=0, vert1=0,lat2=0,vert2=0):
     global x1, y1,x2,y2,dist
     x1, y1 = x1 +lat1, y1 +vert1
     x2, y2 = x2 +lat2, y2 +vert2
     if flag==0:
        can1.coords(oval1, x1,y1, x1+60,y1+60)
     else:
        can1.coords(oval2, x2, y2, x2 + 30, y2 + 30)

     dist=calculdist(x1,y1,x2,y2)
     return dist

def calculdist(x1,y1,x2,y2):
    dist=sqrt((x2-x1)**2+(y2-y1)**2)
    dist= str(dist)
    return dist

# gestionnaires d'événements :
def depl_gauche():
    if flag==0:
        avance(-10, 0)
    else:
        avance(0,0,-10,0)
def depl_droite():
    if flag==0:
        avance(10, 0)
    else:
        avance(0,0,10,0)
def depl_haut():
    if flag==0:
        avance(0, -10)
    else:
        avance(0,0,0,-10)
def depl_bas():
     if flag==0:
         avance(0, 10)
     else:
         avance(0,0,0,10)

def which():
    global flag
    if flag==0:
        flag=1
    elif flag==1:
        flag=0

#------ Programme principal ------
# les variables suivantes seront utilisées de manière globale :
x1, y1,x2,y2 =100,100,300,300 # coordonnées initiales
flag=0

fen1 = Tk()
fen1.title("Exercice d'animation avec tkinter")

can1 = Canvas(fen1,bg='light grey',height=500,width=500)
oval1 = can1.create_oval(x1,y1,x1+60,y1+60,width=2,fill='red')
oval2 = can1.create_oval(x2,y2,x2+30,y2+30,width=2,fill='blue')

can1.pack(side=LEFT)
Button(fen1,text='Quitter',command=fen1.quit).pack(side=BOTTOM)
Button(fen1,text='Gauche',command=depl_gauche).pack()
Button(fen1,text='Droite',command=depl_droite).pack()
Button(fen1,text='Haut',command=depl_haut).pack()
Button(fen1,text='Bas',command=depl_bas).pack()
Button(fen1,text='Change',command=which).pack()
Label(fen1, text = 'distance :'+calculdist(x1,y1,x2,y2)).pack()

fen1.mainloop()

Body:
Label will not update automatically if you don't use textvariable= with StringVar().

But you can update text manually without textvariable and StringVar

First you have to assign Label to variable to have access to it.

lab = Label(fen1, text = 'distance :'+calculdist(x1,y1,x2,y2))
lab.pack()

And later in avance you can change text using

lab['text'] = 'distance :'+calculdist(x1,y1,x2,y2)

EDIT: full code with better formatting to make it more readable

import tkinter as tk
from math import sqrt

def avance(lat1=0, vert1=0, lat2=0, vert2=0):
     global x1, y1, x2, y2

     x1 += lat1
     y1 += vert1
     x2 += lat2
     y2 += vert2

     if flag == 0:
        can1.coords(oval1, x1, y1, x1+60, y1+60)
     else:
        can1.coords(oval2, x2, y2, x2+30, y2+30)

     lab['text'] = 'distance: '+calculdist(x1,y1,x2,y2)

def calculdist(x1, y1, x2, y2):
    dist = sqrt((x2-x1)**2+(y2-y1)**2)
    #dist = str(dist)
    dist = "{:10.5f}".format(dist)
    return dist

def depl_gauche():
    if flag == 0:
        avance(-10, 0)
    else:
        avance(0, 0, -10, 0)

def depl_droite():
    if flag == 0:
        avance(10, 0)
    else:
        avance(0, 0, 10, 0)

def depl_haut():
    if flag == 0:
        avance(0, -10)
    else:
        avance(0, 0, 0, -10)

def depl_bas():
     if flag == 0:
         avance(0, 10)
     else:
         avance(0, 0, 0, 10)

def which():
    global flag

    if flag == 0:
        flag = 1
    elif flag == 1:
        flag = 0

#------

x1 = 100
y1 = 100
x2 = 300
y2 = 300
flag = 0

fen1 = tk.Tk()
fen1.title("Exercice d'animation avec tkinter")

can1 = tk.Canvas(fen1, bg='light grey', height=500, width=500)
oval1 = can1.create_oval(x1, y1, x1+60, y1+60, width=2, fill='red')
oval2 = can1.create_oval(x2, y2, x2+30, y2+30, width=2, fill='blue')

can1.pack(side='left')

tk.Button(fen1, text='Quitter', command=fen1.destroy).pack(side='bottom')
tk.Button(fen1, text='Gauche', command=depl_gauche).pack()
tk.Button(fen1, text='Droite', command=depl_droite).pack()
tk.Button(fen1, text='Haut', command=depl_haut).pack()
tk.Button(fen1, text='Bas', command=depl_bas).pack()
tk.Button(fen1, text='Change', command=which).pack()

lab = tk.Label(fen1, text='distance: '+calculdist(x1, y1, x2, y2))
lab.pack()

fen1.mainloop()

BTW: see PEP 8 -- Style Guide for Python Code


问:
Framework7 router does not work after converting project to apk
I have tried out this tutorial to develop an android application via Cordova and Framework7. It works in the browser and also Android Emulator (ADK). I converted the project to the apk with Cordova build command and transferred the apk file to my device.

The application works, however, the list which is the application based Framework7 (indeed on Vue) does not show anything. It looks like Vue not initialized.

Here is the HTML code:

```<code><template  id="page-alt-sayfa">
<f7-page>
  <f7-navbar title="Alt Sayfa" back-link="Geri" sliding></f7-navbar>
  <f7-block-title>
  <!-- sayfa id'sini data obj iÃ§inde ara-->
  {{this.$root.$data['icerik'][$route.params['sayfaId']].baslik}}</p>
  </f7-block-title>
  <f7-block-title>Dondurucuya Konur mu?</f7-block-title>
  <f7-block inner>
    <img style="width:95%;overflow:hidden" :src="'./img/sembolik/'+$route.params['sayfaId']+'.png'"/>
    <br>
    <div v-if="this.$root.$data['icerik'][$route.params['sayfaId']].dondurucu">
      <div class="chip">
          <div class="chip-media bg-green"><i class="material-icons">dns</i></div>
          <div class="chip-label">Dondurucuya Konulur</div>
        </div>
    </div>
</code>```

Here is initializing Framework7 and Vue:

```<code>...
<script src="cordova.js"></script>
          <script src="js/framework7.min.js"></script>
          <script src="js/vue.min.js"></script>
          <script src="js/framework7-vue.min.js"></script>
          <script type="text/javascript" src="js/data.json"></script>
          <script src="js/app.js"></script>
        </body>

    </html>
</code>```

Here a screenshoot from my phone.

(source: ultraimg.com)

How can the problem be solved?

Edit:
Here is my router code:

```<code>// Init F7 Vue Plugin
Vue.use(Framework7Vue)
// Init Page Components
Vue.component('page-about', {
  template: '#page-about'
})
Vue.component('page-form', {
  template: '#page-form'
})
Vue.component('page-dynamic-routing', {
  template: '#page-dynamic-routing'
})
Vue.component('page-alt-sayfa', {
  template: '#page-alt-sayfa'
})
// Handle device ready event
// Note: You may want to check out the vue-cordova package on npm for cordova specific handling with vue - https://www.npmjs.com/package/vue-cordova
document.addEventListener('deviceready', () => {
  console.log("DEVICE IS READY!");
}, false)

// Init App
new Vue({
  el: '#app',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: [
      {
        path: '/about/',
        component: 'page-about'
      },
      {
        path: '/alt-sayfa/:sayfaId/',
        component: 'page-alt-sayfa'
      }
    ]
  },
  data: {
    mesaj: 'Merhaba',
    icerik: icerik
  }
});
</code>```

答:
I recently faced a similar problem. The routing was working well when tested my computer browser and emulator. But when I built the apk, it just did not work. It turned out I had a case sensitivity issue with the names of the views in my code. My computer and emulator ignored it and did the routing, but my phone didn't.

Have you crossed-checked the spelling of the names of your views to make sure it is not a case-sensitivity issue?

ContentLicense: CC BY-SA 4.0

Body:
I have tried out this tutorial to develop an android application via Cordova and Framework7. It works in the browser and also Android Emulator (ADK). I converted the project to the apk with Cordova build command and transferred the apk file to my device.

The application works, however, the list which is the application based Framework7 (indeed on Vue) does not show anything. It looks like Vue not initialized.

Here is the HTML code:

<template  id="page-alt-sayfa">
<f7-page>
  <f7-navbar title="Alt Sayfa" back-link="Geri" sliding></f7-navbar>
  <f7-block-title>

  {{this.$root.$data['icerik'][$route.params['sayfaId']].baslik}}

  </f7-block-title>
  <f7-block-title>Dondurucuya Konur mu?</f7-block-title>
  <f7-block inner>

dns

Dondurucuya Konulur

Here is initializing Framework7 and Vue:

...

Here a screenshoot from my phone.

(source: ultraimg.com)

How can the problem be solved?

Edit:
Here is my router code:

// Init F7 Vue Plugin
Vue.use(Framework7Vue)
// Init Page Components
Vue.component('page-about', {
  template: '#page-about'
})
Vue.component('page-form', {
  template: '#page-form'
})
Vue.component('page-dynamic-routing', {
  template: '#page-dynamic-routing'
})
Vue.component('page-alt-sayfa', {
  template: '#page-alt-sayfa'
})
// Handle device ready event
// Note: You may want to check out the vue-cordova package on npm for cordova specific handling with vue - https://www.npmjs.com/package/vue-cordova
document.addEventListener('deviceready', () => {
  console.log("DEVICE IS READY!");
}, false)

// Init App
new Vue({
  el: '#app',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: [
      {
        path: '/about/',
        component: 'page-about'
      },
      {
        path: '/alt-sayfa/:sayfaId/',
        component: 'page-alt-sayfa'
      }
    ]
  },
  data: {
    mesaj: 'Merhaba',
    icerik: icerik
  }
});


问:
Difference between completion variables and semaphores
In the linux kernel, semaphores are used to provide mutual exclusion for critical sections of data and Completion variables are used to synchronize between 2 threads waiting on an event. Why not use semaphores for such a synchronization ? Is there any advantage of using a completion variable over a semaphore ?</p>

答:
There are two reasons you might want to use a completion instead of a semaphore.  First, multiple threads can wait for a completion, and they can all be released with one call to complete_all().  It's more complex to have a semaphore wake up an unknown number of threads.

Second, if the waiting thread is going to deallocate the synchronization object, there is a race condition if you're using semaphores.  That is, the waiter might get woken up and deallocate the object before the waking thread is done with up().  This race doesn't exist for completions.   (See Lasse's post.)

ContentLicense: CC BY-SA 2.5


问:
How to get a data set to acutally read as values in order to change them?
Example: Data = (1, 2, 3, 4, 5, 6, 7, 8, 9). I want to subtract the mean value from each value. I tried using

```<code>L= (Data)

G= L - 5.4

print(G)
</code>```

but python doesn't read Data as actual values. How do I get python to read the individual values in my data set and subtract the mean from each one?

Please help. Thank you!

答:
You can also use numpy if you like:

```<code>import numpy as np

data = np.array(Data)

new_data = data - np.mean(data)
</code>```

This will give the desired output

```<code>array([-4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
</code>```

If you cannot use numpy then  - as in the other answers - a list comprehension is probably the best choice. As a small variation of Ajax1234's answer, I would calculate the mean first (otherwise it is calculated in each iteration):

```<code>m = float(sum(Data)) / len(Data)
new_data = tuple([vi - m for vi in Data])
</code>```

This yields

```<code> (-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0)
</code>```

Body:
Example: Data = (1, 2, 3, 4, 5, 6, 7, 8, 9). I want to subtract the mean value from each value. I tried using

L= (Data)

G= L - 5.4

print(G)

but python doesn't read Data as actual values. How do I get python to read the individual values in my data set and subtract the mean from each one?

Please help. Thank you!

Body:
You can also use numpy if you like:

import numpy as np

data = np.array(Data)

new_data = data - np.mean(data)

This will give the desired output

array([-4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])

If you cannot use numpy then  - as in the other answers - a list comprehension is probably the best choice. As a small variation of Ajax1234's answer, I would calculate the mean first (otherwise it is calculated in each iteration):

m = float(sum(Data)) / len(Data)
new_data = tuple([vi - m for vi in Data])

This yields

 (-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0)


问:
Importing Earth Engine javascript library into another javascript file
sorry I am not much of a Javascript programmer so this is a rather noob question. But I was having trouble trying to import the Google Earth Engine api file into another javascript file. All of the examples in the Earth Engine repo use a  in html to access the Earth Engine features, but I want to avoid using html.

I tried to follow standard Javascript procedures. Here is the code that I got.

```<code>var mymod = require('/../javascript/ee_api_js');

var image = mymod.Image('srtm90_v4');
var path = image.getDownloadURL({
    'scale': 30,
    'crs': 'EPSG:4326',
    'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]'
});
print(path);
</code>```

The error message I got back was:

```<code>var image = mymod.Image('srtm90_v4');
                  ^
TypeError: mymod.Image is not a function
</code>```

The original ee_api_js.js file is located in the github repo at:
https://github.com/google/earthengine-api/tree/master/javascript/build

Not sure why this module is not importing correctly? Any ideas.

答:
I suspect your life will be a lot easier if you alias that:</p>

```<code>var ee = require('...').ee
</code>```

Body:
sorry I am not much of a Javascript programmer so this is a rather noob question. But I was having trouble trying to import the Google Earth Engine api file into another javascript file. All of the examples in the Earth Engine repo use a  in html to access the Earth Engine features, but I want to avoid using html.

I tried to follow standard Javascript procedures. Here is the code that I got.

var mymod = require('/../javascript/ee_api_js');

var image = mymod.Image('srtm90_v4');
var path = image.getDownloadURL({
    'scale': 30,
    'crs': 'EPSG:4326',
    'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]'
});
print(path);

The error message I got back was:

var image = mymod.Image('srtm90_v4');
                  ^
TypeError: mymod.Image is not a function

The original ee_api_js.js file is located in the github repo at:
https://github.com/google/earthengine-api/tree/master/javascript/build

Not sure why this module is not importing correctly? Any ideas.

Body:
I suspect your life will be a lot easier if you alias that:

var ee = require('...').ee


问:
Print 2 ArrayLists with specific format
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

```<code>public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}
</code>```

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

```<code>itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();
</code>```

The constructors, respectively:

```<code>public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}
</code>```

and

```<code>public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}
</code>```

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

```<code>customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...
</code>```

Any help would be appreciated!

答:
EDITED FOR SPECIFIC FORMAT

Adding extra code to @Shiksha Verma to print the customer name and ID only once:

```<code>int x = 0;
for(CafeCustomer customer : customers ){
   for(CafeOrders order: itemOrders ){
       if(customer.getOrderNo.equals(order.getOrderId()) ){
           if(x == 0){
               System.out.println(customer.getCustomerName() +"with Id " +
               customer.getCustomerId()+ "has purchased: "
               +order.getItemName());
               x = 1;
               continue;
           }
           System.out.printf("%1$40s",order.getItemName());
       }
   }
   x = 0;
}
</code>```

Title: Print 2 ArrayLists with specific format

Body:
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();

The constructors, respectively:

public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}

and

public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...

Any help would be appreciated!

Body:
EDITED FOR SPECIFIC FORMAT

Adding extra code to @Shiksha Verma to print the customer name and ID only once:

int x = 0;
for(CafeCustomer customer : customers ){
   for(CafeOrders order: itemOrders ){
       if(customer.getOrderNo.equals(order.getOrderId()) ){
           if(x == 0){
               System.out.println(customer.getCustomerName() +"with Id " +
               customer.getCustomerId()+ "has purchased: "
               +order.getItemName());
               x = 1;
               continue;
           }
           System.out.printf("%1$40s",order.getItemName());
       }
   }
   x = 0;
}


问:
C++ if a pointer point to nullptr, can I replace it with number?

Hey guys, I encountered some problems about C++. Actually it's not the problem of language feature, otherwise it is related to kind of coding style.

OK, Let's get to the point!

I try to write the AVL Tree and want to calculate the balance factors,
and according the rule, the subtree without nodes(just a empty tree),
its height should be treated as -1. Yeah, everything thinks fine,
but when I write the code, use pointer to read Node class member,
I cannot read the nullptr BAD ACCESS, so I add lots of conditions, which makes my code look bad. Here is some parts of my code.

```<code>struct Node{
    int key;
    int height;
    Node* left;
    Node* right;
    Node* parent;
    Node(void);
    Node(int key);
};

    while((parent_node->left->height - parent_node->right->height) <= 1
          ||(parent_node->left->height - parent_node->right->height) >= (-1))
    {
        parent_node = parent_node->parent;
        if(parent_node == nullptr) break;
    }
</code>```

The result I want is that when the parent_node's left subtree is empty,
its height will be treated as -1. And the fact is, though it's empty, its height should not exist.
So in the code I only list four cases

1. left subtree == nullptr && right subtree == nullptr

2. left subtree != nullptr && right subtree == nullptr

3. left subtree != nullptr && right subtree != nullptr

4. left subtree == nullptr && right subtree != nullptr

Then I replace the code of height part with the value -1 respectively.
It feels painful. And this condition happens in my coding time many times, I want to find the better solution.

My English is not that good, so my description maybe sort of misleading, I will appreciate it if you help me in any way.

答:
Create a function that compute the height of a subtree including the special cases, and use that instead of accessing the ->height data member:

```<code>int heightOfSubtree(Node* tree) {
    if (tree == nullptr) {
        return -1;
    }
    else {
        return tree-> height;
    }
}
</code>```

then your code becomes:

```<code>while((heightOfSubtree(parent_node->left) - heightOfSubtree(parent_node->right)) <= 1
      ||((heightOfSubtree(parent_node->left) - heightOfSubtree(parent_node->right)) >= (-1))
{
    ...
}
</code>```

or better, you can define a member function in the Node structure such as this:

```<code>bool Node::isBalanced() {
    int unb = heightOfSubtree(left) - heightOfSubtree(right);
    return (unb <= 1) || (unb >=-1);
}
</code>```

and your while condition becomes:

```<code>while(parent_node->isBalanced()) {
    ...
}
</code>```

p.s.: I believe there is a logical error in your code: I am not sure the condition you are checking is correct, since it is always true (any number is either bigger than -1 or smaller than 1, for some both are true)

Body:
Hey guys, I encountered some problems about C++. Actually it's not the problem of language feature, otherwise it is related to kind of coding style.

OK, Let's get to the point!

I try to write the AVL Tree and want to calculate the balance factors,
and according the rule, the subtree without nodes(just a empty tree),
its height should be treated as -1. Yeah, everything thinks fine,
but when I write the code, use pointer to read Node class member,
I cannot read the nullptr BAD ACCESS, so I add lots of conditions, which makes my code look bad. Here is some parts of my code.

struct Node{
    int key;
    int height;
    Node* left;
    Node* right;
    Node* parent;
    Node(void);
    Node(int key);
};

    while((parent_node->left->height - parent_node->right->height) <= 1
          ||(parent_node->left->height - parent_node->right->height) >= (-1))
    {
        parent_node = parent_node->parent;
        if(parent_node == nullptr) break;
    }

The result I want is that when the parent_node's left subtree is empty,
its height will be treated as -1. And the fact is, though it's empty, its height should not exist.
So in the code I only list four cases

1. left subtree == nullptr && right subtree == nullptr

2. left subtree != nullptr && right subtree == nullptr

3. left subtree != nullptr && right subtree != nullptr

4. left subtree == nullptr && right subtree != nullptr

Then I replace the code of height part with the value -1 respectively.
It feels painful. And this condition happens in my coding time many times, I want to find the better solution.

My English is not that good, so my description maybe sort of misleading, I will appreciate it if you help me in any way.

Body:
Create a function that compute the height of a subtree including the special cases, and use that instead of accessing the ->height data member:

int heightOfSubtree(Node* tree) {
    if (tree == nullptr) {
        return -1;
    }
    else {
        return tree-> height;
    }
}

then your code becomes:

while((heightOfSubtree(parent_node->left) - heightOfSubtree(parent_node->right)) <= 1
      ||((heightOfSubtree(parent_node->left) - heightOfSubtree(parent_node->right)) >= (-1))
{
    ...
}

or better, you can define a member function in the Node structure such as this:

bool Node::isBalanced() {
    int unb = heightOfSubtree(left) - heightOfSubtree(right);
    return (unb <= 1) || (unb >=-1);
}

and your while condition becomes:

while(parent_node->isBalanced()) {
    ...
}

p.s.: I believe there is a logical error in your code: I am not sure the condition you are checking is correct, since it is always true (any number is either bigger than -1 or smaller than 1, for some both are true)


问:
Import classes from external typescript library which uses namespaces
I have an existing Angular 2 Project and now I have to use an external TypeScript Library which uses Namespaces. I somehow need to import some classes from the External library so I can use them.

externalLibrary.ts:

```<code>namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}
</code>```

And in My Angular2 Component I want to to do:

```<code>myA: A = new A();
myA.doSomething();
</code>```

So far, i have tried:

1)

```<code>import {A} from '../dir/externalLibrary';
</code>```

which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

2)

```<code>/// <reference path='../dir/externalLibrary.ts'>
...
myA: com.foo.bar.A = new com.foo.bar.A();
</code>```

which results in a run-time error saying: 'ReferenceError: com is not defined'

My Question is: How can I use the class A in my Project?
I am thankful for any help.

EDIT 1:

Just for clarification: The external library is a Java Library which is then transpiled into TypeScript. It consists of ~80.000 lines of code, therefore I can not change too much, because it would take too much time. This is also the reason why I have to stick to namespaces because the Typescipt transpiler creates them out of the existing java package structure.

@Aaron: Thanks for the answer but my upcoming problem with the 'export namespace' approach is as follows:
If i put 'export' before a namespace other Classes can not be found any longer:

b.ts:

```<code>export namespace com.foo.bar
{
    export interface B {

    }
}
</code>```

a.ts

```<code>export namespace com.foo.bar {

    export class A implements B
    {

    }
}
</code>```

In file a.ts the compiler says: 'cannot find name B'.
I also tried to somehow import B but I failed. Is there any posibillity to import B or am I completely on the wrong way?

答:
you should export your namespace too:

export namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}```

and then:

import * as comFooBar from '../dir/externalLibrary';

Body:
I have an existing Angular 2 Project and now I have to use an external TypeScript Library which uses Namespaces. I somehow need to import some classes from the External library so I can use them.

externalLibrary.ts:

namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}

And in My Angular2 Component I want to to do:

myA: A = new A();
myA.doSomething();

So far, i have tried:

1)

import {A} from '../dir/externalLibrary';

which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

2)

/// <reference path='../dir/externalLibrary.ts'>
...
myA: com.foo.bar.A = new com.foo.bar.A();

which results in a run-time error saying: 'ReferenceError: com is not defined'

My Question is: How can I use the class A in my Project?
I am thankful for any help.

EDIT 1:

Just for clarification: The external library is a Java Library which is then transpiled into TypeScript. It consists of ~80.000 lines of code, therefore I can not change too much, because it would take too much time. This is also the reason why I have to stick to namespaces because the Typescipt transpiler creates them out of the existing java package structure.

@Aaron: Thanks for the answer but my upcoming problem with the 'export namespace' approach is as follows:
If i put 'export' before a namespace other Classes can not be found any longer:

b.ts:

export namespace com.foo.bar
{
    export interface B {

    }
}

a.ts

export namespace com.foo.bar {

    export class A implements B
    {

    }
}

In file a.ts the compiler says: 'cannot find name B'.
I also tried to somehow import B but I failed. Is there any posibillity to import B or am I completely on the wrong way?

Body:
you should export your namespace too:

export namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}

and then:

import * as comFooBar from '../dir/externalLibrary';


答:
While this code works:

```<code>public void displayOrders(){
    for(CafeCustomer customer : customers ){
        for(CafeOrders order: itemOrders ){
            if(customer.getOrderNo().equals(order.getOrderID()) ){
                display(customer.getCustomerID()+"."+customer.getCustomerName() +"with Order ID " +
                customer.getOrderNo() + " has purchased a "
                +order.getItemName());
            }
        }
    }
}
</code>```

I want the customer ID,name and order ID to appear once and then on the right the list of the items. Like I showed in my initial post.

Is it possible? I can't seem to find a way to do it.
Like this:

```<code>customerID"."customerName "with id" orderID "has purchased" itemName1
                                                            itemName2
                                                            itemName3
                                                            etc...
</code>```

And it appears exactly like this.

Title: Print 2 ArrayLists with specific format

Body:
While this code works:

public void displayOrders(){
    for(CafeCustomer customer : customers ){
        for(CafeOrders order: itemOrders ){
            if(customer.getOrderNo().equals(order.getOrderID()) ){
                display(customer.getCustomerID()+"."+customer.getCustomerName() +"with Order ID " +
                customer.getOrderNo() + " has purchased a "
                +order.getItemName());
            }
        }
    }
}

I want the customer ID,name and order ID to appear once and then on the right the list of the items. Like I showed in my initial post.

Is it possible? I can't seem to find a way to do it.
Like this:

customerID"."customerName "with id" orderID "has purchased" itemName1
                                                            itemName2
                                                            itemName3
                                                            etc...

And it appears exactly like this.


问:
Import feeds from Google Reader
I am making a webapp that uses feeds to get website urls. I want to make it so users can click a button and it will automatically add all of the feeds from their google reader accounts. Is there a way to do this? Thanks in advance for any help.</p>

答: check out the answer to Google Reader API?</p>

Title: Import feeds from Google Reader


问:
Control image quality after transform scaling
For example:

there is an 1000x1000 image

I add style to it width:10px

I add transform style that scales it by 100x: transform: scale(100, 100)

And finally image size becomes 1000px.

The problem:

I expect the image to be blurred, since it's 100x scaled from 10px. But it's not, the image is full resolution.

Is there any way to control the quality? I tried applying to scale to parent element, to child element itself, but no matter what I do - image is rendered at the real size.

JSFiddle https://jsfiddle.net/dpfmp4hz/

Why I need this:

I need to run scaling animation from 4000x4000 image to 600x600, and scaling down causes significant lag. What's interesting is that scaling from 600x600 to 4000x4000 is very smooth, since I apply 4000x4000 dimensions only after transition is finished.

I really don't want to use canvas...

Thank you for any help!

答:
I have created a fiddle with a reduction from 4000px down to 600px, I don't see any lag as you describe using the following css:

```<code>img {
  width: 4000px;
  height: auto;
}
.parent {
  transform-origin: 0 0;
  transition: all 1s ease-in-out;
  display: inline-block;
}
.parent:hover {
  transform: scale(.15, .15);
}
</code>```

https://jsfiddle.net/p5yL6fwo/1/

Is there something further to your issue which I am not seeing? Are you using a device/computer which might struggle repainting such an image transition?

This is the same but transforming up, again no lag:
https://jsfiddle.net/he12r8g5/

Body:
I have created a fiddle with a reduction from 4000px down to 600px, I don't see any lag as you describe using the following css:

img {
  width: 4000px;
  height: auto;
}
.parent {
  transform-origin: 0 0;
  transition: all 1s ease-in-out;
  display: inline-block;
}
.parent:hover {
  transform: scale(.15, .15);
}

https://jsfiddle.net/p5yL6fwo/1/

Is there something further to your issue which I am not seeing? Are you using a device/computer which might struggle repainting such an image transition?

This is the same but transforming up, again no lag:
https://jsfiddle.net/he12r8g5/


问:
Modifying the value of a Maven Property when Substituting it
Is there a way in Maven to convert the value of a property, such as through a simple String.replace() call, before the value is substituted into a file?

I have a situtation where I am trying to create an assembly containing maven depenedencies with a particular directory structure.  In particular, I want to place each artifact into a directory sturcture that maps to its groupId.  In other words, if I have artifact org.example.app:library1:jar, I want to place it into the directory org/example/app/library1.jar.

I tried creating an Assembly descriptor to put the dependent artifacts into a subdirectory, but I have reached a point where I cannot convert the groupId (with dot notation) into a path.  Below is the dependencySet portion of the assembly file that I am using.

```<code><dependencySets>
  <dependencySet>
    <outputFileNameMapping>${artifact.groupId}/${artifact.artifactId}/${artifact.version}/${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}</outputFileNameMapping>
    <outputDirectory>.</outputDirectory>
    <unpack>false</unpack>
    <useTransitiveDependencies>true</useTransitiveDependencies>
    <useTransitiveFiltering>false</useTransitiveFiltering>
    <useProjectArtifact>false</useProjectArtifact>
  </dependencySet>
</dependencySets>
</code>```

P.S. I also investigated the Assembly plugin's repository mode, but it includes too much information (e.g. SHA1 and MD5 hashes, plus Maven POM files).

答:
The assembly descriptor file is used by the assembly plugin and, by itself has no mechanisms to embed Maven properties such as ${my.property}.  However, as a work-around you could use the maven resources plugin to "filter" the assembly descriptor file (while it is being copied from one place to another).  This would enable the substitution you'd be looking for.

Then you would have the Maven assembly plugin use the filtered descriptor file.

Body:
Is there a way in Maven to convert the value of a property, such as through a simple String.replace() call, before the value is substituted into a file?

I have a situtation where I am trying to create an assembly containing maven depenedencies with a particular directory structure.  In particular, I want to place each artifact into a directory sturcture that maps to its groupId.  In other words, if I have artifact org.example.app:library1:jar, I want to place it into the directory org/example/app/library1.jar.

I tried creating an Assembly descriptor to put the dependent artifacts into a subdirectory, but I have reached a point where I cannot convert the groupId (with dot notation) into a path.  Below is the dependencySet portion of the assembly file that I am using.

<dependencySets>
  <dependencySet>
    <outputFileNameMapping>${artifact.groupId}/${artifact.artifactId}/${artifact.version}/${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}</outputFileNameMapping>
    <outputDirectory>.</outputDirectory>
    <unpack>false</unpack>
    <useTransitiveDependencies>true</useTransitiveDependencies>
    <useTransitiveFiltering>false</useTransitiveFiltering>
    <useProjectArtifact>false</useProjectArtifact>
  </dependencySet>
</dependencySets>

P.S. I also investigated the Assembly plugin's repository mode, but it includes too much information (e.g. SHA1 and MD5 hashes, plus Maven POM files).


问:
How to create new instance of contract for whole test suite truffle
I am setting up an ERC20 token ICO on the ethereum network using Solidity and Truffle.

Can anyone tell me why this is not working, I have 4 test files (as I would ideally like to keep them as short and concise as possible), one for testing the token, one for testing the set-up of the crowdsale, one for testing a successful run through (where the cap is reached) and one for testing the emergency stop functionality.

For this reason, I would like to run through multiple it() test cases which use the preceding values to test their own thing in each file i.e.

In the set-up test file:

First it() tests if the contract is deployed

Second it() tests if the contracts variables are set correctly etc.

I have then attempted to create a new instance of the token and contract on each file so that I can run through various test cases.

Each file starts with:

```<code>  Token.new(initialAmount, tokenName, decimalUnits,tokenSymbol, {from: account_one});
  Sale.new(softCap, hardCap, etherCostOfEachToken, account_one, token, durationInMinutes, {from: account_one});
</code>```

However, when running through my tests I get the error:

```<code>AssertionError: State of contract was not 'Waiting approval': expected '4' to equal 1
at /Users/jackpickering/Desktop/Development/Capped_ICO/test/4Crowdsale_EmergencyStop_Test.js:28:14
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
</code>```

The status has not been reset back to 1 after finishing the Successful crowdsale test file had ran and therefore, the Sale.new() line must not work.

Is there a better way to do this? Am I missing anything?

Thanks in advance.

答:
The reason I was getting this error was because I was not waiting until the contract had been deployed to the network, instead I changed these to be performed within an asynchronous function and used the 'await' function to wait until the contract had been deployed before carrying on with the rest of the tests. </p>

<p>My working code is as follows: </p>

```<code>it("should create new token", async function() {
  token = await Token.new(initialAmount, tokenName, decimalUnits,tokenSymbol)
  supply = await token.totalSupply();
  assert.equal(supply, 10000000, "New crowdsale was not created");
});

it("should create new crowdsale", async function() {
  sale = await Sale.new(softCap, hardCap, etherCostOfEachToken, account_one, Token(token), durationInMinutes);
  state = await sale.getState();
  assert.equal(state, 1, "New crowdsale was not created");
});
</code>```

Body:
I am setting up an ERC20 token ICO on the ethereum network using Solidity and Truffle.

Can anyone tell me why this is not working, I have 4 test files (as I would ideally like to keep them as short and concise as possible), one for testing the token, one for testing the set-up of the crowdsale, one for testing a successful run through (where the cap is reached) and one for testing the emergency stop functionality.

For this reason, I would like to run through multiple it() test cases which use the preceding values to test their own thing in each file i.e.

In the set-up test file:

First it() tests if the contract is deployed

Second it() tests if the contracts variables are set correctly etc.

I have then attempted to create a new instance of the token and contract on each file so that I can run through various test cases.

Each file starts with:

  Token.new(initialAmount, tokenName, decimalUnits,tokenSymbol, {from: account_one});
  Sale.new(softCap, hardCap, etherCostOfEachToken, account_one, token, durationInMinutes, {from: account_one});

However, when running through my tests I get the error:

AssertionError: State of contract was not 'Waiting approval': expected '4' to equal 1
at /Users/jackpickering/Desktop/Development/Capped_ICO/test/4Crowdsale_EmergencyStop_Test.js:28:14
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)

The status has not been reset back to 1 after finishing the Successful crowdsale test file had ran and therefore, the Sale.new() line must not work.

Is there a better way to do this? Am I missing anything?

Thanks in advance.

Body:
The reason I was getting this error was because I was not waiting until the contract had been deployed to the network, instead I changed these to be performed within an asynchronous function and used the 'await' function to wait until the contract had been deployed before carrying on with the rest of the tests.

My working code is as follows:

it("should create new token", async function() {
  token = await Token.new(initialAmount, tokenName, decimalUnits,tokenSymbol)
  supply = await token.totalSupply();
  assert.equal(supply, 10000000, "New crowdsale was not created");
});

it("should create new crowdsale", async function() {
  sale = await Sale.new(softCap, hardCap, etherCostOfEachToken, account_one, Token(token), durationInMinutes);
  state = await sale.getState();
  assert.equal(state, 1, "New crowdsale was not created");
});


问:
Bootstrap tooltip vs normal HTML title
I'm going to add a lot of tooltips to my web site in order to guide the visitor.

I can do this easily with the HTML title-attribute. But I can also use the Bootstrap's tooltip plugin (this requires an extra data-toggle-attribute for each tooltip though).

Is there any obvious reason why I should avoid using the easier HTML title-tag only?

I'm not interesting in positioning and layout of the tooltip. I simply want to show the text.

答:
Since that you're only interested in showing the text you probably should go for HTML title attribute but to be sure, ask yourself if the text has a any meaning, semantic meaning, if yes, use Title attribute if not (and it's there to make the website cooler), use CSS or bootstrap framework or whatsoever you wish.

So whenever you're between HTML or Something else, HTML is for 1st structure 2nd the meaning.

Title: Bootstrap tooltip vs normal HTML title


问:
Exception handling in a @testset in Julia
what is the prefered way to investigate or print out further detail (print input variable of a function, iteration number, etc.) of a failed @test inside a @testset?
I tried to wrap a try-catch-block around it. However, it doesn't seem to fire.

Here is a made-up example:

```<code>using Base.Test
rng = MersenneTwister(3231);

# define function that works different than expected
function compare(a,b)
    if a == 3 && b == 3
        return false
    else
        return a == b
    end
end

# test function in a test set
@testset "Test Compare Function" begin
    for iii = 1:10
        number = rand(rng,1:10)
        try
            @test compare(number,number) == true
        catch
            @show(number)
        end
    end
end
</code>```

Thank you very much!

答:
You need to make sure it tests after the printing.</p>

```<code>@testset "Test Compare Function" begin
    for iii = 1:10
        number = rand(rng,1:10)
        @test begin
             res = compare(number,number) == true
             if !res
                 @show number
                 flush(STDOUT)
             end
             res
        end
    end
end
</code>```

Body:
what is the prefered way to investigate or print out further detail (print input variable of a function, iteration number, etc.) of a failed @test inside a @testset?
I tried to wrap a try-catch-block around it. However, it doesn't seem to fire.

Here is a made-up example:

using Base.Test
rng = MersenneTwister(3231);

# define function that works different than expected
function compare(a,b)
    if a == 3 && b == 3
        return false
    else
        return a == b
    end
end

# test function in a test set
@testset "Test Compare Function" begin
    for iii = 1:10
        number = rand(rng,1:10)
        try
            @test compare(number,number) == true
        catch
            @show(number)
        end
    end
end

Thank you very much!

Body:
You need to make sure it tests after the printing.

@testset "Test Compare Function" begin
    for iii = 1:10
        number = rand(rng,1:10)
        @test begin
             res = compare(number,number) == true
             if !res
                 @show number
                 flush(STDOUT)
             end
             res
        end
    end
end


问:
Jupyter Notebook in virtual environment doesn't see the virtual env packages
I'm trying to use a Jupyter Notebook in a virtual environment.
I have created a new virtualenv virtualenv ker12
+ activate + installed a specific version of keras or any other library.

also as mentioned in Using a virtualenv in an IPython notebook I did:

pip install ipykernel

and

python -m ipykernel install --user --name=my-virtualenv-name

when I run the notebook and write
! which jupyter the output is correct

/Users/myname/virtualenv/ker12/bin/python

but when I try to import a library, for example import keras there is an error.

ImportError: No module named keras

But from the other side when I write pip freeze | grep Keras
the output is:

Keras==1.2.0

UPDATE 1:

this problem is not related to Keras it occurs with any other library (for example pandas)

If I print os.path the output is following:

<'module 'posixpath' from /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc>

From a "command line python" the os.path looks correct

<'module 'posixpath' from '/Users/my_name/virtualenv/ker12/lib/python2.7/posixpath.pyc'>

UPDATE 2:

If I print sys.path from terminal and jupyter the output is also different:

from terminal

/Users/myname/virtualenv/ker12/lib/python27.zip
  /Users/myname/virtualenv/ker12/lib/python2.7
  /Users/myname/virtualenv/ker12/lib/python2.7/plat-darwin
  /Users/myname/virtualenv/ker12/lib/python2.7/plat-mac
  /Users/myname/virtualenv/ker12/lib/python2.7/plat-mac/lib-scriptpackages
  /Users/myname/virtualenv/ker12/lib/python2.7/lib-tk
  /Users/myname/virtualenv/ker12/lib/python2.7/lib-old
  /Users/myname/virtualenv/ker12/lib/python2.7/lib-dynload
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
  /Users/myname/virtualenv/ker12/lib/python2.7/site-packages

from JUPYTER

/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
  /usr/local/lib/python2.7/site-packages
  /usr/local/lib/python2.7/site-packages/IPython/extensions
  /Users/myname/.ipython `

答:
the solution is to open jupyter notebook with following command:

~/virtualenv/my_venv_name/bin/jupyter-notebook


问:
mule : Scatter and Gather: How to aggregate scatter gather result with original payload?
I have scatter gather component which calls multiple services and aggregates the result as list of maps. I would like to know is there any way to merge the original payload ( payload which is an input to Scatter Gather) with this result?</p>

答:
Say if you have a map(Key value pair) given as input to scatter-gather flow.And Scatter-gather in turn gives out list of Map.Then you can follow below steps

Store the "input" to scatter-gather into a flowVar/SessionVar depending on your need.

Once you are out of scatter-gather flow,add Set Payload transformer.

In "Set Payload" transformer add [payload.addAll(flowVars['flowVar_Name_which_you_saved_earlier']) as value.


问:
Mysql select rows except first row
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

```<code>SELECT * FROM table ORDER BY id DESC
</code>```

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

```<code>$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");
</code>```

答:
Try this:

```<code>SELECT *
FROM
(
    SELECT *, row_number()
    OVER (ORDER BY id DESC) row
    FROM table
)
WHERE row != 1
</code>```

It gives numbers to your selected rows and takes all of them without the one with row number 1

Title: Mysql select rows except first row

Body:
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

SELECT * FROM table ORDER BY id DESC

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");

Body:
Try this:

SELECT *
FROM
(
    SELECT *, row_number()
    OVER (ORDER BY id DESC) row
    FROM table
)
WHERE row != 1

It gives numbers to your selected rows and takes all of them without the one with row number 1


问:
How to click option that appeard on small pop window in selenium?
I'm trying to make the script for uploading the files from my local disk to google drive using selenium. I am success upto successful login and clicking new button on google drive desktop version but after that I am not able to select option that appears under new small window ( window that appears after 'new' button is pressed ) </p>

<p>My code till now: </p>

```<code>#!/usr/bin/python
    from selenium import webdriver
    import time
    from selenium.webdriver.common.keys import Keys

    browser=webdriver.Firefox()
    #gdURL='https://drive.google.com'
    gdURL='https://accounts.google.com/ServiceLogin?service=wise&passive=true&   continue=http%3A%2F%2Fdrive.google.com%2F%3Futm_source%3Den_US&  utm_medium=button&utm_campaign=web&utm_content=gotodrive&usp=gtd&ltmpl=drive'
   browser.get(gdURL)
   def idIn(email):
       gId=browser.find_element_by_id('identifierId')
       gId.send_keys(email)
       gId.send_keys(Keys.ENTER)
       time.sleep( 10 )
   def passIn(passwd):
       gPass=browser.find_element_by_name('password')
       gPass.send_keys(passwd)
       gPass.send_keys(Keys.ENTER)
       time.sleep( 30 )
   if browser.find_element_by_id('identifierId'):
       idIn('myemail')
       passIn('mypassword')
   #if browser.find_element_by_name('password'):
   #   passIn('mypassword')
   btn=browser.find_elements_by_tag_name('button')
   btn[4].click()
</code>```

答:
This may help - So you need to switch to the new browser instance using window handles. I don't know if this only works in Windows systems though.

Apologies, the code below is in Java:

```<code>// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle); }
// Perform the actions on new window
// Close the new window, if that window no more required driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
//continue with original browser (first window)
</code>```

See the source post for this answer here.

Body:
I'm trying to make the script for uploading the files from my local disk to google drive using selenium. I am success upto successful login and clicking new button on google drive desktop version but after that I am not able to select option that appears under new small window ( window that appears after 'new' button is pressed )

My code till now:

#!/usr/bin/python
    from selenium import webdriver
    import time
    from selenium.webdriver.common.keys import Keys

    browser=webdriver.Firefox()
    #gdURL='https://drive.google.com'
    gdURL='https://accounts.google.com/ServiceLogin?service=wise&passive=true&   continue=http%3A%2F%2Fdrive.google.com%2F%3Futm_source%3Den_US&  utm_medium=button&utm_campaign=web&utm_content=gotodrive&usp=gtd&ltmpl=drive'
   browser.get(gdURL)
   def idIn(email):
       gId=browser.find_element_by_id('identifierId')
       gId.send_keys(email)
       gId.send_keys(Keys.ENTER)
       time.sleep( 10 )
   def passIn(passwd):
       gPass=browser.find_element_by_name('password')
       gPass.send_keys(passwd)
       gPass.send_keys(Keys.ENTER)
       time.sleep( 30 )
   if browser.find_element_by_id('identifierId'):
       idIn('myemail')
       passIn('mypassword')
   #if browser.find_element_by_name('password'):
   #   passIn('mypassword')
   btn=browser.find_elements_by_tag_name('button')
   btn[4].click()

Body:
This may help - So you need to switch to the new browser instance using window handles. I don't know if this only works in Windows systems though.

Apologies, the code below is in Java:

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle); }
// Perform the actions on new window
// Close the new window, if that window no more required driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
//continue with original browser (first window)

See the source post for this answer here.


问:
Why passing &error instead of error in Cocoa programming?
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?</p>

```<code>NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code
</code>```

答:
When you call the method, you aren't giving it a pointer to an NSError, you're giving it a place to pass a pointer to an NSError back to you.

I often write

```<code>NSError *error = nil;
</code>```

which makes it a bit more obvious that there nothing (interesting) in error when you call -save:.  It's just a place you've set aside for the address in memory of an NSError object.  If the method encounters an error, it creates an NSError object and writes the address of the object in error to pass it back to you.

Body:
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?

NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code

Body:
When you call the method, you aren't giving it a pointer to an NSError, you're giving it a place to pass a pointer to an NSError back to you.

I often write

NSError *error = nil;

which makes it a bit more obvious that there nothing (interesting) in error when you call -save:.  It's just a place you've set aside for the address in memory of an NSError object.  If the method encounters an error, it creates an NSError object and writes the address of the object in error to pass it back to you.


问:
SPARQL: Distinct with different data types
I have a request in SPARQL on DBPEDIA,
I would like to get actors with their birth date, name ...
For instance:

```<code>select ?actor ?name ?birthDate where {
    ?actor <http://purl.org/linguistics/gold/hypernym> dbr:Actor ;
    rdfs:label ?name ; dbo:birthDate ?birthDate .
    filter(?name = "Tom Cruise"@en)
} LIMIT 5
</code>```

I get this result:

My concern is about the data type of birthDate, I am looking for a way to declare a DISTINCT type insensitive and so have only one result in the previous request.

Any ideas?

答:
First, I think that DBpedia uses only xsd:date data type for birthdates, to make sure, you can try out this query:

```<code>select distinct datatype(?birthDate)  where {
  ?actor <http://purl.org/linguistics/gold/hypernym> dbr:Actor ;
  dbo:birthDate ?birthDate .
}
</code>```

The problem is that some of the values are dirty, as mentioned in the comments, they need to be cleansed. There is some workaround for that, but not sure if it is fine for you.

First, you should guarantee that all formats of the same intended date are unified, so that DISTINCT can be used to filter.

For some reason, that I am not really aware of, xsd:dateTime shows some tolerance in practice, while it should take values of yyyy-mm-dd ...., it accepts values of the form yyyy-m-d ..... As a consequence, convert ?birthDate to xsd:dateTime, and then to xsd:date. For example, try select xsd:date (xsd:dateTime ("2000-1-1")) {}, it results in "2000-01-01"^^xsd:date. Somehow, it just works.

Then, and as some data are dirty, you have no option, but to get rid of these data, i.e., values like 2000-0-0 should be excluded. To do this you should make sure that transferring the value of ?birthDate to the required format succeeds. To this end ( coalesce(xsd:dateTime(xsd:date(?birthDate)), '!') ) would do it, as it returns '!' if the ?birthDate cannot be cast.

I don't have a working query, but this should, in principle, help.

Body:
I have a request in SPARQL on DBPEDIA,
I would like to get actors with their birth date, name ...
For instance:

select ?actor ?name ?birthDate where {
    ?actor <http://purl.org/linguistics/gold/hypernym> dbr:Actor ;
    rdfs:label ?name ; dbo:birthDate ?birthDate .
    filter(?name = "Tom Cruise"@en)
} LIMIT 5

I get this result:

My concern is about the data type of birthDate, I am looking for a way to declare a DISTINCT type insensitive and so have only one result in the previous request.

Any ideas?

Body:
First, I think that DBpedia uses only xsd:date data type for birthdates, to make sure, you can try out this query:

select distinct datatype(?birthDate)  where {
  ?actor <http://purl.org/linguistics/gold/hypernym> dbr:Actor ;
  dbo:birthDate ?birthDate .
}

The problem is that some of the values are dirty, as mentioned in the comments, they need to be cleansed. There is some workaround for that, but not sure if it is fine for you.

First, you should guarantee that all formats of the same intended date are unified, so that DISTINCT can be used to filter.

For some reason, that I am not really aware of, xsd:dateTime shows some tolerance in practice, while it should take values of yyyy-mm-dd ...., it accepts values of the form yyyy-m-d ..... As a consequence, convert ?birthDate to xsd:dateTime, and then to xsd:date. For example, try select xsd:date (xsd:dateTime ("2000-1-1")) {}, it results in "2000-01-01"^^xsd:date. Somehow, it just works.

Then, and as some data are dirty, you have no option, but to get rid of these data, i.e., values like 2000-0-0 should be excluded. To do this you should make sure that transferring the value of ?birthDate to the required format succeeds. To this end ( coalesce(xsd:dateTime(xsd:date(?birthDate)), '!') ) would do it, as it returns '!' if the ?birthDate cannot be cast.

I don't have a working query, but this should, in principle, help.


问:
Selenium WD / Java | Cannot create 'if' & 'else if' statement
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}
</code>```

I get a syntax error under 'else' :

Syntax error on token "else", delete this token

答:
The code you posted has a few issues.

You put ; at the end of the if and else if statements. They should both be removed.

You are comparing an element Status (that is currently null) to a .findElement() return. If the element is not found, it will throw an exception, not return a null element. The way to get around this is to use .findElements() (note the plural, Elements) and check to see if the list is empty. If it is empty, the element was not found.

Your .back() statement exists in both cases. Because of this, it can be moved out of the if and will get executed either way.

Rewritten code

```<code>public static void runTestClock(WebDriver driver)
{
    if (driver.findElements(By.cssSelector(".redClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is closed");
    }
    else if (driver.findElements(By.cssSelector(".greenClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is open");
    }
    driver.navigate().back();
}
</code>```

Having said all that... by looking at the CSS selectors you are using, I would guess that green means the stock is open and red means it's closed. This would mean that you have your logic backwards. I think you will need to switch your messages open <-> closed but you would know better than I...

Body:
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}

I get a syntax error under 'else' :

Syntax error on token "else", delete this token

Body:
The code you posted has a few issues.

You put ; at the end of the if and else if statements. They should both be removed.

You are comparing an element Status (that is currently null) to a .findElement() return. If the element is not found, it will throw an exception, not return a null element. The way to get around this is to use .findElements() (note the plural, Elements) and check to see if the list is empty. If it is empty, the element was not found.

Your .back() statement exists in both cases. Because of this, it can be moved out of the if and will get executed either way.

Rewritten code

public static void runTestClock(WebDriver driver)
{
    if (driver.findElements(By.cssSelector(".redClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is closed");
    }
    else if (driver.findElements(By.cssSelector(".greenClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is open");
    }
    driver.navigate().back();
}

Having said all that... by looking at the CSS selectors you are using, I would guess that green means the stock is open and red means it's closed. This would mean that you have your logic backwards. I think you will need to switch your messages open <-> closed but you would know better than I...


问:
Not able to click a dropdown field which is designed in the DOJO Html using selenium
I am not able to click an arrow drop down filed in my application using selenium web driver.

I tried lot of XPath using class name and relative XPath

This is the code used for the problem

```<code><span class="dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport"
             data-dojo-attach-point="iconNode"></span>
</code>```

答:
Please add some more information from your HTML i just add some text and xpaths are like that

```<code><span class="dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport"
             data-dojo-attach-point="iconNode">test</span>
</code>```

Xpaths are:

```<code>//span[@class='dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport']
</code>```

or

```<code>//span[@data-dojo-attach-point='iconNode']
</code>```

or

```<code>//span[@data-dojo-attach-point='iconNode' and @class='dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport']
</code>```

Add some more informaton if you have any concern

Body:
Please add some more information from your HTML i just add some text and xpaths are like that

<span class="dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport"
             data-dojo-attach-point="iconNode">test</span>

Xpaths are:

//span[@class='dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport']

or

//span[@data-dojo-attach-point='iconNode']

or

//span[@data-dojo-attach-point='iconNode' and @class='dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport']

Add some more informaton if you have any concern


问:
Use alternative font for specific character
We're currently using the following font rule:

```<code>body {
    font-family: Meiryo, Verdana, sans-serif;
}
</code>```

This works nicely. There's only one problem: since Meiryo is a Japanese font, the code point for \ is ¥. This causes problems with emoticons like ¥o/ or ¯¥_(ツ)_/¯.

I'm wanting to experiment with @font-face and unicode-range to use Verdana's \ even when Meiryo is active.

I've tried various combinations of the following:

```<code>@font-face {
  font-family: Meiryo;
  src: local(Meiryo);
}
@font-face {
  font-family: Meiryo;
  src: local(Verdana);
  unicode-range: U+5C;
}
</code>```

I... honestly don't know what it's doing sometimes. It looks like it's still using Meiryo, but bolded text is all wrong and the baseline has changed, which in turn affects line heights and the overall layout of the page in a chain-reaction kind of way.

I almost feel like I'd be better off doing a server-side "replace \ with \" kind of thing...

Are any of my attempts reasonable or are there other things I should try?

Here's a "workaround" I've come up with:

(function fixBackslashes() {
    var walker = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false),
        node, offset, span;
    while( node = walker.nextNode()) {
        if( node.parentNode.className == 'bs') continue;
        if( (offset = node.nodeValue.indexOf('\\')) > -1) {
            node = node.splitText(offset);
            node.splitText(1);
            span = document.createElement('span');
            span.className = 'bs';
            span.style.cssText = // TODO: Move this to stylesheet
                "display:inline-block;" +
                "text-decoration:inherit;" +
                "transform:scaleX(-1);";
            node.parentNode.replaceChild(span,node);
            span.appendChild(document.createTextNode("/"));
        }
    }
})();
```

Basically, replace backslashes in text nodes with a forward slash mirrored horizontally. It works, for some definition of the word "works".

答:
```<code>@font-face {
  font-family: Meiryo;
  src: local(Meiryo);
  unicode-range: U+0-5B, U+5D-10FFFF; /*exclude U+5C (the backlash)*/
}
body {
  font-family: Meiryo, Verdana, sans-serif;
}
</code>```

Since meiryo is now missing glyph for the backlash char, engine tries to render '\' by next fallback fonts, verdana.

Body:
We're currently using the following font rule:

body {
    font-family: Meiryo, Verdana, sans-serif;
}

This works nicely. There's only one problem: since Meiryo is a Japanese font, the code point for \ is ¥. This causes problems with emoticons like ¥o/ or ¯¥_(ツ)_/¯.

I'm wanting to experiment with @font-face and unicode-range to use Verdana's \ even when Meiryo is active.

I've tried various combinations of the following:

@font-face {
  font-family: Meiryo;
  src: local(Meiryo);
}
@font-face {
  font-family: Meiryo;
  src: local(Verdana);
  unicode-range: U+5C;
}

I... honestly don't know what it's doing sometimes. It looks like it's still using Meiryo, but bolded text is all wrong and the baseline has changed, which in turn affects line heights and the overall layout of the page in a chain-reaction kind of way.

I almost feel like I'd be better off doing a server-side "replace \ with \" kind of thing...

Are any of my attempts reasonable or are there other things I should try?

Here's a "workaround" I've come up with:

(function fixBackslashes() {
    var walker = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false),
        node, offset, span;
    while( node = walker.nextNode()) {
        if( node.parentNode.className == 'bs') continue;
        if( (offset = node.nodeValue.indexOf('\\')) > -1) {
            node = node.splitText(offset);
            node.splitText(1);
            span = document.createElement('span');
            span.className = 'bs';
            span.style.cssText = // TODO: Move this to stylesheet
                "display:inline-block;" +
                "text-decoration:inherit;" +
                "transform:scaleX(-1);";
            node.parentNode.replaceChild(span,node);
            span.appendChild(document.createTextNode("/"));
        }
    }
})();

Basically, replace backslashes in text nodes with a forward slash mirrored horizontally. It works, for some definition of the word "works".

Body:
@font-face {
  font-family: Meiryo;
  src: local(Meiryo);
  unicode-range: U+0-5B, U+5D-10FFFF; /*exclude U+5C (the backlash)*/
}
body {
  font-family: Meiryo, Verdana, sans-serif;
}

Since meiryo is now missing glyph for the backlash char, engine tries to render '\' by next fallback fonts, verdana.


问:
three.js OrthographicTrackballControls with Angular
Is it possible to use the OrthographicTrackballControls of three.js with Angular 4? I tried with:

```<code>npm install --save three-orthographic-trackball-controls
</code>```

And in my component:

```<code>import { OrthographicTrackballControls } from 'three-orthographic-trackball-controls';
</code>```

I had no success and no idea on how to do this. I found solutions for OrbitControls, but using another npm package and RequireJS. Any ideas to solve this issue will be helpful. Thanks in advance.

答:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. One of solution/workaround could be:

Firstly, include dependencies:

```<code>three
@types/three
</code>```

Secondly, import in component:

```<code>import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";
</code>```

Replace OrbitControls to OrthographicTrackballControls in scene.component.ts. Most probably Camera characteristics should be adjusted as well.

```<code>this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);
</code>```

Hope this could help you to start. Also it shows an alternative solution (directly accessing original examples from three.js module without installation of additional NPM packages).

Body:
Is it possible to use the OrthographicTrackballControls of three.js with Angular 4? I tried with:

npm install --save three-orthographic-trackball-controls

And in my component:

import { OrthographicTrackballControls } from 'three-orthographic-trackball-controls';

I had no success and no idea on how to do this. I found solutions for OrbitControls, but using another npm package and RequireJS. Any ideas to solve this issue will be helpful. Thanks in advance.

Body:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. One of solution/workaround could be:

Firstly, include dependencies:

three
@types/three

Secondly, import in component:

import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";

Replace OrbitControls to OrthographicTrackballControls in scene.component.ts. Most probably Camera characteristics should be adjusted as well.

this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);

Hope this could help you to start. Also it shows an alternative solution (directly accessing original examples from three.js module without installation of additional NPM packages).


答:
All you need is offset 1, but offset cannot be used without limit. So, I'd suggest something like:

```<code>SELECT * FROM table ORDER BY id DESC LIMIT 99999999 OFFSET 1
</code>```

Warning: make sure your table doesn't contain lots of records, otherwise you will run into performance issues. Or, change the limit to something reasonable, like 10.

EDIT:

Read: How to use offset without limit

Title: Mysql select rows except first row

Body:
All you need is offset 1, but offset cannot be used without limit. So, I'd suggest something like:

SELECT * FROM table ORDER BY id DESC LIMIT 99999999 OFFSET 1

Warning: make sure your table doesn't contain lots of records, otherwise you will run into performance issues. Or, change the limit to something reasonable, like 10.

EDIT:

Read: How to use offset without limit


问:
JSON parse on a JSON string throws "Cannot convert object to primitive value"
server.js

uses the body parser middleware, handlebars and express

route

```<code>module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};
</code>```

client

```<code>function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

```<code>     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5
</code>```

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).

答:
Since you are using body-parser middleware then you dont have to parse req.body again cause it already parsed by body-parser

Example

if you used
app.use(bodyParser.json())

then you just have to do this

```<code>module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = req.body; // this is already parsed and is an object
        res.send({});
    });
};
</code>```

as pointed out by @T.J. Crowder you should also send the correct contentType so body-parser knows its json

```<code>function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        contentType: 'application/json',
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

Body:
server.js

uses the body parser middleware, handlebars and express

route

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};

client

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).

Body:
Since you are using body-parser middleware then you dont have to parse req.body again cause it already parsed by body-parser

Example

if you used
app.use(bodyParser.json())

then you just have to do this

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = req.body; // this is already parsed and is an object
        res.send({});
    });
};

as pointed out by @T.J. Crowder you should also send the correct contentType so body-parser knows its json

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        contentType: 'application/json',
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}


答:
```<code>SELECT *
  FROM table
  WHERE id NOT IN ( SELECT id
                      FROM table
                      ORDER BY id DESC
                      LIMIT 1 )
ORDER BY id DESC;
</code>```

You can try this.

In this case I am selecting all the rows, except the one with the biggest id.

In the example of [1,2,3,4,5], it will be :

```<code>SELECT *
  FROM table
  WHERE id NOT IN ( 5 )
ORDER BY id DESC;
</code>```

Hope this helps!

Title: Mysql select rows except first row

Body:
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

SELECT * FROM table ORDER BY id DESC

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");

Body:
SELECT *
  FROM table
  WHERE id NOT IN ( SELECT id
                      FROM table
                      ORDER BY id DESC
                      LIMIT 1 )
ORDER BY id DESC;

You can try this.

In this case I am selecting all the rows, except the one with the biggest id.

In the example of [1,2,3,4,5], it will be :

SELECT *
  FROM table
  WHERE id NOT IN ( 5 )
ORDER BY id DESC;

Hope this helps!