问:
React native error when run-android
when i first run react-native run-android i got this error

```<code>Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: AAPT process not ready to receive commands
</code>```

which is my aapt error with log like this above

```<code>app:mergeDebugResources
AAPT err(Facade for 806023675): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 320379832): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1789437959): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1055339140): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 520641803): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1656371171): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1847553157): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1677766557): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1952482313): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1103640883): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1227322743): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 962420428): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1155783227): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 236690628): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1275003794): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1275871824): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 2018846724): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 291122889): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1890726756): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
AAPT err(Facade for 122608110): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
</code>```

...
    :app:mergeDebugResources FAILED

i installed android sdk correctly, i run my android emulator and i have my react native packager running

答:
i just paste this in the command line and enter

```<code>sudo apt-get install lib32stdc++6 lib32z1
</code>```

this works for me , maybe you have different problem with AAPT so i can't say this is the absolute answer but this works for me

Note: Not every aapt error's solution is this, but i hope this may help some of you.

Title: React native error when run-android

Body:
when i first run react-native run-android i got this error

Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: AAPT process not ready to receive commands

which is my aapt error with log like this above

app:mergeDebugResources
AAPT err(Facade for 806023675): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 320379832): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1789437959): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1055339140): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 520641803): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1656371171): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1847553157): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1677766557): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1952482313): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1103640883): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1227322743): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 962420428): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1155783227): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 236690628): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1275003794): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1275871824): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 2018846724): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 291122889): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
AAPT err(Facade for 1890726756): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
AAPT err(Facade for 122608110): /usr/Android/Sdk/build-tools/23.0.1/aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory

...
    :app:mergeDebugResources FAILED

i installed android sdk correctly, i run my android emulator and i have my react native packager running

Body:
i just paste this in the command line and enter

sudo apt-get install lib32stdc++6 lib32z1

this works for me , maybe you have different problem with AAPT so i can't say this is the absolute answer but this works for me

Note: Not every aapt error's solution is this, but i hope this may help some of you.


来源: stackexchange

问:
react-router-dom: getting props.location from within <BrowserRouter> component
I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:

```<code>class App extends Component{
  render(){
    return (
      <BrowserRouter>
        // How do I access this.props.location?
        <div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}
</code>```

I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?

答:
You achieve what u have asked for by doing this

```<code>import AccessRoute from './AccessRoute'

class App extends Component{
  render(){
    return (
      <BrowserRouter>

  <AccessRoute>
 <div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>
        </div>
       </AccessRoute>
      </BrowserRouter>
    );
  }
}
</code>```

AccessRoute.jsx

```<code>import React from 'react'
import {withRouter} from 'react-router';
class AccessRoute extends React.Component{
    constructor(props){
        super(props);
    }

 //If you want to find the location on mount use this

 componentDidMount(){
        console.log("the path name is ",this.props.location.pathname);
    }

 //If you want to find the location on change use this

  componentDidUpdate(prevprops){
    if(this.props.location.pathname!=prevprops.location.pathname){
        console.log("the new path name is ",this.props.location.pathname);
    }

}

    render(){
        return(

            this.props.children

            );
    }
}
export default withRouter(AccessRoute)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:

class App extends Component{
  render(){
    return (
      <BrowserRouter>
        // How do I access this.props.location?

          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>

      </BrowserRouter>
    );
  }
}

I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?

Body:
You achieve what u have asked for by doing this

import AccessRoute from './AccessRoute'

class App extends Component{
  render(){
    return (
      <BrowserRouter>

  <AccessRoute>
 <div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>
        </div>
       </AccessRoute>
      </BrowserRouter>
    );
  }
}

AccessRoute.jsx

import React from 'react'
import {withRouter} from 'react-router';
class AccessRoute extends React.Component{
    constructor(props){
        super(props);
    }

 //If you want to find the location on mount use this

 componentDidMount(){
        console.log("the path name is ",this.props.location.pathname);
    }

 //If you want to find the location on change use this

  componentDidUpdate(prevprops){
    if(this.props.location.pathname!=prevprops.location.pathname){
        console.log("the new path name is ",this.props.location.pathname);
    }

}

    render(){
        return(

            this.props.children

            );
    }
}
export default withRouter(AccessRoute)


问:
How to add bitten-slave as a Windows service
As Part of setting up continuous integration using bitten, I would like to set up some bitten-slaves on windows. However, bitten documentation lacks instructions on how to register bitten slave as a service.

Looking at Microsoft's documentation on How to create a Windows service by using Sc.exe, I've tried the following:

```<code>sc create bitten-slave binPath= "C:\Python26\Scripts\bitten-slave.exe --verbose
--log=C:\dev\bitten.log http://svn/cgi-bin/trac.cgi/builds"
</code>```

The service was indeed created. But trying to start it, I get the following error:

The bitten-slave service failed to
  start due to the following error:  The
  service did not respond to the start
  or control request in a timely
  fashion.

What am I doing wrong?

答: This page on the Bitten wiki describes a simple Python script that can be configured as a scheduled task to ensure the Bitten slave is kept running.</p>

ContentLicense: CC BY-SA 2.5

Body:
As Part of setting up continuous integration using bitten, I would like to set up some bitten-slaves on windows. However, bitten documentation lacks instructions on how to register bitten slave as a service.

Looking at Microsoft's documentation on How to create a Windows service by using Sc.exe, I've tried the following:

sc create bitten-slave binPath= "C:\Python26\Scripts\bitten-slave.exe --verbose
--log=C:\dev\bitten.log http://svn/cgi-bin/trac.cgi/builds"

The service was indeed created. But trying to start it, I get the following error:

The bitten-slave service failed to
  start due to the following error:  The
  service did not respond to the start
  or control request in a timely
  fashion.

What am I doing wrong?


问:
Make a unity game look like it has crashed C#
I want to make my Unity game look like it has crashed (Unresponsive Application Crash, Not a code exception crash).

There probably is some function in the Windows API you can call to emulate this.

I have also seen a game called "Pony Island" do this before, so it certainly is possible. However I don't own a copy nor can I decompile a steam game.

If there is a way to actually hang the program while still being able to bring it back at anytime that solution is preferable, this seems to be unlikely.

To be clear, I want it to look legitimate, so I would prefer the windows API be used to change the window color and generate a pop-up, instead of having them in unity as GUI objects or something similar. I also don't really care about cross-compatibility because the Mac API appears to be hard to implement and even harder to test (on a Windows machine), and most likely won't be compatible with as many hacky features as the Windows API is.

答:
I would try to achieve that by using Thread.Sleep(int)
so while in the main thread, i would call that to freeze the entire unity loop for an amount of seconds eg 5 seconds = 5000ms

and check whether you want to continue the crash or not. for example, but not tested, (i don't have unity at my office environment)

Be carefull with this, as this will freeze it for real, you can't do any operation while it still freezing.

```<code>public class Crasher : MonoBehaviour
{
    public bool isCrash = false;
    //The crash in seconds
    public float crashDuration = 5;

    void Update ()
    {
        if (isCrash)
        {
            //Freeze the applicaion for amount of milliSeconds
            System.Threading.Thread.Sleep(crashDuration * 1000);
        }
    }
}
</code>```

Body:
I would try to achieve that by using Thread.Sleep(int)
so while in the main thread, i would call that to freeze the entire unity loop for an amount of seconds eg 5 seconds = 5000ms

and check whether you want to continue the crash or not. for example, but not tested, (i don't have unity at my office environment)

Be carefull with this, as this will freeze it for real, you can't do any operation while it still freezing.

public class Crasher : MonoBehaviour
{
    public bool isCrash = false;
    //The crash in seconds
    public float crashDuration = 5;

    void Update ()
    {
        if (isCrash)
        {
            //Freeze the applicaion for amount of milliSeconds
            System.Threading.Thread.Sleep(crashDuration * 1000);
        }
    }
}


问:
Android GCM error authentication sender account
It's been a while since I created a Android app with GCM integrated. Previously in the API console you would specify the server IP as a white list. However on my latest project this option is not there. Instead it asks for the SHA1 from the signing key which I have configured.

However when I try to send a notification to a registered device ID I get

"There was an error authenticating the sender account"

I am using the correct API key so I can't see what is wrong.

答:
Google Cloud Messaging defaults to Firebase Cloud Messaging (FCM) now. Use the Server Key provided in the Firebase Console.

Before that, you may also need to Import your Google Cloud Project into Firebase if you have one.

Import instructions (only follow the "Migrate your console project" section)


问:
ImageJ calculating area of solid
I have a series of images of Ice that I want to analyse to determine the area of solid versus liquid. An example image here. This is similar to a porosity measurement however Im struggling as the colours are too similar to simply do Threshold.

At the moment I'm having to play around with the contrast/find edges/despeckle/make binary to make the crystals easier to identify.

I then pass them through morphological segmentation:
example and then threshold to work out area.

Is there an easier way to do this to work out the area of ice versus the area of space/liquid without having to trace out each crystal?

答:
Your image has an uneven background illumination, so it makes sense to do a background subtraction. And Find Edges is a nice preprocessing step to enhance the edges to make the Morphological Segmentation (a reasonable tool here) easier.

Here is a sample macro which automates many of these steps:

// Perform a background subtraction.
orig = getImageID();
run("Duplicate...", " ");
dupl = getImageID();
run("Gaussian Blur...", "sigma=50");
imageCalculator("Subtract create 32-bit", orig, dupl);

// Enhance the edges.
run("Find Edges");

// Run Morphological Segmentation.
run("Morphological Segmentation");
wait(1000); // HACK
call("inra.ijpb.plugins.MorphologicalSegmentation.segment", "tolerance=20", "calculateDams=true", "connectivity=6");
call("inra.ijpb.plugins.MorphologicalSegmentation.setDisplayFormat", "Catchment basins");
call("inra.ijpb.plugins.MorphologicalSegmentation.createResultImage");
```

