问:
How to get setInterval to execute exactly every n milliseconds?
I am trying to get a piece of code to execute exactly every second. I am finding, however, that there is a >1000ms time difference between each run of the setInterval.

```<code>var incrementUnitCount = function() {

    var now = new Date();

    console.log('Shift' + now + 'ms' + now.getMilliseconds());

};

setInterval(incrementUnitCount2, interval);
</code>```

The output looks like this:

```<code>js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:05 GMT-0400 (EDT)ms457
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:06 GMT-0400 (EDT)ms458
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:07 GMT-0400 (EDT)ms460
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:08 GMT-0400 (EDT)ms463
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:09 GMT-0400 (EDT)ms465
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:10 GMT-0400 (EDT)ms468
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:11 GMT-0400 (EDT)ms468
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:12 GMT-0400 (EDT)ms470
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:13 GMT-0400 (EDT)ms472
</code>```

As shown, the difference in time between each call is 1001ms, not 1000. If I have a time-sensitive application, how can I guarantee a call every 1000 ms - something like this:

```<code>js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:12 GMT-0400 (EDT)ms470
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:13 GMT-0400 (EDT)ms470
</code>```

Thanks!

答:
You can't, but you may be able to make a more accurate (not exact) replacement setInterval using requestAnimationFrame.  From https://gist.github.com/joelambert/1002116</p>

```<code>window.requestInterval = function(fn, delay) {
    if( !window.requestAnimationFrame       &&
        !window.webkitRequestAnimationFrame &&
        !(window.mozRequestAnimationFrame && window.mozCancelRequestAnimationFrame) && // Firefox 5 ships without cancel support
        !window.oRequestAnimationFrame      &&
        !window.msRequestAnimationFrame)
            return window.setInterval(fn, delay);

    var start = new Date().getTime(),
        handle = new Object();

    function loop() {
        var current = new Date().getTime(),
            delta = current - start;

        if(delta >= delay) {
            fn.call();
            start = new Date().getTime();
        }

        handle.value = requestAnimFrame(loop);
    };

    handle.value = requestAnimFrame(loop);
    return handle;
}
</code>```

Body:
I am trying to get a piece of code to execute exactly every second. I am finding, however, that there is a >1000ms time difference between each run of the setInterval.

var incrementUnitCount = function() {

    var now = new Date();

    console.log('Shift' + now + 'ms' + now.getMilliseconds());

};

setInterval(incrementUnitCount2, interval);

The output looks like this:

js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:05 GMT-0400 (EDT)ms457
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:06 GMT-0400 (EDT)ms458
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:07 GMT-0400 (EDT)ms460
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:08 GMT-0400 (EDT)ms463
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:09 GMT-0400 (EDT)ms465
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:10 GMT-0400 (EDT)ms468
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:11 GMT-0400 (EDT)ms468
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:12 GMT-0400 (EDT)ms470
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:13 GMT-0400 (EDT)ms472

As shown, the difference in time between each call is 1001ms, not 1000. If I have a time-sensitive application, how can I guarantee a call every 1000 ms - something like this:

js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:12 GMT-0400 (EDT)ms470
js/schedule.js (148) :ShiftTue Mar 28 2017 21:44:13 GMT-0400 (EDT)ms470

Thanks!

Body:
You can't, but you may be able to make a more accurate (not exact) replacement setInterval using requestAnimationFrame.  From https://gist.github.com/joelambert/1002116

window.requestInterval = function(fn, delay) {
    if( !window.requestAnimationFrame       &&
        !window.webkitRequestAnimationFrame &&
        !(window.mozRequestAnimationFrame && window.mozCancelRequestAnimationFrame) && // Firefox 5 ships without cancel support
        !window.oRequestAnimationFrame      &&
        !window.msRequestAnimationFrame)
            return window.setInterval(fn, delay);

    var start = new Date().getTime(),
        handle = new Object();

    function loop() {
        var current = new Date().getTime(),
            delta = current - start;

        if(delta >= delay) {
            fn.call();
            start = new Date().getTime();
        }

        handle.value = requestAnimFrame(loop);
    };

    handle.value = requestAnimFrame(loop);
    return handle;
}


来源: stackexchange

问:
Ionic serve not working with ionic2
I have started a clean project with ionic2 based on tabs template, by following the next steps:

```<code>$ ionic start <myapp> --v2
$ cd <myapp>
$ ionic serve
</code>```

Then the output from ionic serve is just:

```<code>> ionic-hello-world@ ionic:serve /home/luan/<myapp>
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
</code>```

If I try to open localhost:8100 there's no response.

The files and code of the project are just the same as one using tabs template, but it's just don't wonking.
Could someone help?

UPDATE:
My ionic info

```<code>My system information:
Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed
</code>```

答:
I have found the answer. It turns out, the 1.2.2 version of Ionic App Scripts (app-scripts) version was the problem. Just downgraded to 1.1.4 and works fine. The actual workaround:

in package.json, change

```<code>"@ionic/app-scripts": "1.2.2"
</code>```

to

```<code>"@ionic/app-scripts": "1.1.4"
</code>```

then run npm install again. It should show something like this:

```<code>[...]
- sentence-case@2.1.1 node_modules/sentence-case
- change-case@3.0.1 node_modules/change-case
ionic-hello-world@ /home/luan/Projetos/prestacontas
└── @ionic/app-scripts@1.1.4 ## The problem was here
</code>```

Make shure that @ionic/app-scripts is now 1.1.4, and not 1.2.2.

And that's it.

ContentLicense: CC BY-SA 3.0

Title: Ionic serve not working with ionic2

Body:
I have started a clean project with ionic2 based on tabs template, by following the next steps:

$ ionic start <myapp> --v2
$ cd <myapp>
$ ionic serve

Then the output from ionic serve is just:

> ionic-hello-world@ ionic:serve /home/luan/<myapp>
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"

If I try to open localhost:8100 there's no response.

The files and code of the project are just the same as one using tabs template, but it's just don't wonking.
Could someone help?

UPDATE:
My ionic info

My system information:
Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed

Body:
I have found the answer. It turns out, the 1.2.2 version of Ionic App Scripts (app-scripts) version was the problem. Just downgraded to 1.1.4 and works fine. The actual workaround:

in package.json, change

"@ionic/app-scripts": "1.2.2"

to

"@ionic/app-scripts": "1.1.4"

then run npm install again. It should show something like this:

[...]
- sentence-case@2.1.1 node_modules/sentence-case
- change-case@3.0.1 node_modules/change-case
ionic-hello-world@ /home/luan/Projetos/prestacontas
└── @ionic/app-scripts@1.1.4 ## The problem was here

Make shure that @ionic/app-scripts is now 1.1.4, and not 1.2.2.

And that's it.


答:
I am trying to overwrite the function vtable:

There is no such thing. Perhaps you mean class vtable?

Will just b *0xb7993170 work?

No. b *0xb7993170 will only work IF 0xb7993170 contains executable code. If it actually contains a vtable (i.e. a pointer to code), you'll want:

```<code>awatch *(int**)0xb7993170
</code>```

Or you can just continue the binary and let it crash when it tries to dereference 0x42424242.

P.S. Given that 0xb7993170 contained 0 before the memcpy, it was certainly not a function pointer (but could still be part of vtable).

You need to set a watch point on the actual pointer location (i.e. 0xb7993170 will not work, you need 0xb7993178 or something like that).

Title: GDB - see what have accessed the address/break on it

Body:
I am trying to overwrite the function vtable:

Here it is done:

Before memcpy

(gdb) x/100x 0xb7993150
0xb7993150:     0xb6eae130      0xb6eae130      0x41414141      0x41414141
0xb7993160:     0x41414141      0x41414141      0x41414141      0x41414141
0xb7993170:     0x00000000      0x00000000      0x00000030      0x00000023
0xb7993180:     0x6c707061      0x74616369      0x2f6e6f69      0x6574636f
0xb7993190:     0x74732d74      0x6d616572      0x00000000      0x0000001b
0xb79931a0:     0x00000001      0x00000001      0xb7993078      0x00000000
0xb79931b0:     0x00000000      0x0000002b      0xb6727688      0xb79931e0
0xb79931c0:     0x00000000      0xb6727678      0xb79931f8      0xb6727678
0xb79931d0:     0xb7993208      0x00000000      0x00000000      0x0000001b
0xb79931e0:     0x00000001      0x00000001      0xb79931b8      0x00000000
0xb79931f0:     0x66657463      0x00000013      0x00000000      0xb79932c8
0xb7993200:     0xb7993218      0x00000013      0x00000000      0xb79932d8
0xb7993210:     0xb79932d8      0x00000013      0xb666ee65      0xb79931f8
0xb7993220:     0xb7993228      0x00000013      0xb66b6971      0xb7993218
0xb7993230:     0xb7993238      0x00000013      0xb6693c11      0xb7993228
0xb7993240:     0xb7993248      0x00000013      0xb669ba79      0xb7993238

after memcpy