The resulting image has each region with a different solid value:

From there you could create a histogram (Analyze > Histogram) to get the count of each intensity value—i.e., the area of each object. For some strange reason it didn't work for me until I duplicated the result image first (shift+d).

You can click the Copy button to put the entire histogram into the clipboard, and then paste it into a spreadsheet program or text file, for analysis in other tools.

There are surely other (and probably better) ways to analyze the Catchment basins "labeling" image from Morphological Segmentation; consider asking on the ImageJ Forum for more ideas and suggestions.

Another simpler option you could try is the Trainable Weka Segmentation.

Title: ImageJ calculating area of solid

Body:
Your image has an uneven background illumination, so it makes sense to do a background subtraction. And Find Edges is a nice preprocessing step to enhance the edges to make the Morphological Segmentation (a reasonable tool here) easier.

Here is a sample macro which automates many of these steps:

// Perform a background subtraction.
orig = getImageID();
run("Duplicate...", " ");
dupl = getImageID();
run("Gaussian Blur...", "sigma=50");
imageCalculator("Subtract create 32-bit", orig, dupl);

// Enhance the edges.
run("Find Edges");

// Run Morphological Segmentation.
run("Morphological Segmentation");
wait(1000); // HACK
call("inra.ijpb.plugins.MorphologicalSegmentation.segment", "tolerance=20", "calculateDams=true", "connectivity=6");
call("inra.ijpb.plugins.MorphologicalSegmentation.setDisplayFormat", "Catchment basins");
call("inra.ijpb.plugins.MorphologicalSegmentation.createResultImage");

The resulting image has each region with a different solid value:

From there you could create a histogram (Analyze > Histogram) to get the count of each intensity value—i.e., the area of each object. For some strange reason it didn't work for me until I duplicated the result image first (shift+d).

You can click the Copy button to put the entire histogram into the clipboard, and then paste it into a spreadsheet program or text file, for analysis in other tools.

There are surely other (and probably better) ways to analyze the Catchment basins "labeling" image from Morphological Segmentation; consider asking on the ImageJ Forum for more ideas and suggestions.

Another simpler option you could try is the Trainable Weka Segmentation.


问:
Using bash, how do you make a classpath out of all files in a directory?
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

```<code>LIB=/path/to/project/dir/lib
</code>```

that contains nothing but *.jar files such as:

```<code>junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
</code>```

I need to create a colon-separated classpath variable in the form:

```<code>CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar
</code>```

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

```<code>for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}
</code>```

What is a simple way to accomplish this via bash script?

答:
for i in $LIB/*.jar; do
    CLASSPATH=$CLASSPATH:$i
done
CLASSPATH=`echo $CLASSPATH | cut -c2-`
```

Body:
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

LIB=/path/to/project/dir/lib

that contains nothing but *.jar files such as:

junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar

I need to create a colon-separated classpath variable in the form:

CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}

What is a simple way to accomplish this via bash script?


问:
Print triangle pattern using nested loops
I need to make a "Pyramid" that would look so if the height someone would input was say 2:

```<code> *
***
</code>```

or if someone would input a height of about 6 it would look like this:

```<code>     *
    ***
   *****
  *******
 *********
***********
</code>```

I got down the code for the previous triangle:

```<code>n = int(input("Enter a value for n: "))
for x in range(1, n+1):
    for y in range(n, 0, -1):
        if y > x:
            print(" ", end = "")
        else:
            print("*", end = "")
    print("")
for x in range(1, n):
    for y in range(n):
        if y < x:
            print(" ", end = "")
        else:
            print("*", end = "")
    print("")
</code>```

That prints the triangle

```<code>     *
    **
   ***
  ****
 *****
******
 *****
  ****
   ***
    **
     *
</code>```

答:
I think this is easier</p>

```<code>n = int(input("Please enter an integer: "))
for x in range(1, n+1):
    print("*" * x)
for y in range(n-1, 0, -1):
    print("*" * y)
</code>```

Body:
I need to make a "Pyramid" that would look so if the height someone would input was say 2:

 *
***

or if someone would input a height of about 6 it would look like this:

     *
    ***
   *****
  *******
 *********
***********

I got down the code for the previous triangle:

n = int(input("Enter a value for n: "))
for x in range(1, n+1):
    for y in range(n, 0, -1):
        if y > x:
            print(" ", end = "")
        else:
            print("*", end = "")
    print("")
for x in range(1, n):
    for y in range(n):
        if y < x:
            print(" ", end = "")
        else:
            print("*", end = "")
    print("")

That prints the triangle

     *
    **
   ***
  ****
 *****
******
 *****
  ****
   ***
    **
     *

Body:
I think this is easier

n = int(input("Please enter an integer: "))
for x in range(1, n+1):
    print("*" * x)
for y in range(n-1, 0, -1):
    print("*" * y)


问:
Why this loop is not working?
```<code>while(a!=1&&c!=1)
{
    r=rand()%2;
    if(r==0)
    {
        cout<<"Cruz"<<endl;
        if(a==1)
        {
            c=0;
        }
        c++;
    }
    else if(r==1)
    {
        if(a>1)
        {
            a=0;
        }
        cout<<"Cara"<<endl;
        a++;
    }
    b++;
}
</code>```

I don't know why but this loop always exits when one of the two conditions is false... and I need when both are false.
Does anyone know why is this happening?

答:
After the while statement, you explain the condition that must stay true while the code continues to loop. Since you want to exit when a and b have some property, you need to keep looping while either a or b does not have that property.

Say you can't go to sleep until both your homework and your chores are done. That means you need to stay awake while either your homework or your chores aren't done.

Title: Why this loop is not working?

Body:
while(a!=1&&c!=1)
{
    r=rand()%2;
    if(r==0)
    {
        cout<<"Cruz"<<endl;
        if(a==1)
        {
            c=0;
        }
        c++;
    }
    else if(r==1)
    {
        if(a>1)
        {
            a=0;
        }
        cout<<"Cara"<<endl;
        a++;
    }
    b++;
}

I don't know why but this loop always exits when one of the two conditions is false... and I need when both are false.
Does anyone know why is this happening?


问:
@Autowired doesn't work in method parameter
Here is my AppConfig:

```<code>@Configuration
@EnableWebMvc
@ComponentScan
class AppConfig{
    @Bean("myname")
    fun name(): Name = Name("Quang")
}
</code>```

Data class:

```<code>data class Name(val value: String ="")
</code>```

My Controller Class:

```<code>@Controller
@RequestMapping("/")
class Main{
    @RequestMapping("/")
    @ResponseBody
    fun index(@Autowired @Qualifier("myname") name: Name): Name {
        //this return ""
        return name
    }
}
</code>```

The result is "" instead of "Quang".
But now if I inject it from field like this, it works fine:

```<code>@Controller
@RequestMapping("/")
class Main{
    @Autowired(required = true)
    @Qualifier("myname")
    lateinit var name:Name
    @RequestMapping("/")
    @ResponseBody
    fun index(): Name {
        //this return "Quang" as expected
        return name
    }
}
</code>```

So can you explain why @Autowired doesn't works when I use it in method parameter

答:
According to documentation:

Marks a constructor, field, setter method or config method as to be
  autowired by Spring's dependency injection facilities.

In your first example, Spring will not autowire anything.

Body:
Here is my AppConfig:

@Configuration
@EnableWebMvc
@ComponentScan
class AppConfig{
    @Bean("myname")
    fun name(): Name = Name("Quang")
}

Data class:

data class Name(val value: String ="")

My Controller Class:

@Controller
@RequestMapping("/")
class Main{
    @RequestMapping("/")
    @ResponseBody
    fun index(@Autowired @Qualifier("myname") name: Name): Name {
        //this return ""
        return name
    }
}

The result is "" instead of "Quang".
But now if I inject it from field like this, it works fine:

@Controller
@RequestMapping("/")
class Main{
    @Autowired(required = true)
    @Qualifier("myname")
    lateinit var name:Name
    @RequestMapping("/")
    @ResponseBody
    fun index(): Name {
        //this return "Quang" as expected
        return name
    }
}

So can you explain why @Autowired doesn't works when I use it in method parameter


问:
Debugging a Scrollbar code that's not working properly on Blogger
I've been trying to get this scrollbar code to work on Blogger, but haven't been able to figure out how to. Can someone see if they are able to figure out what the issue is, and how to resolve it.

Same Code, Both look and act different,

Jsfiddle:

https://jsfiddle.net/xuc92tt3/

Screenshot

vs.

Blogger:

https://debugscroll.blogspot.com/

Screenshot

Also, there shouldn't be a horizontal line below the div blocks either.

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

```

答:
Add this CSS code</p>

```<code>.main-inner .widget ul li {
    padding: 0;
    border-top: 0;
    border-bottom: 0;
    margin-bottom: 20px;
}
.main-inner .widget h2 {
    margin: 0;
    padding: 0;
}
</code>```

Body:
Add this CSS code

.main-inner .widget ul li {
    padding: 0;
    border-top: 0;
    border-bottom: 0;
    margin-bottom: 20px;
}
.main-inner .widget h2 {
    margin: 0;
    padding: 0;
}


问:
Iterate over a column in PL/SQL
I have a table Emp with EmpID, Empname, Salary and I am trying to do a calculation for each employee. But I am having problems trying to iterate over each emp to do the calculation. I cant use explicit cursors though.

So right now I am just trying to create the list of empIDs:

```<code>Declare
    aRows Number;
    eid emp_ID%TYPE;
Begin
    Select Count(*)
    Into aRows
    from emp;

    Select emp_ID
    Into eid
    From emp;

    FOR days IN 1..Tot_Rows
    Loop
        Dbms_Output.Put_Line(eid);
        eid := eid + 1;
    End Loop;
END;
</code>```

But I get the error:
PLS-00320: the declaration of the type of this expression is incomplete or malformed

答:
The simplest way to iterate over the rows in a table in PL/SQL is to do something like

```<code>BEGIN
  FOR employees IN (SELECT emp_id FROM emp)
  LOOP
    dbms_output.put_line( employees.emp_id );
  END LOOP;
END;
</code>```

Alternately, you could fetch all the EID values into a PL/SQL collection and iterate over the collection, as in this example

```<code>DECLARE
  TYPE emp_id_tbl IS TABLE OF emp.emp_id%type;
  l_emp_ids emp_id_tbl ;
BEGIN
  SELECT emp_id
    BULK COLLECT INTO l_emp_ids
    FROM emp;

  FOR i IN l_emp_ids .FIRST .. l_empnos.LAST
  LOOP
    dbms_output.put_line( l_emp_ids (i) );
  END LOOP;
END;
</code>```

If your query can return thousands of rows, however, fetching all the data into the collection may use more of the PGA memory than you'd like and you may need to fetch rows in chunks using the LIMIT clause.  But that would seem to be getting ahead of ourselves at this point.

Title: Iterate over a column in PL/SQL

Body:
I have a table Emp with EmpID, Empname, Salary and I am trying to do a calculation for each employee. But I am having problems trying to iterate over each emp to do the calculation. I cant use explicit cursors though.

So right now I am just trying to create the list of empIDs:

Declare
    aRows Number;
    eid emp_ID%TYPE;
Begin
    Select Count(*)
    Into aRows
    from emp;

    Select emp_ID
    Into eid
    From emp;

    FOR days IN 1..Tot_Rows
    Loop
        Dbms_Output.Put_Line(eid);
        eid := eid + 1;
    End Loop;
END;

But I get the error:
PLS-00320: the declaration of the type of this expression is incomplete or malformed

Body:
The simplest way to iterate over the rows in a table in PL/SQL is to do something like

BEGIN
  FOR employees IN (SELECT emp_id FROM emp)
  LOOP
    dbms_output.put_line( employees.emp_id );
  END LOOP;
END;

Alternately, you could fetch all the EID values into a PL/SQL collection and iterate over the collection, as in this example

DECLARE
  TYPE emp_id_tbl IS TABLE OF emp.emp_id%type;
  l_emp_ids emp_id_tbl ;
BEGIN
  SELECT emp_id
    BULK COLLECT INTO l_emp_ids
    FROM emp;

  FOR i IN l_emp_ids .FIRST .. l_empnos.LAST
  LOOP
    dbms_output.put_line( l_emp_ids (i) );
  END LOOP;
END;

If your query can return thousands of rows, however, fetching all the data into the collection may use more of the PGA memory than you'd like and you may need to fetch rows in chunks using the LIMIT clause.  But that would seem to be getting ahead of ourselves at this point.


问:
Populate variable from a JSON Result in ASP.NET MVC
I don't know if this is a basic stuff but I'm a having a hard time on populating a variable from a JSON result. I can't just find a right keyword on it.

What I want to do is populate this variable.

Js File

```<code>var opts = [
 { key: 1, label: 'High' },
 { key: 2, label: 'Normal' },
 { key: 3, label: 'Low' }
];
</code>```

Layer

```<code>public IEnumerable<DropdownModel> ToLayerLevel()
    {
        List<DropdownModel> data = new List<DropdownModel>();
        using (SqlConnection con = new SqlConnection(Conn.MyConn()))
        {
            SqlCommand com = new SqlCommand("SELECT id, desc FROM PriorityLevel", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                DropdownModel value = new DropdownModel();
                value.key = reader.GetInt32(0);
                value.label = reader.GetString(1);
                data.Add(value);
            }
        }
        return data;
    }
</code>```

Controller

```<code>public JsonResult ddlToLayerLevel()
    {
        DropdownLayers ddl = new DropdownLayers();
        var data = ddl.ToLayerLevel();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
</code>```

答:
Getting data using jQuery:

```<code>var opts = [];
$.getJSON("<your url here>", function(res){
    opts = res;
});
</code>```

There is an alternate simplified way I use when I need to get objects created in c# directly into a js variable. It does come with pros and cons though

pros

Much quicker to code rather than having to create a controller and call a js ajax function every time.

Loads the entire page in one go and overall loads the data into js faster.

cons

The code doesn't go into your js file but instead into a cshtml file.

The information is only fetched in load time and the code can't be reused in real time when the page is still open.

If you don't need the js variable on page load, not using this would speed up the initial page load speed and will load the js information later.

First I create an extension function in static class as follows:

```<code>public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
{
    return htmlHelper.Raw(JsonConvert.SerializeObject(obj));
}
</code>```

Now in any cshtml file I can define the js variable by simply using the following:

```<code>@{
    DropdownLayers ddl = new DropdownLayers();
    var data = ddl.ToLayerLevel();
}

<script>
    var opts = @Html.ToJS(data);
</script>
</code>```

Body:
I don't know if this is a basic stuff but I'm a having a hard time on populating a variable from a JSON result. I can't just find a right keyword on it.

What I want to do is populate this variable.

Js File

var opts = [
 { key: 1, label: 'High' },
 { key: 2, label: 'Normal' },
 { key: 3, label: 'Low' }
];

Layer

public IEnumerable<DropdownModel> ToLayerLevel()
    {
        List<DropdownModel> data = new List<DropdownModel>();
        using (SqlConnection con = new SqlConnection(Conn.MyConn()))
        {
            SqlCommand com = new SqlCommand("SELECT id, desc FROM PriorityLevel", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                DropdownModel value = new DropdownModel();
                value.key = reader.GetInt32(0);
                value.label = reader.GetString(1);
                data.Add(value);
            }
        }
        return data;
    }

Controller

public JsonResult ddlToLayerLevel()
    {
        DropdownLayers ddl = new DropdownLayers();
        var data = ddl.ToLayerLevel();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Body:
Getting data using jQuery:

var opts = [];
$.getJSON("<your url here>", function(res){
    opts = res;
});

There is an alternate simplified way I use when I need to get objects created in c# directly into a js variable. It does come with pros and cons though

pros

Much quicker to code rather than having to create a controller and call a js ajax function every time.

Loads the entire page in one go and overall loads the data into js faster.

cons

The code doesn't go into your js file but instead into a cshtml file.

The information is only fetched in load time and the code can't be reused in real time when the page is still open.

If you don't need the js variable on page load, not using this would speed up the initial page load speed and will load the js information later.

First I create an extension function in static class as follows:

public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
{
    return htmlHelper.Raw(JsonConvert.SerializeObject(obj));
}

Now in any cshtml file I can define the js variable by simply using the following:

@{
    DropdownLayers ddl = new DropdownLayers();
    var data = ddl.ToLayerLevel();
}

<script>
    var opts = @Html.ToJS(data);
</script>


问:
perl GetOptions, option-triggered subroutine that accepts arguments
I am trying to use the GetOptions function from GetOpt::Long to call a subroutine that accepts an argument. However, the subroutine gets called regardless of whether the option is specified on the command line. This unexpected behavior does not occur if an argument is not passed to the subroutine in the GetOptions line.

What follows is a minimal demonstration of the problem:

If an argument is provided to the subroutine in the GetOptions line, the subroutine ends up being called regardless of whether its controlling option is supplied on the command line:

```<code>$ cat a1.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $var="entered";
GetOptions ( "opt" => \&sub1($var) );
sub sub1 { print "sub1 $_[0]\n"; }

$ perl a1.pl --opt
sub1 entered

$ perl a1.pl
sub1 entered
</code>```

In contrast, if the subroutine is called in GetOptions without an argument, it behaves appropriately:

```<code>$ cat a2.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
GetOptions ( "opt" => \&sub2 );
sub sub2 { print "sub2 entered\n"; }

$ perl a2.pl --opt
sub2 entered

$ perl a2.pl
</code>```

What am I doing wrong?

PS: I know that I can simply set a variable that controls whether the subroutine is called after the GetOptions block, but I would like to determine the correct syntax for calling the subroutine within the GetOptions line, as well as understand why the observed behavior is happening.

答:
It's been a few years since I did much Perl, but I'm pretty sure it is because

```<code>\&sub1($var)
</code>```

is a reference to the result of invoking sub1.  That is, the line

```<code>GetOptions ( "opt" => \&sub1($var) );
</code>```

actually invokes sub($var) as part of constructing the argument list to GetOptions.  This looks like a corner case in the syntax, you are taking a reference to the result of that invocation.

This should clear things up:

```<code>$ perl -de0

Loading DB routines from perl5db.pl version 1.49_001
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):   0
  DB<1> sub sub1 { print "sub1\n"; }

  DB<2> sub1()
sub1

  DB<3> &sub1
sub1

  DB<4> \&sub1

  DB<5> x \&sub1
0  CODE(0x804d7fe8)
   -> &main::sub1 in (eval 6)[/usr/lib/perl5/5.22/perl5db.pl:737]:2-2
  DB<6> x \&sub1()
sub1
0  SCALAR(0x804ee7f0)
   -> 1
</code>```

Body:
I am trying to use the GetOptions function from GetOpt::Long to call a subroutine that accepts an argument. However, the subroutine gets called regardless of whether the option is specified on the command line. This unexpected behavior does not occur if an argument is not passed to the subroutine in the GetOptions line.

What follows is a minimal demonstration of the problem:

If an argument is provided to the subroutine in the GetOptions line, the subroutine ends up being called regardless of whether its controlling option is supplied on the command line:

$ cat a1.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $var="entered";
GetOptions ( "opt" => \&sub1($var) );
sub sub1 { print "sub1 $_[0]\n"; }

$ perl a1.pl --opt
sub1 entered

$ perl a1.pl
sub1 entered

In contrast, if the subroutine is called in GetOptions without an argument, it behaves appropriately:

$ cat a2.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
GetOptions ( "opt" => \&sub2 );
sub sub2 { print "sub2 entered\n"; }

$ perl a2.pl --opt
sub2 entered

$ perl a2.pl

What am I doing wrong?

PS: I know that I can simply set a variable that controls whether the subroutine is called after the GetOptions block, but I would like to determine the correct syntax for calling the subroutine within the GetOptions line, as well as understand why the observed behavior is happening.

Body:
It's been a few years since I did much Perl, but I'm pretty sure it is because

\&sub1($var)

is a reference to the result of invoking sub1.  That is, the line

GetOptions ( "opt" => \&sub1($var) );

actually invokes sub($var) as part of constructing the argument list to GetOptions.  This looks like a corner case in the syntax, you are taking a reference to the result of that invocation.

This should clear things up:

$ perl -de0

Loading DB routines from perl5db.pl version 1.49_001
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):   0
  DB<1> sub sub1 { print "sub1\n"; }

  DB<2> sub1()
sub1

  DB<3> &sub1
sub1

  DB<4> \&sub1

  DB<5> x \&sub1
0  CODE(0x804d7fe8)
   -> &main::sub1 in (eval 6)[/usr/lib/perl5/5.22/perl5db.pl:737]:2-2
  DB<6> x \&sub1()
sub1
0  SCALAR(0x804ee7f0)
   -> 1


问:
Conditional formatting multiple rules to single cell
I have used one formula to change the font colour if a cell contains the text "complete" & another formula to add a light blue fill to the entire row if the word "odd" appears in a cell which is in a different column to the first formula.

The conditions seem to clash & although I have changed and played with the order of the conditions & checked there is no conflict in the fill/background or the font colour, even when changing the font colour manually again the fill from the second formula returns the font the cell to black although it is set to automatic in the conditional formatting rule with the fill ?

I wonder where i am going wrong as everything suggests the two conditions should work fine together though when the fill is applied the font goes back to black when it should be green ?

Have you any suggestions ?

答:
You can combine multiple conditional formats overlapping cells/rows.  (Excel's just a little picky that you do it just right!)

Always use New Rule as opposed to using the built-in rules.

Choose Use a formula to determine which cells to format.

For your example question, I populated the cells as shown above.  Select cell B4 and set the conditional formatting as above =($B4="complete") .  Note that I removed a $ (dynamic vs absolute cell reference) that was automatically filled in, so that I can fill the formatting's formula down.

Highlight entire Row 4 and set the conditional formatting as below.  Again, note the modified $.

When it's working properly, copy entire Row 4, select the rows to which the formatting should be applied, and Paste Formatting.

[

Obviously the steps will vary for you depending on your data and what's in the neighboring cells whose formats you may or may not want affected by the formatting and copy/pasting.

Let me know if that works for you.


问:
Search through multiple fields in Django
I'm trying to build a search system, and I want to search by multiple fieldsname, state, city, in my django models. I wrote the below code, yet I've been unable to figure out how to go about it.

Models:

```<code>class Finhall(models.Model):
     user=models.ForeignKey(User)
     name=models.CharField(max_length=250, unique=True)
     address=models.CharField(max_length=200)
     city=models.CharField(max_length=200)
     state=models.CharField(max_length=200)

     def __unicode__(self):
         return u'%s' % (self.name)
</code>```

Views.py

```<code>def hup_find(request):
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string=request.GET.get('q')
        seens=Finhall.objects.filter(name__icontains=query_string)
    else:
        seens=None
    return render_to_response('find.html',{'seens':seens},context_instance=RequestContext(request))
</code>```

Template:

```<code> {% block content %}
     <body>
    <form action="" method="GET">
    <input type="text" name="q" />
    <button type="submit">search</button>
   </form>

    {% for seen in seens %}

    <p> {{seen.name}}</p>

    {% empty %}

      <p> no search </p>
    {% endfor %}

 </body>

   {% endblock %}
</code>```

How can I go about this? I don't want to use haysatck due to some personal reasons.

答:
To search same text in multiple fields you can use this :</p>

```<code>from django.db.models import Q

class SearchAPI(APIView):
    def get(self, request, search_text, format=None, **kwargs):
        Model.objects.filter(Q(search_tags__contains=search_text) | Q(auto_tags__contains=search_text)
</code>```

Body:
I'm trying to build a search system, and I want to search by multiple fieldsname, state, city, in my django models. I wrote the below code, yet I've been unable to figure out how to go about it.

Models:

class Finhall(models.Model):
     user=models.ForeignKey(User)
     name=models.CharField(max_length=250, unique=True)
     address=models.CharField(max_length=200)
     city=models.CharField(max_length=200)
     state=models.CharField(max_length=200)

     def __unicode__(self):
         return u'%s' % (self.name)

Views.py

def hup_find(request):
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string=request.GET.get('q')
        seens=Finhall.objects.filter(name__icontains=query_string)
    else:
        seens=None
    return render_to_response('find.html',{'seens':seens},context_instance=RequestContext(request))

Template:

 {% block content %}

    <form action="" method="GET">
    <input type="text" name="q" />
    <button type="submit">search</button>
   </form>

    {% for seen in seens %}

 {{seen.name}}

    {% empty %}

 no search

    {% endfor %}

   {% endblock %}

How can I go about this? I don't want to use haysatck due to some personal reasons.

Body:
To search same text in multiple fields you can use this :

from django.db.models import Q

class SearchAPI(APIView):
    def get(self, request, search_text, format=None, **kwargs):
        Model.objects.filter(Q(search_tags__contains=search_text) | Q(auto_tags__contains=search_text)


问:
How multilevel CPU caches having the same cache line size work?
Note: I'm not sure if StackOverflow is the correct place for that question or if there is a more suitable StackExchange sub for this

I've read in a book, that for multilevel CPU caches, cache line size increases as per level's total memory size. I can totally undrestand how this works (or at least I think so) when used with quite simple architectures. Then I came accross this question. Question is how cache memories of the same cache line can cooperate?

This is how I percieve the way of cache memories with different cache line size work. For simplicity, lets suppose there are no different caches for data and for instructions and we only have L1 and L2 caches (L3 and L4 not exist).
If L1 has cache line size of 64 bytes and L2 of 128 bytes, when we have cache miss on L2 and we need to fetch the desired byte or word from main memory, we also bring its closest bytes or words in order to fill the 128 bytes of the L2 cache line. Then because of the locality of the references to memory locations produced by the processor we have higher probability of geting a hit on L2 whe missing on L1. But if we had equal cache line sizes this of course wouldn't happen, with the previous algorithm. Can you explain me some sort/simple algorithm or implementation of how modern CPUs take advantage of caches having the same line size?

Thanks in advance.

答:
I've read in a book, that for multilevel CPU caches, cache line size increases as per level's total memory size.

That's not true for most CPUs.  Usually the line size is the same in all caches, but the total size increases.  Often also the associativity, but usually not by as much as the total size, so the number of sets typically increases.

The point of multi-level caches is to get low latency and large size without needing a single cache that's both large and low latency (because that's physically impossible).

HW prefetch into L2 and/or L1 is what makes sequential read work well, not larger line size in out levels of cache.  (And in multi-core CPUs, private L1/L2 + shared L3 provide private latency + bandwidth filters for the memory workload hits the shared domain, but then you have L3 as a coherency backstop instead of hitting DRAM for data that's shared between cores.)

Having different line sizes in different caches is more complicated, especially in a multi-core system where caches have to maintain coherency with each other using MESI.  Transferring around whole cache between caches works well.

But if if L1D lines are 64B and private L2 / shared L3 lines are 128B, then a load on one core might force the L2 cache to request both halves separately in case separate cores had each of the two halves of the 128B line modified.  Sounds really complicated, and puts more logic into the outer-level cache.

(Paul Clayton's answer on the question you linked points out that a possible solution to that problem is separate validity bits for the two halves of a larger cache line, or even separate MESI coherency state.  But still sharing the same tag, so if they are both valid then they have to be caching two halves of the same 128B block.)


问:
How to schedule a task that runs php using window task scheduler?
I've been trying to run a php file using window task scheduler. I've tried using the .bat file, but it won't work.
Here's what I've done:

I've created a task "Download Image"

I've created a .bat file, and the content is:

"C:\xampp\php\php.exe" -f "D:\server\newxml\download.php";

The php file that I want to run is:

```<code>    ini_set('max_execution_time', 300);
    $doc = simplexml_load_file('xml_edit_feeds.xml');

    foreach ($doc->xpath("//item") as $item) {
        $name = $item->productname;
        $realname = preg_replace('/\s/', '',$name);
        $url = $item->thumbnail_url;
        $img = 'D:/server/newxml/imagethumbnail/'.$realname.'.png';
        $filename = 'D:server/newxml/imagethumbnail/'.$realname.'.png';
            file_put_contents($img, file_get_contents($url));
    }
?>
</code>```

This is the screen shoot of the windows task scheduler:

Is there something wrong from what I did? Thank you for your help

答: I didn't try this before, but I think you should use a browser exe program to open your webpage instead of php.exe.</p>

Body:
I've been trying to run a php file using window task scheduler. I've tried using the .bat file, but it won't work.
Here's what I've done:

I've created a task "Download Image"

I've created a .bat file, and the content is:

"C:\xampp\php\php.exe" -f "D:\server\newxml\download.php";

The php file that I want to run is:

    ini_set('max_execution_time', 300);
    $doc = simplexml_load_file('xml_edit_feeds.xml');

    foreach ($doc->xpath("//item") as $item) {
        $name = $item->productname;
        $realname = preg_replace('/\s/', '',$name);
        $url = $item->thumbnail_url;
        $img = 'D:/server/newxml/imagethumbnail/'.$realname.'.png';
        $filename = 'D:server/newxml/imagethumbnail/'.$realname.'.png';
            file_put_contents($img, file_get_contents($url));
    }
?>

This is the screen shoot of the windows task scheduler:

Is there something wrong from what I did? Thank you for your help


答: The logical and operation only returns true when both the conditions are met. If you require the loop to work please use the logical OR operator that returns true when any one of the conditions are met. Please see the below truth table. Please check if you are using the correct logical operator</p>

Title: Why this loop is not working?


问:
How can I create a class that is a vector of another class in C++?
Thanks for reading my question.

I'm trying to begin writing a program that uses a deck of cards, because I want to learn about using classes. I decided to create a class that stores a suit and a value, like so:

#ifndef CARD_H
#define CARD_H

class Card {
    public:
        //here are the individual card values
        int _suit;
        int _value;
        Card(int suit, int value);
};

#endif
```

<pre class="lang-c++ prettyprint-override"><code>#include "card.h"

//define suits
const int spades = 0;
const int clubs = 1;
const int hearts = 2;
const int diamonds = 3;
//define face cards
const int jack = 11;
const int queen = 12;
const int king = 13;
const int ace = 14;

Card::Card(int suit, int value){
    _suit = suit;
    _value = value;
}
</code>```

I then decided to create a deck class, and in that class initialize my cards by assigning a value from 0-3 (suit) and then a value from 2-14 (ranking of card). I also add the cards into a vector that I defined to hold them, like so:

#ifndef DECK_H
#define DECK_H

#include <vector>

class Deck {
    public:
        std::vector<Card> _deck(51);
        Deck();
};

#endif
```

<pre class="lang-c++ prettyprint-override"><code>#include <iostream>
#include <vector>

#include "card.h"
#include "deck.h"

const int all_suits = 4 - 1;
const int all_values = 14;

Deck::Deck(){
    int i = 0;
    for (int j = 0; j <= all_suits; ++j) {
        //begin with 2 because card can't have value 0
        for (int k = 2; k <= all_values; ++k) {
            _deck[i] = Card(j, k);
            ++i;
        }
    }
}
</code>```

This somehow gives me issues when I try to test the program like so:

#include <iostream>
#include <vector>

#include "card.h"
#include "deck.h"

int main() {
    Deck new_deck = Deck();
    std::cout << new_deck._deck[4]._value;
  return 0;
}
```

<p>The following errors show up when I try to run the code:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code>In file included from main.cpp:6:
./deck.h:8:27: error: expected parameter declarator
                std::vector<Card> _deck(51);
                                        ^
./deck.h:8:27: error: expected ')'
./deck.h:8:26: note: to match this '('
                std::vector<Card> _deck(51);
                                       ^
main.cpp:22:24: error: reference to non-static member function must be called; did you mean to call it with no arguments?
        std::cout << new_deck._deck[4]._value;
                     ~~~~~~~~~^~~~~
                                   ()
3 errors generated.
In file included from deck.cpp:8:
./deck.h:8:27: error: expected parameter declarator
                std::vector<Card> _deck(51);
                                        ^
./deck.h:8:27: error: expected ')'
./deck.h:8:26: note: to match this '('
                std::vector<Card> _deck(51);
                                       ^
deck.cpp:18:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
                        _deck[i] = Card(j, k);
                        ^~~~~
                             ()
3 errors generated.</code>```

Honestly, I'm not quite sure what's going on. I pretty closely followed an example of classes I saw online. If anyone could help me find the problem, that would be much appreciated. Sorry, I'm a little new to this, and may have made some silly mistakes. I really appreciate your time and patience in reading this and helping me out.

答:
Your problem lies with the declaration of _deck:

```<code>class Deck {
    public:
        std::vector<Card> _deck(51);
</code>```

Here you are trying to declare _deck and call a constructor, but you can not do so from a class member initialiser. It's possible to do this for data members with no constructors, for example:

```<code>class Deck {
    public:
        int no_of_cards = 51;
        std::vector<Card> _deck;
</code>```

You will need to use your constructor to initialise _deck (much like you're already doing:

```<code>Deck::Deck() {
    _deck.reserve(51);
    int i = 0;
    for (int j = 0; j <= all_suits; ++j) {
        //begin with 2 because card can't have value 0
        for (int k = 2; k <= all_values; ++k) {
            _deck.push_back(Card(j, k));
            ++i;
        }
    }
}
</code>```

And leave your declaration of _deck as:

```<code>class Deck {
    public:
        std::vector<Card> _deck;
</code>```

Body:
Thanks for reading my question.

I'm trying to begin writing a program that uses a deck of cards, because I want to learn about using classes. I decided to create a class that stores a suit and a value, like so:

#ifndef CARD_H
#define CARD_H

class Card {
    public:
        //here are the individual card values
        int _suit;
        int _value;
        Card(int suit, int value);
};

#endif

#include "card.h"

//define suits
const int spades = 0;
const int clubs = 1;
const int hearts = 2;
const int diamonds = 3;
//define face cards
const int jack = 11;
const int queen = 12;
const int king = 13;
const int ace = 14;

Card::Card(int suit, int value){
    _suit = suit;
    _value = value;
}

I then decided to create a deck class, and in that class initialize my cards by assigning a value from 0-3 (suit) and then a value from 2-14 (ranking of card). I also add the cards into a vector that I defined to hold them, like so:

#ifndef DECK_H
#define DECK_H

#include <vector>

class Deck {
    public:
        std::vector<Card> _deck(51);
        Deck();
};

#endif

#include <iostream>
#include <vector>

#include "card.h"
#include "deck.h"

const int all_suits = 4 - 1;
const int all_values = 14;

Deck::Deck(){
    int i = 0;
    for (int j = 0; j <= all_suits; ++j) {
        //begin with 2 because card can't have value 0
        for (int k = 2; k <= all_values; ++k) {
            _deck[i] = Card(j, k);
            ++i;
        }
    }
}

This somehow gives me issues when I try to test the program like so:

#include <iostream>
#include <vector>

#include "card.h"
#include "deck.h"

int main() {
    Deck new_deck = Deck();
    std::cout << new_deck._deck[4]._value;
  return 0;
}

The following errors show up when I try to run the code:

In file included from main.cpp:6:
./deck.h:8:27: error: expected parameter declarator
                std::vector<Card> _deck(51);
                                        ^
./deck.h:8:27: error: expected ')'
./deck.h:8:26: note: to match this '('
                std::vector<Card> _deck(51);
                                       ^
main.cpp:22:24: error: reference to non-static member function must be called; did you mean to call it with no arguments?
        std::cout << new_deck._deck[4]._value;
                     ~~~~~~~~~^~~~~
                                   ()
3 errors generated.
In file included from deck.cpp:8:
./deck.h:8:27: error: expected parameter declarator
                std::vector<Card> _deck(51);
                                        ^
./deck.h:8:27: error: expected ')'
./deck.h:8:26: note: to match this '('
                std::vector<Card> _deck(51);
                                       ^
deck.cpp:18:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
                        _deck[i] = Card(j, k);
                        ^~~~~
                             ()
3 errors generated.

Honestly, I'm not quite sure what's going on. I pretty closely followed an example of classes I saw online. If anyone could help me find the problem, that would be much appreciated. Sorry, I'm a little new to this, and may have made some silly mistakes. I really appreciate your time and patience in reading this and helping me out.

Body:
Your problem lies with the declaration of _deck:

class Deck {
    public:
        std::vector<Card> _deck(51);

Here you are trying to declare _deck and call a constructor, but you can not do so from a class member initialiser. It's possible to do this for data members with no constructors, for example:

class Deck {
    public:
        int no_of_cards = 51;
        std::vector<Card> _deck;

You will need to use your constructor to initialise _deck (much like you're already doing:

Deck::Deck() {
    _deck.reserve(51);
    int i = 0;
    for (int j = 0; j <= all_suits; ++j) {
        //begin with 2 because card can't have value 0
        for (int k = 2; k <= all_values; ++k) {
            _deck.push_back(Card(j, k));
            ++i;
        }
    }
}

And leave your declaration of _deck as:

class Deck {
    public:
        std::vector<Card> _deck;


问:
Solr - schema help (product attributes)
I was wondering if any of you could help me with storing product attributes in Solr. The problem that I have is that product attributes vary depending on the product category. From what I've understood so far, I'd have to list the fields in my schema. The number of attributes is rather large and constantly changing - what do you guys suggest?

For example, a product in the shirts category might have a size attribute but one in the realty category have might have bedrooms attribute.

(I'm currently planning on constantly importing MySQL data into Solr and use Solr mostly for faceted searching)

答:
You can set up dynamic fields in solr. In schema.xml, in the <fields> block, you can configure dynamic field definitions like this:

```<code><fields>
    ...

    <dynamicField name="*_t"  type="text"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_s"  type="string" indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_sa" type="string" indexed="true" stored="true" multiValued="true" />
    <dynamicField name="*_d"  type="date"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_f"  type="sfloat" indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_i"  type="sint"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_ia" type="sint"   indexed="true" stored="true" multiValued="true" />
</fields>
</code>```

The particular settings you want might be different, but this is the basic idea.

Consider the first dynamicField definition above. What it is saying is that you can dynamically add any fields ending _t and these fields will be treated as text fields, will be indexed and stored, and will be treated as a single value (as opposed to an array).

You can set up as many dynamic field names as you want, and there is no significance or convention to the names you use. Just set up one dynamicField definition for each data type that you might have.

Then, that's it. No need to define your specific fields, just use the suffixes you set up. So, for example if you used the fields above, you could do an insert with:

```<code>category_s = 'realty'
bedrooms_i = 4
</code>```

Or you could do an insert with:

```<code>category_s = 'shirts'
size_s = 'M'
</code>```

Title: Solr - schema help (product attributes)

Body:
You can set up dynamic fields in solr. In schema.xml, in the <fields> block, you can configure dynamic field definitions like this:

<fields>
    ...

    <dynamicField name="*_t"  type="text"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_s"  type="string" indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_sa" type="string" indexed="true" stored="true" multiValued="true" />
    <dynamicField name="*_d"  type="date"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_f"  type="sfloat" indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_i"  type="sint"   indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="*_ia" type="sint"   indexed="true" stored="true" multiValued="true" />
</fields>

The particular settings you want might be different, but this is the basic idea.

Consider the first dynamicField definition above. What it is saying is that you can dynamically add any fields ending _t and these fields will be treated as text fields, will be indexed and stored, and will be treated as a single value (as opposed to an array).

You can set up as many dynamic field names as you want, and there is no significance or convention to the names you use. Just set up one dynamicField definition for each data type that you might have.

Then, that's it. No need to define your specific fields, just use the suffixes you set up. So, for example if you used the fields above, you could do an insert with:

category_s = 'realty'
bedrooms_i = 4

Or you could do an insert with:

category_s = 'shirts'
size_s = 'M'


问:
Issue with "Pre-Launch report" Google play store
I recently uploaded my app to the Google Play Store but got this pre-launch report in some devices :

```<code>Issue: Crash of app com.mypackage running instrumentation

ComponentInfo{com.google.android.apps.mtaas.crawler/android.support.test.runner.AndroidJUnitRunner}
</code>```

How do solve it ?

答:
I got the answer in Google play Console Help

As of October 2017, the pre-launch report uses a new crawler to provide a more comprehensive review of your app. To do so, the pre-launch report must temporarily re-sign your APK within our test environment.

If you notice any issues, you can switch back to the previous testing process (which doesn't require APK re-signing):

Sign in to your Play Console.

Select an app.

Select Release
management > Pre-launch report > Settings.

In the 'Pre-launch report version' section, move the Opt-out switch to the right until it turns blue.

I have tested and all test passed for all devices, and no more crash for running instrumentation.

Body:
I recently uploaded my app to the Google Play Store but got this pre-launch report in some devices :

Issue: Crash of app com.mypackage running instrumentation

ComponentInfo{com.google.android.apps.mtaas.crawler/android.support.test.runner.AndroidJUnitRunner}

How do solve it ?


问:
IOIOActivity and AppCompactActivity
I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.

My code:

```<code>public class MainActivity extends AppCompatActivity  {

    private class Testing extends IOIOActivity {

        private ToggleButton button_;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button_ = (ToggleButton) findViewById(R.id.toggleButton);

        }

        class Looper extends BaseIOIOLooper {
            /** The on-board LED. */
            private DigitalOutput led_;

            @Override
            protected void setup() throws ConnectionLostException {
                showVersions(ioio_, "IOIO connected!");
                led_ = ioio_.openDigitalOutput(0, true);
                enableUi(true);
            }
 @Override
            public void loop() throws ConnectionLostException, InterruptedException {
                led_.write(!button_.isChecked());
                Thread.sleep(100);
            }

            @Override
            public void disconnected() {
                enableUi(false);
                toast("IOIO disconnected");
            }

            @Override
            public void incompatible() {
                showVersions(ioio_, "Incompatible firmware version!");
            }
        }

        @Override
        protected IOIOLooper createIOIOLooper() {
            return new Looper();
        }

        private void showVersions(IOIO ioio, String title) {
            toast(String.format("%s\n" +
                            "IOIOLib: %s\n" +
                            "Application firmware: %s\n" +
                            "Bootloader firmware: %s\n" +
                            "Hardware: %s",
                    title,
                    ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
                    ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
                    ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
                    ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
        }

        private void toast(final String message) {
            final Context context = this;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                }
            });
        }

        private int numConnected_ = 0;

        private void enableUi(final boolean enable) {
            // This is slightly trickier than expected to support a multi-IOIO use-case.
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (enable) {
                        if (numConnected_++ == 0) {
                            button_.setEnabled(true);
                        }
                    } else {
                        if (--numConnected_ == 0) {
                            button_.setEnabled(false);
                        }
                    }
                }
            });
        }
    }
}
</code>```

Thankss

答:
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.

Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507

```<code>public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);