0xb7993150:     0x7d000000      0x67337874      0x41414141      0x41414141
0xb7993160:     0x41414141      0x41414141      0x41414141      0x41414141
0xb7993170:     0x99999999      0x42424242      0x42424242      0x42424242
0xb7993180:     0x42424242      0x42424242      0x42424242      0x42424242
0xb7993190:     0x42424242      0x42424242      0x42424242      0x42424242
0xb79931a0:     0x42424242      0x42424242      0x42424242      0x42424242
0xb79931b0:     0x42424242      0x42424242      0x42424242      0x46454443
0xb79931c0:     0x4a494847      0x0000204b      0xe8919cb3      0xb67276b6
0xb79931d0:     0xb7993208      0x00000000      0x00000000      0x0000001b
0xb79931e0:     0x00000001      0x00000001      0xb79931b8      0x00000000
0xb79931f0:     0x66657463      0x00000013      0x00000000      0xb79932c8
0xb7993200:     0xb7993218      0x00000013      0x00000000      0xb79932d8
0xb7993210:     0xb79932d8      0x00000013      0xb666ee65      0xb79931f8
0xb7993220:     0xb7993228      0x00000013      0xb66b6971      0xb7993218
0xb7993230:     0xb7993238      0x00000013      0xb6693c11      0xb7993228
0xb7993240:     0xb7993248      0x00000013      0xb669ba79      0xb7993238
0xb7993250:     0xb7993258      0x00000013      0xb666990d      0xb7993248
0xb7993260:     0xb7993268      0x00000013      0xb665ad61      0xb7993258
0xb7993270:     0xb7993278      0x00000013      0xb66c83b5      0xb7993268
0xb7993280:     0xb7993288      0x00000013      0xb666adad      0xb7993278

How Can I stop/make breakpoint when 0x99999999 is accessed/read as a vtable pointer?

Will just

b *0xb7993170

work?

Body:
I am trying to overwrite the function vtable:

There is no such thing. Perhaps you mean class vtable?

Will just b *0xb7993170 work?

No. b *0xb7993170 will only work IF 0xb7993170 contains executable code. If it actually contains a vtable (i.e. a pointer to code), you'll want:

awatch *(int**)0xb7993170

Or you can just continue the binary and let it crash when it tries to dereference 0x42424242.

P.S. Given that 0xb7993170 contained 0 before the memcpy, it was certainly not a function pointer (but could still be part of vtable).

You need to set a watch point on the actual pointer location (i.e. 0xb7993170 will not work, you need 0xb7993178 or something like that).


问:
Conditionally excluding cmdlet arguments that are null or empty
I've written a script that calls the New-Service cmdlet to create a Windows service:

```<code>New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description $Description -StartupType $StartupType
</code>```

I have a problem with the Description.  If $Description is an empty string or $null I get an error:

```<code>Cannot validate argument on parameter 'Description'.
The argument is null or empty. Provide an argument that is not null or empty,
and then try the command again.
</code>```

If I leave out the -Description parameter entirely the command runs without error:

```<code>New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -StartupType $StartupType
</code>```

I can work around this problem via:

```<code>if ($Description)
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -Description $Description -StartupType $StartupType
}
else
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -StartupType $StartupType
}
</code>```

However, this seems verbose and clunky.  Is there any way of telling a Powershell cmdlet to ignore an argument that is null or empty when calling the cmdlet?

Something along the lines of:

```<code>New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType
</code>```

答:
Parameter splatting, documented in the conceptual about_Splatting help topic,[1] is the best approach in such cases:

```<code># Create a hashtable with all parameters known to have values.
# Note that the keys are the parameter names without the "-" prefix.
$htParams = @{
  Name = $Name
  BinaryPathName = $ExecutablePath
  Credential = $Credential
  DisplayName = $DisplayName
  StartupType = $StartupType
}

# Only add a -Description argument if it is nonempty.
if ($Description) { $htParams.Description = $Description }

# Use the splatting operator, @, to pass the parameters hashtable.
New-Service @htParams
</code>```

[1] chribonn also recommends this blog post for an introduction to splatting.

Body:
I've written a script that calls the New-Service cmdlet to create a Windows service:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description $Description -StartupType $StartupType

I have a problem with the Description.  If $Description is an empty string or $null I get an error:

Cannot validate argument on parameter 'Description'.
The argument is null or empty. Provide an argument that is not null or empty,
and then try the command again.

If I leave out the -Description parameter entirely the command runs without error:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -StartupType $StartupType

I can work around this problem via:

if ($Description)
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -Description $Description -StartupType $StartupType
}
else
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -StartupType $StartupType
}

However, this seems verbose and clunky.  Is there any way of telling a Powershell cmdlet to ignore an argument that is null or empty when calling the cmdlet?

Something along the lines of:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType

Body:
Parameter splatting, documented in the conceptual about_Splatting help topic,[1] is the best approach in such cases:

# Create a hashtable with all parameters known to have values.
# Note that the keys are the parameter names without the "-" prefix.
$htParams = @{
  Name = $Name
  BinaryPathName = $ExecutablePath
  Credential = $Credential
  DisplayName = $DisplayName
  StartupType = $StartupType
}

# Only add a -Description argument if it is nonempty.
if ($Description) { $htParams.Description = $Description }

# Use the splatting operator, @, to pass the parameters hashtable.
New-Service @htParams

[1] chribonn also recommends this blog post for an introduction to splatting.

ContentLicense: CC BY-SA 4.0


问:
How do you make multiple radio buttons over an image responsive?
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

```<code>#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;
</code>```

HTML:

```<code><img src="map.png">
<label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
<label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
<label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
<label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
<label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
<label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
<label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
<label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</code>```

答:
From the snippet you are positioning the radio buttons absolute to the body element.

Since image tag is inline and cannot hold html child elements, simply place the radio buttons in a div (parent) and add a background image to your div. Then you will notice how the radio button are positioned absolute to the parent (div container)

#container{
  position:relative;
  background-image:url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRiWmnVBwnR9ddbHOGmGaoA3gTrU5r3pslI-IybKWIJz4Amy6VA);
  background-size:cover;
  width:200px;
  height:200px;
}
#radio1{
position:absolute;
top:58.9%;
left:24.4%;
}

#radio2{
position:absolute;
top:57.5%;
left:27.1%;
}

#radio3{
 position:absolute;
top:63.2%;
left:34.05%;
}

#radio4{
position:absolute;
top:66.8%;
left:38%;
}

#radio5{
position:absolute;
top:68.9%;
left:40.4%;
}

#radio6{
position:absolute;
top:69.7%;
left:38.8%;
}

#radio7{
position:absolute;
top:73.1%;
left:40.5%;
}

#radio8{
position:absolute;
top:78.8%;
left:45.5%;
}