public AppCompactIOIOActivity() {
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.helper_.create();
}

protected void onDestroy() {
    this.helper_.destroy();
    super.onDestroy();
}

protected void onStart() {
    super.onStart();
    this.helper_.start();
}

protected void onStop() {
    this.helper_.stop();
    super.onStop();
}

@SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if((intent.getFlags() & 268435456) != 0) {
        this.helper_.restart();
    }

}

protected IOIOLooper createIOIOLooper() {
    throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}

public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
    return this.createIOIOLooper();
}
</code>```

}

Then in your MainActivity

```<code>public class MainActivity extends AppCompactIOIOActivity {

    private ToggleButton button_;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_ = (ToggleButton) findViewById(R.id.toggleButton);

    }
    class Looper extends BaseIOIOLooper {
        /** The on-board LED. */
        private DigitalOutput led_;

        @Override
        protected void setup() throws ConnectionLostException {
            showVersions(ioio_, "IOIO connected!");
            led_ = ioio_.openDigitalOutput(0, true);
            enableUi(true);
        }

        @Override
        public void loop() throws ConnectionLostException, InterruptedException {
            led_.write(!button_.isChecked());
            Thread.sleep(100);
        }

        @Override
        public void disconnected() {
            enableUi(false);
            toast("IOIO disconnected");
        }

        @Override
        public void incompatible() {
            showVersions(ioio_, "Incompatible firmware version!");
        }
    }

    @Override
    protected IOIOLooper createIOIOLooper() {
        return new Looper();
    }

    private void showVersions(IOIO ioio, String title) {
        toast(String.format("%s\n" +
                        "IOIOLib: %s\n" +
                        "Application firmware: %s\n" +
                        "Bootloader firmware: %s\n" +
                        "Hardware: %s",
                title,
                ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
                ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
                ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
                ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
    }

    private void toast(final String message) {
        final Context context = this;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }
        });
    }

    private int numConnected_ = 0;

    private void enableUi(final boolean enable) {
        // This is slightly trickier than expected to support a multi-IOIO use-case.
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (enable) {
                    if (numConnected_++ == 0) {
                        button_.setEnabled(true);
                    }
                } else {
                    if (--numConnected_ == 0) {
                        button_.setEnabled(false);
                    }
                }
            }
        });
    }
}
</code>```

Don't forget to add your resources and dependances from IOIO developers. Good luck!

Title: IOIOActivity and AppCompactActivity

Body:
I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.

My code:

public class MainActivity extends AppCompatActivity  {

    private class Testing extends IOIOActivity {

        private ToggleButton button_;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button_ = (ToggleButton) findViewById(R.id.toggleButton);

        }

        class Looper extends BaseIOIOLooper {
            /** The on-board LED. */
            private DigitalOutput led_;

            @Override
            protected void setup() throws ConnectionLostException {
                showVersions(ioio_, "IOIO connected!");
                led_ = ioio_.openDigitalOutput(0, true);
                enableUi(true);
            }
 @Override
            public void loop() throws ConnectionLostException, InterruptedException {
                led_.write(!button_.isChecked());
                Thread.sleep(100);
            }

            @Override
            public void disconnected() {
                enableUi(false);
                toast("IOIO disconnected");
            }

            @Override
            public void incompatible() {
                showVersions(ioio_, "Incompatible firmware version!");
            }
        }

        @Override
        protected IOIOLooper createIOIOLooper() {
            return new Looper();
        }

        private void showVersions(IOIO ioio, String title) {
            toast(String.format("%s\n" +
                            "IOIOLib: %s\n" +
                            "Application firmware: %s\n" +
                            "Bootloader firmware: %s\n" +
                            "Hardware: %s",
                    title,
                    ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
                    ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
                    ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
                    ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
        }

        private void toast(final String message) {
            final Context context = this;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                }
            });
        }

        private int numConnected_ = 0;

        private void enableUi(final boolean enable) {
            // This is slightly trickier than expected to support a multi-IOIO use-case.
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (enable) {
                        if (numConnected_++ == 0) {
                            button_.setEnabled(true);
                        }
                    } else {
                        if (--numConnected_ == 0) {
                            button_.setEnabled(false);
                        }
                    }
                }
            });
        }
    }
}

Thankss

Body:
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.

Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507

public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);

public AppCompactIOIOActivity() {
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.helper_.create();
}

protected void onDestroy() {
    this.helper_.destroy();
    super.onDestroy();
}

protected void onStart() {
    super.onStart();
    this.helper_.start();
}

protected void onStop() {
    this.helper_.stop();
    super.onStop();
}

@SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if((intent.getFlags() & 268435456) != 0) {
        this.helper_.restart();
    }

}

protected IOIOLooper createIOIOLooper() {
    throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}

public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
    return this.createIOIOLooper();
}

}

Then in your MainActivity

public class MainActivity extends AppCompactIOIOActivity {

    private ToggleButton button_;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_ = (ToggleButton) findViewById(R.id.toggleButton);

    }
    class Looper extends BaseIOIOLooper {
        /** The on-board LED. */
        private DigitalOutput led_;

        @Override
        protected void setup() throws ConnectionLostException {
            showVersions(ioio_, "IOIO connected!");
            led_ = ioio_.openDigitalOutput(0, true);
            enableUi(true);
        }

        @Override
        public void loop() throws ConnectionLostException, InterruptedException {
            led_.write(!button_.isChecked());
            Thread.sleep(100);
        }

        @Override
        public void disconnected() {
            enableUi(false);
            toast("IOIO disconnected");
        }

        @Override
        public void incompatible() {
            showVersions(ioio_, "Incompatible firmware version!");
        }
    }

    @Override
    protected IOIOLooper createIOIOLooper() {
        return new Looper();
    }

    private void showVersions(IOIO ioio, String title) {
        toast(String.format("%s\n" +
                        "IOIOLib: %s\n" +
                        "Application firmware: %s\n" +
                        "Bootloader firmware: %s\n" +
                        "Hardware: %s",
                title,
                ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
                ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
                ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
                ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
    }

    private void toast(final String message) {
        final Context context = this;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }
        });
    }

    private int numConnected_ = 0;

    private void enableUi(final boolean enable) {
        // This is slightly trickier than expected to support a multi-IOIO use-case.
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (enable) {
                    if (numConnected_++ == 0) {
                        button_.setEnabled(true);
                    }
                } else {
                    if (--numConnected_ == 0) {
                        button_.setEnabled(false);
                    }
                }
            }
        });
    }
}

Don't forget to add your resources and dependances from IOIO developers. Good luck!


问:
Output 'NaN' Incrementing state value by using ReactJS
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

```<code>class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}
</code>```

And the Render():

```<code> render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>
    <p id='num'>{this.state.num_quantity}</p>
    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}
</code>```

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.

答:
I would refactor your component's code to satisfy next requirements:

1) state are being mutated via callback-based this.setState to avoid situation when there are some other state changes that could not be taken into the account during this.setState({num_quantity: this.state.num_quantity++}); assignment;

2) render method is wrapped with a single root element (also it could be an array of elements if it is React v16);

3) the main point (thanks to @Dane) – providing class methods for the handlers instead of property functions (replacing the arrow functions) – to make a constructor instance this bindings work.

```<code>constructor(props) {
  super(props)
  this.buttonplus_quantity = this.buttonplus_quantity.bind(this)
  this.buttonminus_quantity = this.buttonminus_quantity.bind(this)
  this.state= {
      num_quantity :0
  }
}

buttonplus_quantity() {
  this.setState(prevState => ({
    num_quantity: prevState.num_quantity++
  }));
}

buttonminus_quantity() {
  this.setState(prevState => ({
    num_quantity: prevState.num_quantity--
  }));
}

 render() {
   return (
    <span>
      <Button onClick={this.buttonminus_quantity} value="-">-</Button>
      <p id='num'>{this.state.num_quantity}</p>
      <Button onClick={this.buttonplus_quantity} value="+">+</Button>
    </span>
  );
}
</code>```

Body:
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}

And the Render():

 render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>

{this.state.num_quantity}

    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.

Body:
I would refactor your component's code to satisfy next requirements:

1) state are being mutated via callback-based this.setState to avoid situation when there are some other state changes that could not be taken into the account during this.setState({num_quantity: this.state.num_quantity++}); assignment;

2) render method is wrapped with a single root element (also it could be an array of elements if it is React v16);

3) the main point (thanks to @Dane) – providing class methods for the handlers instead of property functions (replacing the arrow functions) – to make a constructor instance this bindings work.

constructor(props) {
  super(props)
  this.buttonplus_quantity = this.buttonplus_quantity.bind(this)
  this.buttonminus_quantity = this.buttonminus_quantity.bind(this)
  this.state= {
      num_quantity :0
  }
}

buttonplus_quantity() {
  this.setState(prevState => ({
    num_quantity: prevState.num_quantity++
  }));
}

buttonminus_quantity() {
  this.setState(prevState => ({
    num_quantity: prevState.num_quantity--
  }));
}

 render() {
   return (
    <span>
      <Button onClick={this.buttonminus_quantity} value="-">-</Button>
      <p id='num'>{this.state.num_quantity}</p>
      <Button onClick={this.buttonplus_quantity} value="+">+</Button>
    </span>
  );
}


问:
NuGet: How can I append an auto-incrememted build number to my NuGet package version ONLY when $(ConfigurationName) == Debug?
I'm trying to accomplish this using Visual Studio post-build events.

What I want to happen:

When I build in debug, I want to create a .nupkg like MyProject.1.0.0.xxxx-ci.nupkg, where xxxx is some auto-incrementing build number, and 1.0.0 is defined in my .nuspec file.

However when I build release, I want just a simple MyProject.1.0.0.nupkg using my nuspec.

I have a Development NuGet feed, and a Production NuGet feed that I'd like to push these to after build, which is why I ONLY want this extra build number to show up in Debug.

I've almost figured this out using [assembly: AssemblyVersion("1.0.0.*")] in AssemblyInfo.cs, but then my release build also gets that build number tacked on, and I don't want that.

Here's the code I have in post-build right now using just the nuspec and not AssemblyInfo.cs:

```<code>if "$(ConfigurationName)" == "Debug" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec" -Suffix ci
nuget push -Source http://myfeed.com/nuget/NuGet-Development "*.nupkg" )