#third.form img{
display:block;
max-width: 100%;
height: auto;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
  <label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
  <label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
  <label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
  <label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
  <label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
  <label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
  <label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</div></code>```

Body:
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;

HTML:

<input type="radio" name="radio" id="radio1" required>

<input type="radio" name="radio" id="radio2">

<input type="radio" name="radio" id="radio3">

<input type="radio" name="radio" id="radio4">

<input type="radio" name="radio" id="radio5">

<input type="radio" name="radio" id="radio6">

<input type="radio" name="radio" id="radio7">

<input type="radio" name="radio" id="radio8">

Body:
From the snippet you are positioning the radio buttons absolute to the body element.

Since image tag is inline and cannot hold html child elements, simply place the radio buttons in a div (parent) and add a background image to your div. Then you will notice how the radio button are positioned absolute to the parent (div container)

#container{
  position:relative;
  background-image:url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRiWmnVBwnR9ddbHOGmGaoA3gTrU5r3pslI-IybKWIJz4Amy6VA);
  background-size:cover;
  width:200px;
  height:200px;
}
#radio1{
position:absolute;
top:58.9%;
left:24.4%;
}

#radio2{
position:absolute;
top:57.5%;
left:27.1%;
}

#radio3{
 position:absolute;
top:63.2%;
left:34.05%;
}

#radio4{
position:absolute;
top:66.8%;
left:38%;
}

#radio5{
position:absolute;
top:68.9%;
left:40.4%;
}

#radio6{
position:absolute;
top:69.7%;
left:38.8%;
}

#radio7{
position:absolute;
top:73.1%;
left:40.5%;
}

#radio8{
position:absolute;
top:78.8%;
left:45.5%;
}

#third.form img{
display:block;
max-width: 100%;
height: auto;

<div id="container">
  <label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
  <label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
  <label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
  <label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
  <label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
  <label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
  <label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
  <label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</div>


问:
Button with 3 states using React
I've got a need for a button with 3 states.

Each state, would need to handle click and send a value.

The use-case is:

Non-favourite

Favourite

Uber-favourite

I tried using this.state.count + 1 to indicated the levels, but had no success. I am unsure this is the best way either.

I am using the const fill as the CSS value (colour) I will pass into the svg element.

Here is my attempt, but it is limited as checked only has 2 states (on/off) and I need 3. It is also in this codepen.

```<code>class Switch extends React.Component {
  constructor ( props ) {
    super( props );
    this.state = {
      checked: !!props.checked
    };
  }
  handleClick(e) {
        this.setState({
      checked: !this.state.checked
    });
  }

  render () {
    const fill = this.state.checked ? "#E1E0DD" : "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

const App = () => (
    <div>
        <Switch checked={ true } />
    </div>
)

React.render( <App />, document.getElementById( "page" ) );
</code>```

答:
I forked your codepen

A boolean value is 1 or 0. If you want 3 states you need to increment a value.

```<code>  handleClick(e) {
    var count = this.state.count;
    count = count !== 3 ? count + 1 : 0;
    this.setState({
      count: count
    });
  }
</code>```

You should also separate your logic for the fill color:

```<code>function fillColor(count) {
    var fill = "";
    if(count === 1) fill = "#E1E0DD";
    if(count === 2) fill = "#999999";
    if(count === 3) fill = "#000";
    return fill;
}
</code>```

Title: Button with 3 states using React

Body:
I've got a need for a button with 3 states.

Each state, would need to handle click and send a value.

The use-case is:

Non-favourite

Favourite

Uber-favourite

I tried using this.state.count + 1 to indicated the levels, but had no success. I am unsure this is the best way either.

I am using the const fill as the CSS value (colour) I will pass into the svg element.

Here is my attempt, but it is limited as checked only has 2 states (on/off) and I need 3. It is also in this codepen.

class Switch extends React.Component {
  constructor ( props ) {
    super( props );
    this.state = {
      checked: !!props.checked
    };
  }
  handleClick(e) {
        this.setState({
      checked: !this.state.checked
    });
  }

  render () {
    const fill = this.state.checked ? "#E1E0DD" : "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

const App = () => (

        <Switch checked={ true } />

)

React.render( <App />, document.getElementById( "page" ) );

Body:
I forked your codepen

A boolean value is 1 or 0. If you want 3 states you need to increment a value.

  handleClick(e) {
    var count = this.state.count;
    count = count !== 3 ? count + 1 : 0;
    this.setState({
      count: count
    });
  }

You should also separate your logic for the fill color:

function fillColor(count) {
    var fill = "";
    if(count === 1) fill = "#E1E0DD";
    if(count === 2) fill = "#999999";
    if(count === 3) fill = "#000";
    return fill;
}


问:
open external link without interrupting meta auto refresh
I have a very basic teamspeak viewer site that shows who is currently on.

I am using this auto refresh tag:

```<code><meta http-equiv="refresh" content="60;url=index.html">
</code>```

I have a button that connects to the Teamspeak server that is clicked on:

```<code><a href="ts3server://server.address?port=9999" class="ui-btn ui-corner-all ui-shadow">Connect To This TeamSpeak</a>
</code>```

All work great, except for when I click the button that opens the windows application, the internet page stop refreshing every 60 seconds.

I am very new to all this, any help would greatly be appreciated!

答:
Okay, I figured it out. I removed the html meta:

```<code><meta http-equiv="refresh" content="60;url=index.html">
</code>```

and modified a Javascript code that I found from Philip M. 2010:

```<code><script type = "text/javascript">
/*author Philip M. 2010*/

var timeInSecs;
var ticker;

function startTimer(secs){
timeInSecs = parseInt(secs)-1;
ticker = setInterval("tick()",1000);   // every second
}

function tick() {
var secs = timeInSecs;
if (secs <5 ) {
document.getElementById("countdown").style.color = "red";  // and any other styling desired
}
if (secs>0) {
timeInSecs--;
}
else {
document.location.reload(true)
//clearInterval(ticker); // stop counting at zero
// startTimer(60);  // remove forward slashes in front of startTimer to repeat if required
}

document.getElementById("countdown").innerHTML = secs;
}

startTimer(60);  // 60 seconds

</script>

<span id="countdown" style="font-weight: bold;">60</span>
</code>```

The part I modified was:

```<code>else {
document.location.reload(true)
</code>```

Now if I click the button to launch the external windows app, the page will still refresh every 60 seconds.

Body:
I have a very basic teamspeak viewer site that shows who is currently on.

I am using this auto refresh tag:

<meta http-equiv="refresh" content="60;url=index.html">

I have a button that connects to the Teamspeak server that is clicked on:

Connect To This TeamSpeak

All work great, except for when I click the button that opens the windows application, the internet page stop refreshing every 60 seconds.

I am very new to all this, any help would greatly be appreciated!

Body:
Okay, I figured it out. I removed the html meta:

<meta http-equiv="refresh" content="60;url=index.html">

and modified a Javascript code that I found from Philip M. 2010:

<script type = "text/javascript">
/*author Philip M. 2010*/

var timeInSecs;
var ticker;

function startTimer(secs){
timeInSecs = parseInt(secs)-1;
ticker = setInterval("tick()",1000);   // every second
}

function tick() {
var secs = timeInSecs;
if (secs <5 ) {
document.getElementById("countdown").style.color = "red";  // and any other styling desired
}
if (secs>0) {
timeInSecs--;
}
else {
document.location.reload(true)
//clearInterval(ticker); // stop counting at zero
// startTimer(60);  // remove forward slashes in front of startTimer to repeat if required
}

document.getElementById("countdown").innerHTML = secs;
}

startTimer(60);  // 60 seconds

</script>

<span id="countdown" style="font-weight: bold;">60</span>

The part I modified was:

else {
document.location.reload(true)

Now if I click the button to launch the external windows app, the page will still refresh every 60 seconds.


问:
dynamically load formly typeahead options
I am using Angular Formly, and try to build a form with a Select field which allows to pick the state of a country.
The second field is a typeahead field, which allows to enter valid area names belonging to this state.
However, I am failing to dynamically change the typeahead options array.

I have taken the Typeahead type definition from the Formly Examples, and works fine with a static array of options:

```<code>formlyConfig.setType({
  name: 'typeahead',
  template: '<input type="text" ng-model="model[options.key]" ' +
        'uib-typeahead="item for item in to.options | filter:$viewValue | limitTo:8" ' +
        'class="form-control">',
  wrapper: ['bootstrapLabel', 'bootstrapHasError'],
});
</code>```

This is my form definition:

```<code>$scope.selectZoneFormFields = [

  {
    key: 'stateid',
    type: 'select',
    templateOptions:{
      label: Constants.DIVPOL,
      valueProp: 'id',
      labelProp: 'nombre',
      options: StatesManager.get()
    }
  },
  {
    key: 'zoneName',
    type: 'typeahead',
    templateOptions: {
      label: 'Zona',
      options: $scope.zoneNames
    }
  }
];
</code>```

Then, I watch changes in stateid and refresh $scope.zoneNames:

```<code>$scope.$watch('geo.stateid', function(newValue, oldValue) {
  if (newValue === undefined || newValue.length !== 2 || newValue === oldValue )
    return;
  console.log(' !!! STATE change detected: ' + oldValue + '-->' + newValue);
  refreshZones(newValue);
});
</code>```

The problem is that the options for the typeahead field remain those which are loaded at the beginning (initial value of $scope.zoneNames)

I have tried to use a controller inside formly field definition, but with no success.

Ideas?

答:
```<code>  {
    key: 'zoneName',
    type: 'typeahead',
    templateOptions: {
      label: 'Zona',
      options: []
    },
    expressionProperties: {
       'templateOptions.options': function($viewValue, $modelValue, $scope){
           $scope.to.options = []; //set to an empty array
           if($scope.model.stateid) { //if the state has been selected
             $scope.to.options = //whatever code you use to get the zones
             return $scope.to.options; //return the options
           }
        }
    }
  }
</code>```

Body:
I am using Angular Formly, and try to build a form with a Select field which allows to pick the state of a country.
The second field is a typeahead field, which allows to enter valid area names belonging to this state.
However, I am failing to dynamically change the typeahead options array.

I have taken the Typeahead type definition from the Formly Examples, and works fine with a static array of options:

formlyConfig.setType({
  name: 'typeahead',
  template: '<input type="text" ng-model="model[options.key]" ' +
        'uib-typeahead="item for item in to.options | filter:$viewValue | limitTo:8" ' +
        'class="form-control">',
  wrapper: ['bootstrapLabel', 'bootstrapHasError'],
});

This is my form definition:

$scope.selectZoneFormFields = [

  {
    key: 'stateid',
    type: 'select',
    templateOptions:{
      label: Constants.DIVPOL,
      valueProp: 'id',
      labelProp: 'nombre',
      options: StatesManager.get()
    }
  },
  {
    key: 'zoneName',
    type: 'typeahead',
    templateOptions: {
      label: 'Zona',
      options: $scope.zoneNames
    }
  }
];

Then, I watch changes in stateid and refresh $scope.zoneNames:

$scope.$watch('geo.stateid', function(newValue, oldValue) {
  if (newValue === undefined || newValue.length !== 2 || newValue === oldValue )
    return;
  console.log(' !!! STATE change detected: ' + oldValue + '-->' + newValue);
  refreshZones(newValue);
});

The problem is that the options for the typeahead field remain those which are loaded at the beginning (initial value of $scope.zoneNames)

I have tried to use a controller inside formly field definition, but with no success.

Ideas?


问:
Linking shared libraries with gcc on Linux
I need to compile and, most importantly, link a C program that uses a proprietary function present in a shared library file. Because of lack of communication with the previous development team, there is no proper documentation. I declared a function prototype (because I know the number and type of arguments):

```<code>int CustomFunction(unsigned char *in, int size);
</code>```

Since that function name can be grepped from /customlibs/libcustom.so, I tried to compile the code and link it like this:

```<code>gcc -L/customlibs testing.c -o testing -lcustom
</code>```

Which throws a few error messages looking like this:

```<code>/customlibs/libcustom.so: undefined reference to `AnotherCustomFunction'
</code>```

Obviously, I need to tell linker to include other libraries as well, and, to make things worse, they need to be in certain order. I tried exporting LD_LIBRARY_PATH, using -Wl,-rpath=, -Wl,--no-undefined and -Wl,--start-group. Is there an easy way to give the linker all the .so files without the proper order?

答:
Add them on the command line is a way to do it.  Something like this below.  The LD_LIBRARY_PATH tells gcc where to look for libraries, but you still need to say what libraries to include.

gcc -L/customlibs testing.c -o testing -lcustom -lmylib1 -lmylib2 -lmylib3

Body:
I need to compile and, most importantly, link a C program that uses a proprietary function present in a shared library file. Because of lack of communication with the previous development team, there is no proper documentation. I declared a function prototype (because I know the number and type of arguments):

int CustomFunction(unsigned char *in, int size);

Since that function name can be grepped from /customlibs/libcustom.so, I tried to compile the code and link it like this:

gcc -L/customlibs testing.c -o testing -lcustom

Which throws a few error messages looking like this:

/customlibs/libcustom.so: undefined reference to `AnotherCustomFunction'

Obviously, I need to tell linker to include other libraries as well, and, to make things worse, they need to be in certain order. I tried exporting LD_LIBRARY_PATH, using -Wl,-rpath=, -Wl,--no-undefined and -Wl,--start-group. Is there an easy way to give the linker all the .so files without the proper order?


问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答: In Visual Studio open the object explorer, choose .NET 4 Framework, search for IEnumerable<T> and expand the list of derived types. It's way too much to paste here :-).

ContentLicense: CC BY-SA 2.5


问:
Convert SQL Insert command to Xamarin SQLite database
I have a lengthy SQL INSERT command that I would essentially like to convert to a local Xamarin database, using SQLite. Is there any easy way around this or do I manually have to create an object from each value which is then entered into the local SQLite database?</p>

答:
If you want to pre-seed your database and ship it with the app, then as Jason suggested, you can use SQLite Manager.

If you want the mobile app to seed the database on first load, you will need to create the objects (tables) first and run the below for each table you have.

```<code>SQLiteConnection conn = ....
conn.CreateTable<TableClass>();
</code>```

Then if you just want to run the insert queries you have, you can use the Execute method.

```<code>public int Execute(string query, params object[] args)
</code>```

However SQLite isn't as powerful as MS SQL and if your insert queries are complex, you will have to modify them and possibly your DB Schema, depending upon column types.

Body:
If you want to pre-seed your database and ship it with the app, then as Jason suggested, you can use SQLite Manager.

If you want the mobile app to seed the database on first load, you will need to create the objects (tables) first and run the below for each table you have.

SQLiteConnection conn = ....
conn.CreateTable<TableClass>();

Then if you just want to run the insert queries you have, you can use the Execute method.

public int Execute(string query, params object[] args)

However SQLite isn't as powerful as MS SQL and if your insert queries are complex, you will have to modify them and possibly your DB Schema, depending upon column types.


问:
I am trying to call a variable from a different class so I can update the variable
I haven't asked many questions on here so sorry if I have laid this question out wrongly.

I am trying to call the variable AmountOfTickets in the main class. So I can update it with each loop of the while loop. I don't know how to properly call the variable without eclipse showing an error.

This is the class where I have created the variable AmountOfTickets which
I am trying to update

```<code>public class TicketHandler {
    public int TicketCost;
    public static int AmountOfTickets;

    public TicketHandler(int TicketCost, int AmountOfTickets){
        this.TicketCost = TicketCost;
        this.AmountOfTickets = AmountOfTickets;
    }

    public TicketHandler() {
        TicketCost = 200;
        AmountOfTickets = 50;
    }

    public int getTicketCost() {
        return TicketCost;
    }

    public void setTicketCost(int ticketCost) {
        TicketCost = ticketCost;
    }

    public static int getAmountOfTickets() {
        return AmountOfTickets;
    }

    public void setAmountOfTickets(int amountOfTickets) {
        AmountOfTickets = amountOfTickets;
    }

    public void ReduceNoOfTickets(int TicketsSold) {
        this.AmountOfTickets = this.AmountOfTickets - TicketsSold;
    }
}
</code>```

This is the main program code where I am trying to call the variable and used it

```<code>import java.util.Scanner;
public class ApplicationProgram {

    static Scanner inKey = new Scanner(System.in);

    public static void main(String[] args) {
        TicketHandler Red = new TicketHandler (200,50);
        TicketHandler Green = new TicketHandler (200,50);
        TicketHandler Blue = new TicketHandler (200,50);
        TicketHandler Yellow = new TicketHandler (200,50);

        boolean running = true;

        //Main menu
        while (running) {
            printMenu();
            int KeyIn = inKey.nextInt();

            //menu
            switch (KeyIn) {
                case 1:{
                    RedRoute();
                    break;
                }
                case 2:{
                    GreenRoute();
                    break;
                }

                case 3:{
                    BlueRoute();
                    break;
                }
                case 4:{
                    YellowRoute();
                    break;
                }

                case 5:{
                    ShowAvailableTicketsAndPrice();
                    break;
                }

                case 6:{
                    System.out.println("Do you wish to quit: type Y to confirm");
                    String quitYN = inKey.next ();
                    //System.out.println(quitYN);
                    if ((quitYN.matches("Y")) || (quitYN.matches("y"))) {
                        System.out.println("Goodbye\n\n");
                        running = false;
                        System.exit(0);

                    }
                    break;
                }
                default:{
                    System.out.println("Not a valid option, try again.");
                    break;
                }
            }
        }
    }

    public static void printMenu(){
        System.out.println("Bus Tickets");
        System.out.println("---- ----");
        System.out.println("1. \tRedRoute");
        System.out.println("2. \tGreenRoute");
        System.out.println("3. \tBlueRoute");
        System.out.println("4. \tYellowRoute");
        System.out.println("5. \tShowAvailableTicketsAndPrice");
        System.out.println("6. \tQuit");
    }

    public static void RedRoute(){
        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200) {
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void GreenRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200){
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void BlueRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int moneyin = 200;
        while (moneyin <= 200){
            System.out.println("Insert £" + moneyin);
            int KeyIn = Red.nextInt();
            moneyin = moneyin - KeyIn;

            if (moneyin == 0){
                System.out.println("Enjoy");
                AmountOfTickets = get.AmountOfTickets - 1
                break;
            }
        }
    }

    public static void YellowRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200) {
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void ShowAvailableTicketsAndPrice(){
        System.out.println("Routes available:");
        System.out.println("\tRed route, Tickets left: "+  "Price: ");
        System.out.println("\tBlue route, Tickets left: " + "Price: ");
        System.out.println("\tGreen route, Tickets left: " + "Price: ");
        System.out.println("\tYellow route, Tickets left: " + "Price: ");
    }
}
</code>```

Thank you.

答:
First of all, your var called AmountOfTickets is static, it means one copy will live to all objects, also your method getAmountOfTickets.

you have a problem here

```<code>            AmountOfTickets = get.AmountOfTickets - 1
</code>```

you must call the variable using the ClassName.YourVar like this:

```<code>            TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1;
</code>```

also your method.

Also you could import a static like this:

```<code>     import java.util.Scanner;

    import static huh.TicketHandler.*;
</code>```

so you can use:

```<code>            AmountOfTickets = getAmountOfTickets() - 1;
</code>```

"You could think in create an object and call the var like this"

public static void BlueRoute(){

```<code>    Scanner Red = new Scanner(System.in);
    TicketHandler objectOne = new TicketHandler(); //HERE I CREATED AN OBJECT
    System.out.println();
    int moneyin = 200;
    while (moneyin <= 200)
    {
        System.out.println("Insert £" + moneyin);
        int KeyIn = Red.nextInt();
        moneyin = moneyin - KeyIn;

        if (moneyin == 0){
            System.out.println("Enjoy");

            objectOne.AmountOfTickets = objectOne.getAmountOfTickets() - 1; //HERE I USED IT

            break;
    }
</code>```

But as this is static it will replace objectOne to

```<code>            TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1; //HERE I USED IT
</code>```

So, in my humble opinion you can or use an import static (so you avoid to write the same class name before your static), or put the name of your class first then the name and method.

Using an import static could be bad if there is another class with the same name or method as yours and you imported, because compiler could say, hey which one am I suppose to use?

So, I'd rather use fullnameClass.varOrMethod

hope it helps

btw using this: TicketHandler.AmountOfTickets  and this: TicketHandler.getAmountOfTickets() are avable to be used in all  ApplicationProgra's class code as i said because it is static, and because you difined them public

```<code> public static int AmountOfTickets;
   public static int getAmountOfTickets() {

        return AmountOfTickets;
    }
</code>```

=) i guess that was what you asked for. c-ya

Body:
I haven't asked many questions on here so sorry if I have laid this question out wrongly.

I am trying to call the variable AmountOfTickets in the main class. So I can update it with each loop of the while loop. I don't know how to properly call the variable without eclipse showing an error.

This is the class where I have created the variable AmountOfTickets which
I am trying to update

public class TicketHandler {
    public int TicketCost;
    public static int AmountOfTickets;

    public TicketHandler(int TicketCost, int AmountOfTickets){
        this.TicketCost = TicketCost;
        this.AmountOfTickets = AmountOfTickets;
    }

    public TicketHandler() {
        TicketCost = 200;
        AmountOfTickets = 50;
    }

    public int getTicketCost() {
        return TicketCost;
    }

    public void setTicketCost(int ticketCost) {
        TicketCost = ticketCost;
    }

    public static int getAmountOfTickets() {
        return AmountOfTickets;
    }

    public void setAmountOfTickets(int amountOfTickets) {
        AmountOfTickets = amountOfTickets;
    }

    public void ReduceNoOfTickets(int TicketsSold) {
        this.AmountOfTickets = this.AmountOfTickets - TicketsSold;
    }
}

This is the main program code where I am trying to call the variable and used it

import java.util.Scanner;
public class ApplicationProgram {

    static Scanner inKey = new Scanner(System.in);

    public static void main(String[] args) {
        TicketHandler Red = new TicketHandler (200,50);
        TicketHandler Green = new TicketHandler (200,50);
        TicketHandler Blue = new TicketHandler (200,50);
        TicketHandler Yellow = new TicketHandler (200,50);

        boolean running = true;

        //Main menu
        while (running) {
            printMenu();
            int KeyIn = inKey.nextInt();

            //menu
            switch (KeyIn) {
                case 1:{
                    RedRoute();
                    break;
                }
                case 2:{
                    GreenRoute();
                    break;
                }

                case 3:{
                    BlueRoute();
                    break;
                }
                case 4:{
                    YellowRoute();
                    break;
                }

                case 5:{
                    ShowAvailableTicketsAndPrice();
                    break;
                }

                case 6:{
                    System.out.println("Do you wish to quit: type Y to confirm");
                    String quitYN = inKey.next ();
                    //System.out.println(quitYN);
                    if ((quitYN.matches("Y")) || (quitYN.matches("y"))) {
                        System.out.println("Goodbye\n\n");
                        running = false;
                        System.exit(0);

                    }
                    break;
                }
                default:{
                    System.out.println("Not a valid option, try again.");
                    break;
                }
            }
        }
    }

    public static void printMenu(){
        System.out.println("Bus Tickets");
        System.out.println("---- ----");
        System.out.println("1. \tRedRoute");
        System.out.println("2. \tGreenRoute");
        System.out.println("3. \tBlueRoute");
        System.out.println("4. \tYellowRoute");
        System.out.println("5. \tShowAvailableTicketsAndPrice");
        System.out.println("6. \tQuit");
    }

    public static void RedRoute(){
        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200) {
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void GreenRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200){
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void BlueRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int moneyin = 200;
        while (moneyin <= 200){
            System.out.println("Insert £" + moneyin);
            int KeyIn = Red.nextInt();
            moneyin = moneyin - KeyIn;

            if (moneyin == 0){
                System.out.println("Enjoy");
                AmountOfTickets = get.AmountOfTickets - 1
                break;
            }
        }
    }

    public static void YellowRoute(){

        Scanner Red = new Scanner(System.in);
        System.out.println();
        int count = 200;
        while (count <= 200) {
            System.out.println("Insert £" + count);
            int KeyIn = Red.nextInt();
            count = count - KeyIn;

            if (count == 0){
                System.out.println("Enjoy");
                break;
            }
        }
    }

    public static void ShowAvailableTicketsAndPrice(){
        System.out.println("Routes available:");
        System.out.println("\tRed route, Tickets left: "+  "Price: ");
        System.out.println("\tBlue route, Tickets left: " + "Price: ");
        System.out.println("\tGreen route, Tickets left: " + "Price: ");
        System.out.println("\tYellow route, Tickets left: " + "Price: ");
    }
}

Thank you.

Body:
First of all, your var called AmountOfTickets is static, it means one copy will live to all objects, also your method getAmountOfTickets.

you have a problem here

            AmountOfTickets = get.AmountOfTickets - 1

you must call the variable using the ClassName.YourVar like this:

            TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1;

also your method.

Also you could import a static like this:

     import java.util.Scanner;

    import static huh.TicketHandler.*;

so you can use:

            AmountOfTickets = getAmountOfTickets() - 1;

"You could think in create an object and call the var like this"

public static void BlueRoute(){

    Scanner Red = new Scanner(System.in);
    TicketHandler objectOne = new TicketHandler(); //HERE I CREATED AN OBJECT
    System.out.println();
    int moneyin = 200;
    while (moneyin <= 200)
    {
        System.out.println("Insert £" + moneyin);
        int KeyIn = Red.nextInt();
        moneyin = moneyin - KeyIn;

        if (moneyin == 0){
            System.out.println("Enjoy");

            objectOne.AmountOfTickets = objectOne.getAmountOfTickets() - 1; //HERE I USED IT

            break;
    }

But as this is static it will replace objectOne to

            TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1; //HERE I USED IT

So, in my humble opinion you can or use an import static (so you avoid to write the same class name before your static), or put the name of your class first then the name and method.

Using an import static could be bad if there is another class with the same name or method as yours and you imported, because compiler could say, hey which one am I suppose to use?

So, I'd rather use fullnameClass.varOrMethod

hope it helps

btw using this: TicketHandler.AmountOfTickets  and this: TicketHandler.getAmountOfTickets() are avable to be used in all  ApplicationProgra's class code as i said because it is static, and because you difined them public

 public static int AmountOfTickets;
   public static int getAmountOfTickets() {

        return AmountOfTickets;
    }

=) i guess that was what you asked for. c-ya


问:
The following untracked working tree files would be overwritten by merge, but I don't care
On my branch I had some files in .gitignore

On a different branch those files are not.

I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not.

Unfortunately I get this:

The following untracked working tree files would be overwritten by merge

How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?

答:
In addition to the accepted answer you can of course remove the files if they are no longer needed by specifying the file:

```<code>git clean -f '/path/to/file/'
</code>```

Remember to run it with the -n flag first if you would like to see which files git clean will remove. Note that these files will be deleted. In my case I didn't care about them anyway, so that was a better solution for me.

Body:
In addition to the accepted answer you can of course remove the files if they are no longer needed by specifying the file:

git clean -f '/path/to/file/'

Remember to run it with the -n flag first if you would like to see which files git clean will remove. Note that these files will be deleted. In my case I didn't care about them anyway, so that was a better solution for me.


问:
r: pmatch isn't working for big dataframe
I have two dataframes, first one (dt) contains of all chr and second one (TargetWord) is a dictionary contains chr as well. I have used pmatch to search in dt which words are available in the TargetWord and returning the position from TargetWord. It is working fine when dataframes are small. But problem starts when the dataframes are huge, it is returning the word position for only the first column, rest of the columns are becoming NA.

```<code>## Data Table
word_1 <- c("conflict","", "resolved", "", "", "")
word_2 <- c("", "one", "tricky", "one", "", "one")
word_3 <- c("thanks","", "", "comments", "par","")
word_4 <- c("thanks","", "", "comments", "par","")
word_5 <- c("", "one", "tricky", "one", "", "one")
dt <- data.frame(word_1, word_2, word_3,word_4, word_5, stringsAsFactors = FALSE)

## Targeted Words
TargetWord <- data.frame(cbind(c("conflict", "thanks", "tricky", "one", "two", "three")))

## convert into matrix (needed)
dt <- as.matrix(dt)
TargetWord <- as.matrix(TargetWord)

result <- `dim<-`(pmatch(dt, TargetWord, duplicates.ok=TRUE), dim(dt))
print(result)
</code>```

Returning result,

```<code>     [,1] [,2] [,3] [,4] [,5]
[1,]    1   NA    2    2   NA
[2,]   NA    4   NA   NA    4
[3,]   NA    3   NA   NA    3
[4,]   NA    4   NA   NA    4
[5,]   NA   NA   NA   NA   NA
[6,]   NA    4   NA   NA    4
</code>```

Now after reading two .csv as bellow, result is just for the first column where I want it for all columns like above result. Bellow, dt1 = 79*50 dataframe, and word_dict 13901*1 dataframe.

```<code>#################### on big data #####################################
dt1 <- read.csv("C:/Users/Wonderland/Downloads/string_feature.csv", stringsAsFactors = FALSE)
word_dict <- read.csv("C:/Users/Wonderland/Downloads/word_dict.csv", stringsAsFactors = FALSE)

dt1 <- as.matrix(dt1)
word_dict <- as.matrix(word_dict)

result <- `dim<-`(pmatch(dt1, word_dict, duplicates.ok=TRUE), dim(dt1))
print(result)
</code>```

答:
Try with apply:

```<code>apply(dt,2,function(x) pmatch(x,TargetWord,duplicates.ok = T))
</code>```

As you can see, the result is the same but it probably works with huge dataframe

```<code>     word_1 word_2 word_3 word_4 word_5
[1,]      1     NA      2      2     NA
[2,]     NA      4     NA     NA      4
[3,]     NA      3     NA     NA      3
[4,]     NA     NA     NA     NA     NA
[5,]     NA     NA     NA     NA     NA
[6,]     NA     NA     NA     NA     NA
</code>```

I tried with:

```<code>word_1 <- rep(c("conflict","", "resolved", "", "", ""),1000)
word_2 <- rep(c("", "one", "tricky", "one", "", "one"),1000)
word_3 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_4 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_5 <- rep(c("", "one", "tricky", "one", "", "one"),1000)
</code>```

with all the same code and it worked.

Body:
I have two dataframes, first one (dt) contains of all chr and second one (TargetWord) is a dictionary contains chr as well. I have used pmatch to search in dt which words are available in the TargetWord and returning the position from TargetWord. It is working fine when dataframes are small. But problem starts when the dataframes are huge, it is returning the word position for only the first column, rest of the columns are becoming NA.

## Data Table
word_1 <- c("conflict","", "resolved", "", "", "")
word_2 <- c("", "one", "tricky", "one", "", "one")
word_3 <- c("thanks","", "", "comments", "par","")
word_4 <- c("thanks","", "", "comments", "par","")
word_5 <- c("", "one", "tricky", "one", "", "one")
dt <- data.frame(word_1, word_2, word_3,word_4, word_5, stringsAsFactors = FALSE)

## Targeted Words
TargetWord <- data.frame(cbind(c("conflict", "thanks", "tricky", "one", "two", "three")))

## convert into matrix (needed)
dt <- as.matrix(dt)
TargetWord <- as.matrix(TargetWord)

result <- `dim<-`(pmatch(dt, TargetWord, duplicates.ok=TRUE), dim(dt))
print(result)

Returning result,

     [,1] [,2] [,3] [,4] [,5]
[1,]    1   NA    2    2   NA
[2,]   NA    4   NA   NA    4
[3,]   NA    3   NA   NA    3
[4,]   NA    4   NA   NA    4
[5,]   NA   NA   NA   NA   NA
[6,]   NA    4   NA   NA    4

Now after reading two .csv as bellow, result is just for the first column where I want it for all columns like above result. Bellow, dt1 = 79*50 dataframe, and word_dict 13901*1 dataframe.

#################### on big data #####################################
dt1 <- read.csv("C:/Users/Wonderland/Downloads/string_feature.csv", stringsAsFactors = FALSE)
word_dict <- read.csv("C:/Users/Wonderland/Downloads/word_dict.csv", stringsAsFactors = FALSE)

dt1 <- as.matrix(dt1)
word_dict <- as.matrix(word_dict)

result <- `dim<-`(pmatch(dt1, word_dict, duplicates.ok=TRUE), dim(dt1))
print(result)

Body:
Try with apply:

apply(dt,2,function(x) pmatch(x,TargetWord,duplicates.ok = T))

As you can see, the result is the same but it probably works with huge dataframe

     word_1 word_2 word_3 word_4 word_5
[1,]      1     NA      2      2     NA
[2,]     NA      4     NA     NA      4
[3,]     NA      3     NA     NA      3
[4,]     NA     NA     NA     NA     NA
[5,]     NA     NA     NA     NA     NA
[6,]     NA     NA     NA     NA     NA

I tried with:

word_1 <- rep(c("conflict","", "resolved", "", "", ""),1000)
word_2 <- rep(c("", "one", "tricky", "one", "", "one"),1000)
word_3 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_4 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_5 <- rep(c("", "one", "tricky", "one", "", "one"),1000)

with all the same code and it worked.


问:
Logstash/Elasticsearch JDBC document_id vs document_type?
So im trying to wrap my head around the document_type vs document_id when using the JDBC importer from logstash and exporting to elasticsearch.

I finally wrapped my head around indexes. But lets pretend im pulling from a table of sensor data (like temp/humidity/etc...) that has sensor id's...temps/ humidity (weather related data) with time recorded. (So it's a big table)

And I want to keep polling the database every X so often.

What would document_type vs document_id be in this instance, this is going to be stored (or whatever you want to call it) against 1 index.

The document_type vs document_id confuses me, especially in regards to JDBC importer.

If I set document_id to say my primary key, won't it get over-written each time? So i'll just have 1 document of data each time? (which seems pointless)

答:
The jdbc plugin will create a JSON document with one field for each column. So to keep consistent with your example, if you had that data it would be imported as a document that looks like this:

```<code>{
    "sensor_id": 567,
    "temp": 90,
    "humidity": 6,
    "timestamp": "{time}",
    "@timestamp": "{time}" // auto-created field, the time Logstash received the document
}
</code>```

You were right when you said that if you set document_id to your primary key, it would get overwritten. You can disregard document_id unless you want to update existing documents in Elasticsearch, which I don't imagine you would want to do with this type of data. Let Elasticsearch generate the document id for you.

Now let's talk about document_type. If you want to set the document type, you need to set the type field in Logstash to some value (which will propagate into Elasticsearch). So the type field in Elasticsearch is used to group similar documents. If all of the documents in your table that you're importing with the jdbc plugin are of the same type (they should be!), you can set type in the jdbc input like this...

```<code>input {
  jdbc {
    jdbc_driver_library => "mysql-connector-java-5.1.36-bin.jar"
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    jdbc_connection_string => "jdbc:mysql://localhost:3306/mydb"
    jdbc_user => "mysql"
    parameters => { "favorite_artist" => "Beethoven" }
    schedule => "* * * * *"
    statement => "SELECT * from songs where artist = :favorite_artist"
    ...
    type => "weather"
  }
}
</code>```

Now, in Elasticsearch you can take advantage of the type field by setting a mapping for that type. For example you might want:

```<code>PUT my_index
{
  "mappings": {
    "weather": {
      "_all":       { "enabled": false  },
      "properties": {
        "sensor_id":      { "type": "integer"  },
        "temp":           { "type": "integer"  },
        "humidity":       { "type": "integer" },
        "timestamp":      { "type": "date" }
      }
    }
  }
}
</code>```

Hope this helps! :)

Body:
The jdbc plugin will create a JSON document with one field for each column. So to keep consistent with your example, if you had that data it would be imported as a document that looks like this:

{
    "sensor_id": 567,
    "temp": 90,
    "humidity": 6,
    "timestamp": "{time}",
    "@timestamp": "{time}" // auto-created field, the time Logstash received the document
}

You were right when you said that if you set document_id to your primary key, it would get overwritten. You can disregard document_id unless you want to update existing documents in Elasticsearch, which I don't imagine you would want to do with this type of data. Let Elasticsearch generate the document id for you.

Now let's talk about document_type. If you want to set the document type, you need to set the type field in Logstash to some value (which will propagate into Elasticsearch). So the type field in Elasticsearch is used to group similar documents. If all of the documents in your table that you're importing with the jdbc plugin are of the same type (they should be!), you can set type in the jdbc input like this...

input {
  jdbc {
    jdbc_driver_library => "mysql-connector-java-5.1.36-bin.jar"
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    jdbc_connection_string => "jdbc:mysql://localhost:3306/mydb"
    jdbc_user => "mysql"
    parameters => { "favorite_artist" => "Beethoven" }
    schedule => "* * * * *"
    statement => "SELECT * from songs where artist = :favorite_artist"
    ...
    type => "weather"
  }
}

Now, in Elasticsearch you can take advantage of the type field by setting a mapping for that type. For example you might want:

PUT my_index
{
  "mappings": {
    "weather": {
      "_all":       { "enabled": false  },
      "properties": {
        "sensor_id":      { "type": "integer"  },
        "temp":           { "type": "integer"  },
        "humidity":       { "type": "integer" },
        "timestamp":      { "type": "date" }
      }
    }
  }
}

Hope this helps! :)


问:
Uploading file to AWS from local machine

How to use scp command to upload file to aws server

I have .pem file in /Downloads in local machine

I am trying to copy file to /images folder in AWS server

What command can i use ?

Thanks,

答:
Another alternative way to scp is rsync.

Some of the benefits of rsync

faster - uploads only the deltas

enable compression

you can exclude some files from the upload

resume

limit the transfer bandwidth

The rsync cmd

```<code>rsync -ravze "ssh -i /home/your-user/your-key.pem "  --exclude '.env'  --exclude '.git/' /var/www/your-folder-to-upload/*  ubuntu@xx.xxx.xxx.xxx:/var/www/your-remote-folder
</code>```

Now, in case you find this syntax a little bit verbose you can use aws-upload which does all the above but you just tabbing.

Body:
Another alternative way to scp is rsync.

Some of the benefits of rsync

faster - uploads only the deltas

enable compression

you can exclude some files from the upload

resume

limit the transfer bandwidth

The rsync cmd

rsync -ravze "ssh -i /home/your-user/your-key.pem "  --exclude '.env'  --exclude '.git/' /var/www/your-folder-to-upload/*  ubuntu@xx.xxx.xxx.xxx:/var/www/your-remote-folder

Now, in case you find this syntax a little bit verbose you can use aws-upload which does all the above but you just tabbing.


问:
How do I package a website to be served by tomcat?
First, let me apologize, I'm new at web development, so I'm not quite sure how this works, but it's a simple proof of concept, so I don't think it needs to be too advanced.

I have a jar that accesses a server and pulls information that needs to be displayed for the user, I also have a local site that is set up to display this information to the user via html and javascript (but obviously doesn't connect to the server or that jar).  I plan on using tomcat to act as a middleware server that will display the web page and handle the code that accesses the server.

I've seen it done before, but I'm not quite sure how to set it up.  Can somebody just give me the basics on where things need to go to make this work?  I think I'd be ok after that.

My Google-Fu has failed me in finding this, so really any help is appreciated.

Thanks!

答: You need to create a WAR file and deploy it to tomcat. Take a look at this link.</p>


问:
matlab - line equation to 2D matrix with values of 1 and 0
As the title says, I want to covert a line(or any equation) to 2D matrix.

For example: If I have a line equation y = x, then I want it to be like:

```<code>0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0
</code>```

and the length of rows and columns can be variable.

Is there a function or method to implement that?

答: Why not doing it on your own? You loop through all x-coordinates of the matrix that you (probably scaled) use as the x for your function and get an y out, that you (probably scaled) can round and then use as a y coordinate for your matrix to set the 1. </p>

Body:
As the title says, I want to covert a line(or any equation) to 2D matrix.

For example: If I have a line equation y = x, then I want it to be like:

0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0

and the length of rows and columns can be variable.

Is there a function or method to implement that?


问:
Algorithm which adapt (solve) the complex equations ( implicit function f(x,y) )
I'm trying to adapt some equations (implicit f(x,y)) in order to be able list the Y for corresponding X-Value.

The equations could be e.g. as follows:

```<code>y^2 = x^3 + 2x - 3xy
(X^2+y^2-1)^3-x^2y^3=0
X^3+y^3=3xy^2-x-1
X^3+y^2=6xy/sqrt(y/x)
cos(PI*Y) = cos(PI.X)
</code>```

Below you can see the plotted equations:

Hint, I don't know, but maybe this can be helpful, the following applies:

```<code>Y^2 + X^2 =1  ==>  Y= sqrt(1-X^2)
</code>```

The equations are to be adapt (substitution), so that they are expressed by X (not Y).

 For y^2=x^3+2x-3xy by means of substitution results:

y1 = (-(-3x) - sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

y2 = (-(-3x) + sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

By means of adapted equations I will be able to vary X and get the corresponding Y.

See here the solution of Arkadiusz Raszeja-Solution for the equation y^2=x^3+2x-3xy

The solution of "Arkadiusz Raszeja" is for Quadratic equation, but I need an algorithm, so that e.g. all above equations can be solved.

```<code>var x,y;
for(var n=0; n<=10; n++) {
    x=n;
    y = (-(-3*x)-Math.sqrt(((-3*x)*(-3*x)) - 4*(-1)*((x*x*x)+2*x)))/(2*(-1));
    alert(y);
}
</code>```

The above alert(y); will show for Y something like below list:

```<code>X= 1 ; Y=0.79
X=2 ; Y=1.58
X=3 ; Y=2.79
X=4 ; Y=4.39
X=5 ; Y=6.33
X=6 ; Y=8.57
X=7 ; Y=11.12
X=8 ; Y=13.92
X=9 ; Y=16.98
X=10 ; Y= 20.29
</code>```

My question is how can I program an algorithm, which will adapt (solve) the equations like in above example?

(You can also use a JS library like math.js, but not a plot or graph library.  The solution should be in javascript)

Thanks in advance.

答:
Hopefully I'm understanding your question correctly. Would nerdamer help? It can help solve algebraically up to a 3rd degree polynomial. The buildFunction method can be called to get a JS function which can be used for graphing. I use it in a somewhat similar manner on the project website in combination with function-plot.js

var solutions = nerdamer('y^2=x^3+2x-3x*y').solveFor('y');
//You'll get back two solutions since it's quadratic wrt to y
console.log(solutions.toString());
//You can then parse the solutions to native javascript function
var f = nerdamer(solutions[0]).buildFunction();
console.log(f.toString());

/* Evaluate */
var solutions = nerdamer('y^3*x^2=(x^2+y^2-1)').solveFor('y');
console.log(solutions.toString());
//You can then parse the solutions again to native javascript function
var f = nerdamer(solutions[0]);
var points = {};
for(var i=1; i<10; i++)
    points[i] = f.evaluate({x: i}).text();

console.log(points)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<script src="http://nerdamer.com/js/Solve.js"></script></code>```

You could always just evaluate. This is slower than a pure JS function but it might be what you need. You'll have to probably use a try catch block for division by zero.

Body:
I'm trying to adapt some equations (implicit f(x,y)) in order to be able list the Y for corresponding X-Value.

The equations could be e.g. as follows:

y^2 = x^3 + 2x - 3xy
(X^2+y^2-1)^3-x^2y^3=0
X^3+y^3=3xy^2-x-1
X^3+y^2=6xy/sqrt(y/x)
cos(PI*Y) = cos(PI.X)

Below you can see the plotted equations:

Hint, I don't know, but maybe this can be helpful, the following applies:

Y^2 + X^2 =1  ==>  Y= sqrt(1-X^2)

The equations are to be adapt (substitution), so that they are expressed by X (not Y).

 For y^2=x^3+2x-3xy by means of substitution results:

y1 = (-(-3x) - sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

y2 = (-(-3x) + sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

By means of adapted equations I will be able to vary X and get the corresponding Y.

See here the solution of Arkadiusz Raszeja-Solution for the equation y^2=x^3+2x-3xy

The solution of "Arkadiusz Raszeja" is for Quadratic equation, but I need an algorithm, so that e.g. all above equations can be solved.

var x,y;
for(var n=0; n<=10; n++) {
    x=n;
    y = (-(-3*x)-Math.sqrt(((-3*x)*(-3*x)) - 4*(-1)*((x*x*x)+2*x)))/(2*(-1));
    alert(y);
}

The above alert(y); will show for Y something like below list:

X= 1 ; Y=0.79
X=2 ; Y=1.58
X=3 ; Y=2.79
X=4 ; Y=4.39
X=5 ; Y=6.33
X=6 ; Y=8.57
X=7 ; Y=11.12
X=8 ; Y=13.92
X=9 ; Y=16.98
X=10 ; Y= 20.29

My question is how can I program an algorithm, which will adapt (solve) the equations like in above example?

(You can also use a JS library like math.js, but not a plot or graph library.  The solution should be in javascript)

Thanks in advance.

Body:
Hopefully I'm understanding your question correctly. Would nerdamer help? It can help solve algebraically up to a 3rd degree polynomial. The buildFunction method can be called to get a JS function which can be used for graphing. I use it in a somewhat similar manner on the project website in combination with function-plot.js

var solutions = nerdamer('y^2=x^3+2x-3x*y').solveFor('y');
//You'll get back two solutions since it's quadratic wrt to y
console.log(solutions.toString());
//You can then parse the solutions to native javascript function
var f = nerdamer(solutions[0]).buildFunction();
console.log(f.toString());

/* Evaluate */
var solutions = nerdamer('y^3*x^2=(x^2+y^2-1)').solveFor('y');
console.log(solutions.toString());
//You can then parse the solutions again to native javascript function
var f = nerdamer(solutions[0]);
var points = {};
for(var i=1; i<10; i++)
    points[i] = f.evaluate({x: i}).text();

console.log(points)

<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<script src="http://nerdamer.com/js/Solve.js"></script>

You could always just evaluate. This is slower than a pure JS function but it might be what you need. You'll have to probably use a try catch block for division by zero.


问:
Creating the stereo photosphere without Unity
I'm working on a Daydream app using the Google VR SDK/NDK. To submit the app to Google Play, I need a 360-degree stereo photosphere. I've seen directions for creating this with Unity, but is there any way to create this without Unity?

I've taken a screenshot of the app in stereo mode, but I don't think that will satisfy the requirement.

答:
You could always cheat and make your "Daydream 360 degree stereoscopic image" in Photoshop. Just use the same image twice, once on top and once on the bottom.

I think others have already done this, because I have noticed a few wrong looking previews in the store. Where if I close one eye, parts of the image disappear.

If you change your mind and make one with Unity, this plugin worked nicely for me: https://www.assetstore.unity3d.com/en/#!/content/38755


问:
I'm trying to only get one row from a LEFT JOIN
Temp ordering table

```<code>temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time
58db09bba25b4   2                  2                     2       1490750973
58db09bba25b4   2                  4                     1      1490750973
</code>```

NEWS ITEMS TABLE

```<code>news_id   series_id      news_title
   26          2         GENERIC TICKETING
   27          2         GENERIC TICKETING
</code>```

When I do a left join on series_id I get back 4 rows and I only want 2. I'm not sure how to limit the amount of joined rows to one row.

CURRENT QUERY

```<code>SELECT
    *
FROM
    ticket_ordering_temp
LEFT JOIN
    news_items
on
    ( news_items.series_id = SELECT
                                DISTINCT(event_id)
                             FROM
                                news_items
                             where
                                series_id=ticket_ordering_temp.series_id
    )
where
    temp_id='58db09bba25b4''
</code>```

DESIRED RESULT
I want just 1 row from table 2 and not 2 rows joined as stated above

```<code>temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time news_title
58db09bba25b4   2                  2                     2       1490750973  GENERIC TICKETING
58db09bba25b4   2                  4                     1      1490750973 GENERIC TICKETING
</code>```

答:
try this Querying with tempTable:

```<code>select distinct * from
(select  * from
(select '58db09bba25b4' as temp_id,   2 as series_id,2 as news_ticket_breakdown_id,2 as quantity,1490750973 as  expiry_time  union all
select '58db09bba25b4' ,  2   ,              4  ,                  1,     1490750973) as tbl_order) as tbl_order

left join

(select series_id,news_title from
(select  26 as  news_id,         2 as series_id,         'GENERIC TICKETING' as news_title union all
select   27  ,        2 ,        'GENERIC TICKETING') as tbl_items) tbl_items
on tbl_order.series_id = tbl_items.series_id where temp_id ='58db09bba25b4'
</code>```

Querying With actual table:

```<code>select DISTINCT * from
(select temp_id,series_id,news_ticket_breakdown_id,quantity,expiry_time from tbl_order) as tb_order
left join
(select series_id,news_title from tbl_items) as tb_items
on tb_order.series_id = tb_items.series_id where temp_id ='58db09bba25b4'
</code>```

result:

```<code>58db09bba25b4   2   2   2   1490750973  2   GENERIC TICKETING
58db09bba25b4   2   4   1   1490750973  2   GENERIC TICKETING
</code>```

Just giving an another solution.

Body:
Temp ordering table

temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time
58db09bba25b4   2                  2                     2       1490750973
58db09bba25b4   2                  4                     1      1490750973

NEWS ITEMS TABLE

news_id   series_id      news_title
   26          2         GENERIC TICKETING
   27          2         GENERIC TICKETING

When I do a left join on series_id I get back 4 rows and I only want 2. I'm not sure how to limit the amount of joined rows to one row.

CURRENT QUERY

SELECT
    *
FROM
    ticket_ordering_temp
LEFT JOIN
    news_items
on
    ( news_items.series_id = SELECT
                                DISTINCT(event_id)
                             FROM
                                news_items
                             where
                                series_id=ticket_ordering_temp.series_id
    )
where
    temp_id='58db09bba25b4''

DESIRED RESULT
I want just 1 row from table 2 and not 2 rows joined as stated above

temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time news_title
58db09bba25b4   2                  2                     2       1490750973  GENERIC TICKETING
58db09bba25b4   2                  4                     1      1490750973 GENERIC TICKETING

Body:
try this Querying with tempTable:

select distinct * from
(select  * from
(select '58db09bba25b4' as temp_id,   2 as series_id,2 as news_ticket_breakdown_id,2 as quantity,1490750973 as  expiry_time  union all
select '58db09bba25b4' ,  2   ,              4  ,                  1,     1490750973) as tbl_order) as tbl_order

left join

(select series_id,news_title from
(select  26 as  news_id,         2 as series_id,         'GENERIC TICKETING' as news_title union all
select   27  ,        2 ,        'GENERIC TICKETING') as tbl_items) tbl_items
on tbl_order.series_id = tbl_items.series_id where temp_id ='58db09bba25b4'

Querying With actual table:

select DISTINCT * from
(select temp_id,series_id,news_ticket_breakdown_id,quantity,expiry_time from tbl_order) as tb_order
left join
(select series_id,news_title from tbl_items) as tb_items
on tb_order.series_id = tb_items.series_id where temp_id ='58db09bba25b4'

result:

58db09bba25b4   2   2   2   1490750973  2   GENERIC TICKETING
58db09bba25b4   2   4   1   1490750973  2   GENERIC TICKETING

Just giving an another solution.


问:
After showing the output the python window closes immediately
Python version 2.7

I tried a code and it was not giving any error. When I ran the program, It showed the result only for a few milliseconds and then the window closed immediately. Is there any method to display the result permanently and to close the window only at my wish rather than it closing all by itself?

答:
This happens because your code runs as fast as it can and stops when its finished.
When you open a .py program via double clicking it on a windows OS; it opens the program in a cmd window and when the code is done running it closes the window again. You only specified it to perform some calculation and then stop after that. Therefor in order to keep the program running type raw_input() or if using python 3  input() at the end of your code in order to prevent it from running all the way through until you press a key.


问:
How to execute promises sequentially, passing the parameters from an array?
```<code>var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))
</code>```

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

答:
You can make the repeated application of .then into a fold pretty neatly if you’re okay with creating as many promises as array elements as is the case in the question:

```<code>myArray.reduce(
  (p, x) =>
    p.then(() => myPromise(x)),
  Promise.resolve()
)
</code>```

but given support, an async function is a better choice. It’s nicely readable and has O(1) instead of O(n) memory overhead.

```<code>const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x)
  }
}

forEachSeries(myArray, myPromise)
</code>```

If you want to collect the return values as an array, that’s:

```<code>const mapSeries = async (iterable, fn) => {
  const results = []

  for (const x of iterable) {
    results.push(await fn(x))
  }

  return results
}
</code>```

or, without async function support,

```<code>const mapSeries = (iterable, fn) => {
  const iterator = iterable[Symbol.iterator]()
  const results = []
  const go = () => {
    const {value, done} = iterator.next()

    if (done) {
      return results
    }

    return fn(value).then(mapped => {
      results.push(mapped)
      return go()
    })
  }

  return Promise.resolve().then(go)
}
</code>```

Runnable snippet:

const myArray = [1, 2, 3, 4, 5, 6]

const sleep = ms =>
  new Promise(res => {
    setTimeout(res, ms)
  })

const myPromise = num =>
  sleep(500).then(() => {
    console.log('done: ' + num)
  })

const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x)
  }
}

forEachSeries(myArray, myPromise)
  .then(() => {
    console.log('all done!')
  })```

Body:
var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

Body:
You can make the repeated application of .then into a fold pretty neatly if you’re okay with creating as many promises as array elements as is the case in the question:

myArray.reduce(
  (p, x) =>
    p.then(() => myPromise(x)),
  Promise.resolve()
)

but given support, an async function is a better choice. It’s nicely readable and has O(1) instead of O(n) memory overhead.

const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x)
  }
}

forEachSeries(myArray, myPromise)

If you want to collect the return values as an array, that’s:

const mapSeries = async (iterable, fn) => {
  const results = []

  for (const x of iterable) {
    results.push(await fn(x))
  }

  return results
}

or, without async function support,

const mapSeries = (iterable, fn) => {
  const iterator = iterable[Symbol.iterator]()
  const results = []
  const go = () => {
    const {value, done} = iterator.next()

    if (done) {
      return results
    }

    return fn(value).then(mapped => {
      results.push(mapped)
      return go()
    })
  }

  return Promise.resolve().then(go)
}

Runnable snippet:

const myArray = [1, 2, 3, 4, 5, 6]

const sleep = ms =>
  new Promise(res => {
    setTimeout(res, ms)
  })

const myPromise = num =>
  sleep(500).then(() => {
    console.log('done: ' + num)
  })

const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x)
  }
}

forEachSeries(myArray, myPromise)
  .then(() => {
    console.log('all done!')
  })


问:
python: Looking for elements in a list
So the thing I'm trying to do is I need to look for a certain thing in a list

```<code> movieOneList = []
  def listcreator(sheet):
        for row in movie_ID.rows[1:]:
             if row[1].value.find(movieOne) != -1:
                 movieOneList.append( print("Found your movie! MovieID={0}, Title={1}".format(row[0].value, row[1].value)))
</code>```

The code works by you type in a certain movie and then openpyxl goes through the worksheet in excel, looks for the movie and then prints the first two rows which is the movie ID and the movie name.

What i can't figure out is how do i grab the movie ID and put it in another list so i can look for it in another workbook

答: I think your problem is that the print function returns None, meaning that for each movie found, you append None to movieOneList. Instead, try movieOneList.append((row[0].value, row[1].value)), which will append a tuple containing the ID and Title of each movie that it finds to movieOneList. If you also want to print the results, you can move the print("Found...) to after the movieOneList.append(...). Hope this helps!

Title: python: Looking for elements in a list

Body:
So the thing I'm trying to do is I need to look for a certain thing in a list

 movieOneList = []
  def listcreator(sheet):
        for row in movie_ID.rows[1:]:
             if row[1].value.find(movieOne) != -1:
                 movieOneList.append( print("Found your movie! MovieID={0}, Title={1}".format(row[0].value, row[1].value)))

The code works by you type in a certain movie and then openpyxl goes through the worksheet in excel, looks for the movie and then prints the first two rows which is the movie ID and the movie name.

What i can't figure out is how do i grab the movie ID and put it in another list so i can look for it in another workbook


问:
Setting value of active workbook in Excel VBA
I for now have my workbook set up this way, in where the workbook is hard coded into the Set command, I am wondering if there is a way of doing this so I can have it where it is fluid? So no matter where this code is place (in another workbook) the code will adapt to it's new surroundings.

Does this make sense?

Below is what I am using now, what I'd like to have it do is for the ActiveWorkbook or something of the sort be used instead. Since this will be set at the beginning of the code and not the middle.

Set wbOOR = Application.Workbooks("Open Order Report.xlsm")

答:
Try this.

```<code>Dim Workbk as workbook
Set Workbk = thisworkbook
</code>```

Now everything you program will apply just for your containing macro workbook.

Body:
Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.


问:
PyInstaller UAC not working in onefile mode

Hello everybody.

I have a small python project and want to make it to single executable file. I am using...

Windows 7

Python 3.4

PyInstaller 3.2.1

My PyInstaller command is,

```<code>PyInstaller -y -w -F -n output_file_name --uac-admin --clean source_file.py
</code>```

this command works properly. But single output file does not ask for admin rights when executed. And there's no shield mark on executable file icon.

When remove the -F option (equivalent to --onefile), output executable file has shield mark on its icon and ask me admin rights. But this is not what I want. I want a single executable file.

I found a manifest file (output_file_name.exe.manifest) in dist\output_file_name folder. So I did...

```<code>PyInstaller -y -w -F -n output_file_name --manifest output_file_name.exe.manifest --uac-admin --clean source_file.py
</code>```

But this command doesn't work. Its single executable file still does not ask for admin rights.

I have removed PyInstaller and installed recent development version.

```<code>pip install git+https://github.com/pyinstaller/pyinstaller.git@develop
</code>```

But the result is same. Its output doesn't have a shield mark on icon and does not ask admin rights.

Do you have any idea?

Please help me!

答:
I found what's wrong!

The key point is...

Install PyInstaller 3.0

Manifest file must be located in dist folder where single excutable file located

The name of manifest file must be same as output file.

If manifest file is located in dist folder, no need to specify --manifest option. --uac-admin is enough.

You can find manifest file at build folder.

Thank you.

Body:
Hello everybody.

I have a small python project and want to make it to single executable file. I am using...

Windows 7

Python 3.4

PyInstaller 3.2.1

My PyInstaller command is,

PyInstaller -y -w -F -n output_file_name --uac-admin --clean source_file.py

this command works properly. But single output file does not ask for admin rights when executed. And there's no shield mark on executable file icon.

When remove the -F option (equivalent to --onefile), output executable file has shield mark on its icon and ask me admin rights. But this is not what I want. I want a single executable file.

I found a manifest file (output_file_name.exe.manifest) in dist\output_file_name folder. So I did...

PyInstaller -y -w -F -n output_file_name --manifest output_file_name.exe.manifest --uac-admin --clean source_file.py

But this command doesn't work. Its single executable file still does not ask for admin rights.

I have removed PyInstaller and installed recent development version.

pip install git+https://github.com/pyinstaller/pyinstaller.git@develop

But the result is same. Its output doesn't have a shield mark on icon and does not ask admin rights.

Do you have any idea?

Please help me!


问:
iPhone simulator only shows a black screen after launching the app
I am moving my 3.x app to use iOS4 features like background processing, fast-app switching. I have been able to get the app running fine. But now whenever I launch the app on the simulator, it just shows a black screen. The app launches, status in XCode changes to running but nothing shows up other than the black screen.

The app runs fine on a device so I know there's nothing wrong with the code. Any idea what could be happening? I have tried reinstalling the SDK but it did not make a difference.

And yes, I have the [window makeKeyAndVisible]; line in the code. So that is not the issue. I am using application:didFinishLaunchingWithOptions: to handle the app launch.

Thanks.

答:
I'm moving my app from 3.x to 4.x and have the same issue. Sound system is launched (music and sounds play well), but entire screen is black. It happens on 4.x simulator and device, but on 3.1.3 device everything seems well.

UPDATE: Recently i have added some window manipulations after application init:

```<code>[window center];
[window makeKeyAndVisible];
[window becomeFirstResponder];
</code>```

and now it's alive =)

Body:
I'm moving my app from 3.x to 4.x and have the same issue. Sound system is launched (music and sounds play well), but entire screen is black. It happens on 4.x simulator and device, but on 3.1.3 device everything seems well.

UPDATE: Recently i have added some window manipulations after application init:

[window center];
[window makeKeyAndVisible];
[window becomeFirstResponder];

and now it's alive =)


问:
Disable chrome custom tabs?
I recently got an update from chrome beta and it came with chrome custom tabs.
I do not like this feature and would like to just open the links directly without pressing the open in chrome button.

Thanks

答:
This seems to have worked for me:

Open Google application or do a search, click the hamburger in the top left and go into Settings.

Go into Accounts and privacy.

Turn off 'open web pages in app'.

This appears to turn off chrome custom tabs.

Title: Disable chrome custom tabs?