if "$(ConfigurationName)" == "Release" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec"
nuget push -Source http://myfeed.com/nuget/NuGet-Production "*.nupkg" )
</code>```

Is there some sort of way I can use -Version to do this?

I'm very very new to this all, so there's a good chance I'm just missing simple things, or have the wrong commands all together :)

Sorry in advance if my question isn't clear!

答:
Is there some sort of way I can use -Version to do this?

The answer is yes. You can use the version in the [assembly: AssemblyVersion("1.0.0.*")] when you using the .nuspec file. Just add the version to the macro, then you can use this macro in the build event like:@(VersionNumber).

To accomplish this, unload your project. Then at the very end of the project, just before the end-tag </Project>, place below scripts:

```<code><PropertyGroup>
   <PostBuildEventDependsOn>
     $(PostBuildEventDependsOn);
     PostBuildMacros;
   </PostBuildEventDependsOn>
</PropertyGroup>

<Target Name="PostBuildMacros">
  <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
    <Output TaskParameter="Assemblies" ItemName="Targets" />
  </GetAssemblyIdentity>
  <ItemGroup>
    <VersionNumber Include="@(Targets->'%(Version)')"/>
  </ItemGroup>
</Target>
</code>```

Now we could use this macro: @(VersionNumber) in the build event as following:

```<code>if "$(ConfigurationName)" == "Debug" (
nuget.exe pack "$(ProjectDir)$(ProjectName).nuspec" -Suffix @(VersionNumber)-ci)
nuget push -Source http://myfeed.com/nuget/NuGet-Development "*.nupkg" )

if "$(ConfigurationName)" == "Release" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec"
nuget push -Source http://myfeed.com/nuget/NuGet-Production "*.nupkg" )
</code>```

The result when you build in Debug with AssemblyVersion("2.0.0.0"):

When you build in Release:

Body:
I'm trying to accomplish this using Visual Studio post-build events.

What I want to happen:

When I build in debug, I want to create a .nupkg like MyProject.1.0.0.xxxx-ci.nupkg, where xxxx is some auto-incrementing build number, and 1.0.0 is defined in my .nuspec file.

However when I build release, I want just a simple MyProject.1.0.0.nupkg using my nuspec.

I have a Development NuGet feed, and a Production NuGet feed that I'd like to push these to after build, which is why I ONLY want this extra build number to show up in Debug.

I've almost figured this out using [assembly: AssemblyVersion("1.0.0.*")] in AssemblyInfo.cs, but then my release build also gets that build number tacked on, and I don't want that.

Here's the code I have in post-build right now using just the nuspec and not AssemblyInfo.cs:

if "$(ConfigurationName)" == "Debug" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec" -Suffix ci
nuget push -Source http://myfeed.com/nuget/NuGet-Development "*.nupkg" )

if "$(ConfigurationName)" == "Release" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec"
nuget push -Source http://myfeed.com/nuget/NuGet-Production "*.nupkg" )

Is there some sort of way I can use -Version to do this?

I'm very very new to this all, so there's a good chance I'm just missing simple things, or have the wrong commands all together :)

Sorry in advance if my question isn't clear!

Body:
Is there some sort of way I can use -Version to do this?

The answer is yes. You can use the version in the [assembly: AssemblyVersion("1.0.0.*")] when you using the .nuspec file. Just add the version to the macro, then you can use this macro in the build event like:@(VersionNumber).

To accomplish this, unload your project. Then at the very end of the project, just before the end-tag </Project>, place below scripts:

<PropertyGroup>
   <PostBuildEventDependsOn>
     $(PostBuildEventDependsOn);
     PostBuildMacros;
   </PostBuildEventDependsOn>
</PropertyGroup>

<Target Name="PostBuildMacros">
  <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
    <Output TaskParameter="Assemblies" ItemName="Targets" />
  </GetAssemblyIdentity>
  <ItemGroup>
    <VersionNumber Include="@(Targets->'%(Version)')"/>
  </ItemGroup>
</Target>

Now we could use this macro: @(VersionNumber) in the build event as following:

if "$(ConfigurationName)" == "Debug" (
nuget.exe pack "$(ProjectDir)$(ProjectName).nuspec" -Suffix @(VersionNumber)-ci)
nuget push -Source http://myfeed.com/nuget/NuGet-Development "*.nupkg" )

if "$(ConfigurationName)" == "Release" (
nuget pack "$(ProjectDir)$(ProjectName).nuspec"
nuget push -Source http://myfeed.com/nuget/NuGet-Production "*.nupkg" )

The result when you build in Debug with AssemblyVersion("2.0.0.0"):

When you build in Release: