问:
Webpack code splitting
Im trying to set up my project with webpack, i've read about code-splitting and i am trying to make two separate bundles, one for the actual application code and the other for libraries and frameworks. So my webpack config looks like this:

```<code>entry: {
    app: './app/index.js',
    vendor: './app/vendor.js'
},
output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public/js')
},

watch: true,

module: {
    rules: [{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            use: 'css-loader'
        })
    }]
},

plugins: [
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
    })
]
</code>```

in my vendor.js bundle i have only one line:

```<code> import moment from 'moment';
</code>```

And when i try to use it in my app.js file it tells me, that moment is not defined. So, the thing that i don't get, do bundles have common scope or not? If not, then how can i access variables that i've exported in another bundle and if i can't, then what's even the point of having the vendor bundle like described here https://webpack.js.org/guides/code-splitting-libraries/ ?

答:
I see the problem, and it's not related with code splitting. There are different ways to achieve this, depending on your specific case:

Require vendor.js in index.js:

vendor.js

```<code>export default moment from 'moment';
</code>```

index.js

```<code>var moment = require('vendor.js');
console.log(moment());
</code>```

Using import loaders:

The imports loader allows you to use modules that depend on specific global variables. This is useful for third-party modules that rely on global variables like $ or this being the window object. The imports loader can add the necessary require('whatever') calls, so those modules work with webpack.

```<code>require("imports-loader?$=moment,angular!./index.js");
</code>```

Via plugins:

You can expose momentJS to the windows object via plugins, so you can access from index.js as window.moment.

```<code>new webpack.ProvidePlugin({
    "window.moment": "moment"
}),
</code>```

Title: Webpack code splitting

Body:
Im trying to set up my project with webpack, i've read about code-splitting and i am trying to make two separate bundles, one for the actual application code and the other for libraries and frameworks. So my webpack config looks like this:

entry: {
    app: './app/index.js',
    vendor: './app/vendor.js'
},
output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public/js')
},

watch: true,

module: {
    rules: [{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            use: 'css-loader'
        })
    }]
},

plugins: [
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
    })
]

in my vendor.js bundle i have only one line:

 import moment from 'moment';

And when i try to use it in my app.js file it tells me, that moment is not defined. So, the thing that i don't get, do bundles have common scope or not? If not, then how can i access variables that i've exported in another bundle and if i can't, then what's even the point of having the vendor bundle like described here https://webpack.js.org/guides/code-splitting-libraries/ ?

Body:
I see the problem, and it's not related with code splitting. There are different ways to achieve this, depending on your specific case:

Require vendor.js in index.js:

vendor.js

export default moment from 'moment';

index.js

var moment = require('vendor.js');
console.log(moment());

Using import loaders:

The imports loader allows you to use modules that depend on specific global variables. This is useful for third-party modules that rely on global variables like $ or this being the window object. The imports loader can add the necessary require('whatever') calls, so those modules work with webpack.

require("imports-loader?$=moment,angular!./index.js");

Via plugins:

You can expose momentJS to the windows object via plugins, so you can access from index.js as window.moment.

new webpack.ProvidePlugin({
    "window.moment": "moment"
}),


来源: stackexchange

问:
In Mercurial how do I extract a single file's changes from a Changeset to apply to another branch?
I have a large commit of many files on one branch, I need to transfer the modifications of a single file in that changeset to another branch. How can I do this? I am mostly using TortoiseHg but commandline solutions are also fine.

If I go to the changeset in TortoiseHg and select the file I can see the diffs I want to transfer, but not a way to actually apply them.

答:
You can get the patch for just that file using:

```<code>hg log -r THEREVISIONWITHLOTSOFCHANGES -p -I path/to/justthatfile > justthatfile.patch
</code>```

which you can then import on whatever branch you want by doing:

```<code>hg update anotherbranch
hg import --no-commit justthatfile.patch
hg commit
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can get the patch for just that file using:

hg log -r THEREVISIONWITHLOTSOFCHANGES -p -I path/to/justthatfile > justthatfile.patch

which you can then import on whatever branch you want by doing:

hg update anotherbranch
hg import --no-commit justthatfile.patch
hg commit

ContentLicense: CC BY-SA 3.0


问:
Installing all CRAN packages that are not already installed?
The following R commands will install all CRAN packages:

```<code>availablePackages <- available.packages()[,1]
install.packages(availablePackages)
</code>```

And the following command will list all installed packages:

```<code>installedPackages <- .packages(all.available = TRUE)
</code>```

My question is: How do I instruct R to install all CRAN packages that are not already installed?

答:
I've tested this and it works

```<code>availablePackages=available.packages()
availablePackages<-as.vector(availablePackages[,1])
installedPackages=.packages(all.available = TRUE)
missedPackages<-setdiff(availablePackages, installedPackages)
for (i in 1:length(missedPackages))
{
pkgName <- missedPackages[i]
install.packages(pkgName)
}
print("END")
</code>```

Regards

Body:
The following R commands will install all CRAN packages:

availablePackages <- available.packages()[,1]
install.packages(availablePackages)

And the following command will list all installed packages:

installedPackages <- .packages(all.available = TRUE)

My question is: How do I instruct R to install all CRAN packages that are not already installed?

Body:
I've tested this and it works

availablePackages=available.packages()
availablePackages<-as.vector(availablePackages[,1])
installedPackages=.packages(all.available = TRUE)
missedPackages<-setdiff(availablePackages, installedPackages)
for (i in 1:length(missedPackages))
{
pkgName <- missedPackages[i]
install.packages(pkgName)
}
print("END")

Regards


问:
grouping and simplifying multiple if conditions / bash
I have multiple If conditions to to run at the beginning of the script

```<code>if blah; then
echo "hop"
fi
if [ ! -f blah-blah ]; then
echo "hop-hop"
else
echo "hip-hop-hap"
fi
if [ $? -eq 0 ]; then
echo "hip-hop"
fi
</code>```

each of this conditions
are separate from each other, and I have them 7-8
so I'm thinking if there is some way to group them...
I was thinking to use
elif , but elif will stop checking conditions if one of them is truth,
any suggestion would be ppreciated

答:
If what you are hoping for is shorter code, you could do something like this :

```<code>blah && echo "hop"
[ -f "blah-blah" ] && echo "hip-hop-hap" || echo "hop-hop"
[ $? = 0 ] && echo "hip-hop"
</code>```

This is not "simpler" in the logical sense, but it is more concise.

Please note that I removed the ! from the test and switched the resulting statements as a small optimization.

Please note, however, that if you want to perform any kind of error checking or explicit handling (i.e. trap ... ERR, set -e), then using logical operators is going to interfere with that and you will not be able to tell the difference between a bug in your script and a command that fails for "good reasons" (i.e. attempting to delete a non-existing file).  You are probably mostly safe if you restrict yourself to echo statements, or if, like most shell programmers, you allow the shell to simply ignore failed statements (which is not, in my opinion, a good way to build predictable and reliable shell code).

Body:
I have multiple If conditions to to run at the beginning of the script

if blah; then
echo "hop"
fi
if [ ! -f blah-blah ]; then
echo "hop-hop"
else
echo "hip-hop-hap"
fi
if [ $? -eq 0 ]; then
echo "hip-hop"
fi

each of this conditions
are separate from each other, and I have them 7-8
so I'm thinking if there is some way to group them...
I was thinking to use
elif , but elif will stop checking conditions if one of them is truth,
any suggestion would be ppreciated

Body:
If what you are hoping for is shorter code, you could do something like this :

blah && echo "hop"
[ -f "blah-blah" ] && echo "hip-hop-hap" || echo "hop-hop"
[ $? = 0 ] && echo "hip-hop"

This is not "simpler" in the logical sense, but it is more concise.

Please note that I removed the ! from the test and switched the resulting statements as a small optimization.

Please note, however, that if you want to perform any kind of error checking or explicit handling (i.e. trap ... ERR, set -e), then using logical operators is going to interfere with that and you will not be able to tell the difference between a bug in your script and a command that fails for "good reasons" (i.e. attempting to delete a non-existing file).  You are probably mostly safe if you restrict yourself to echo statements, or if, like most shell programmers, you allow the shell to simply ignore failed statements (which is not, in my opinion, a good way to build predictable and reliable shell code).


问:
PHP - requiring bootstrap once for all files
I have installed composer to autoload classes, and made a bootstrap file for the app, where I have this line:

```<code>require __DIR__ . '/../vendor/autoload.php';
</code>```

Now, since I have 2 files in my app, for each I need to add this at the beginning of the file, in order to load the classes:

```<code>require 'app/bootstrap.php';
</code>```

Is there a way of avoiding this, and having only one place, where I would pull all the classes for my files?

答:
Is there a way of avoiding this, and having only one place, where I would pull all the classes for my files?

There's auto_prepend_file configuration directive but you do NOT want to use it.  The common practice is to have one bootstrap file like you have and include it whenever neccessary.

Body:
I have installed composer to autoload classes, and made a bootstrap file for the app, where I have this line:

require __DIR__ . '/../vendor/autoload.php';

Now, since I have 2 files in my app, for each I need to add this at the beginning of the file, in order to load the classes:

require 'app/bootstrap.php';

Is there a way of avoiding this, and having only one place, where I would pull all the classes for my files?


问:
"Cannot read property 'length' of undefined" when calling function
I get the following error when I click my refresh button:

```<code>caught TypeError: Cannot read property 'length' of undefined
at getRandomImage (index.html:85)
at HTMLInputElement.onclick (index.html:11)
</code>```

See this snippet:

var myArray = new Array();

getRandomImage(myArray, "");

function getRandomImage(imgAr, path) {
    path = path || 'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '';
    document.write(imgStr); document.close();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <INPUT TYPE="button" onClick="getRandomImage()" VALUE="More MEME plz">
    </INPUT>
</form></code>```

It works fine with the button refreshing the page but most of the people on my website have bad internet which takes a long time to reload the page so only loading the image and not the background and text and unnecessary things.

Link to github REPO: https://github.com/odude102/1-800MemeLine/blob/master/index.html

答:
This is not the best solution, but it fixes your problem: </p>

```<code>var myArray = new Array();
var path =  'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/';
getRandomImage();

function getRandomImage() {
  var num = Math.floor( Math.random() * myArray.length );
  var img = myArray[ num ];
  var imgStr = '<img src="' + path + img + '" alt = "">';
  document.write(imgStr);
  document.close();
}
</code>```

Body:
I get the following error when I click my refresh button:

caught TypeError: Cannot read property 'length' of undefined
at getRandomImage (index.html:85)
at HTMLInputElement.onclick (index.html:11)

See this snippet:

var myArray = new Array();

getRandomImage(myArray, "");

function getRandomImage(imgAr, path) {
    path = path || 'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '';
    document.write(imgStr); document.close();
}

<form>
    <INPUT TYPE="button" onClick="getRandomImage()" VALUE="More MEME plz">
    </INPUT>
</form>

It works fine with the button refreshing the page but most of the people on my website have bad internet which takes a long time to reload the page so only loading the image and not the background and text and unnecessary things.

Link to github REPO: https://github.com/odude102/1-800MemeLine/blob/master/index.html

Body:
This is not the best solution, but it fixes your problem:

var myArray = new Array();
var path =  'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/';
getRandomImage();

function getRandomImage() {
  var num = Math.floor( Math.random() * myArray.length );
  var img = myArray[ num ];
  var imgStr = '<img src="' + path + img + '" alt = "">';
  document.write(imgStr);
  document.close();
}


问:
Is it possible to use a single task in multiple DAGS in airflow?
I have a task_a that I want to use in DAG_1 and DAG_2. Is this possible in airflow?

```<code>task_a = SomeOperator(
task_id='some_id',
bash_command='some_command',
#instead of just
dag= DAG_1 # I want to assign this task to multiple dags
#dag=assign_multiple_dags_here(DAG_1 and DAG_2)
)
</code>```

Is this possible?

答:
you could always do something with partial and then assign it to 2 different dags:

```<code>from functools import partial
task_template = partial(SomeOperator, some_id='id', some_command='cmd')
task_template(dag=dag1)
task_template(dag=dag2)
</code>```

you could also just create a function that does it:

```<code>def create_task(dag):
    return SomeOperator(some_id='id', some_command='cmd', dag=dag)

for d in (dag1, dag2):
    create_task(d)
</code>```

Body:
I have a task_a that I want to use in DAG_1 and DAG_2. Is this possible in airflow?

task_a = SomeOperator(
task_id='some_id',
bash_command='some_command',
#instead of just
dag= DAG_1 # I want to assign this task to multiple dags
#dag=assign_multiple_dags_here(DAG_1 and DAG_2)
)

Is this possible?

Body:
you could always do something with partial and then assign it to 2 different dags:

from functools import partial
task_template = partial(SomeOperator, some_id='id', some_command='cmd')
task_template(dag=dag1)
task_template(dag=dag2)

you could also just create a function that does it:

def create_task(dag):
    return SomeOperator(some_id='id', some_command='cmd', dag=dag)

for d in (dag1, dag2):
    create_task(d)


问:
RGB average of circles
I'm using OpenCV and PIL in Python. I have 96 circles detected with their center coordinates and radios. I need the average RGB from each circles.

Each circle has 6000 pixels, so I thinks iterate one to one it is not efficient.

How can I extract the average RGB from each circle?
I am ready to use any other library if it suits my use-case.

答:
Finally I get it, this is the solution:</p>

```<code>circle_img = np.zeros((color_img.shape[0],color_img.shape[1]), np.uint8) #Creamos mascara (matriz de ceros) del tamano de la imagen original
cv2.circle(circle_img,(x_center,y_center),radio,(255,255,255),-1) #Pintamos los circulos en la mascara
datos_rgb = cv2.mean(color_img, mask=circle_img)[::-1]
</code>```

Title: RGB average of circles

Body:
Finally I get it, this is the solution:

circle_img = np.zeros((color_img.shape[0],color_img.shape[1]), np.uint8) #Creamos mascara (matriz de ceros) del tamano de la imagen original
cv2.circle(circle_img,(x_center,y_center),radio,(255,255,255),-1) #Pintamos los circulos en la mascara
datos_rgb = cv2.mean(color_img, mask=circle_img)[::-1]


问:
Javascript from Module to Class
I have a javascript module which looks like this:

```<code>var myModule = {

    settings: {
        myage: 25
    },

    init: function() {

        //init code here

    },

    someFunction1: function(param1) {

        //function code here

    },

    someFunction2: function() {

       myModule.someFunction1(myparam);

    }

}
</code>```

I like the structure of modules because it can keep related functions together.

```<code>My question is...
</code>```

Is it bad coding practice to use modules and not classes?

How can I convert the code above to a class? Would it be very hard?

答:
Is is bad coding practice to use modules and not classes?

No!

At least if your module is immutable. If you are dynamically modifying it, you essentially have introduced global state, and that is a bad practise. Also I'm not sure whether these "settings" are supposed to be global or not - if there is any reason (and be it for testing only) to have multiple module instances with different settings, then a class would be appropriate.

How can I convert the code above to a class? Would it be very hard?

Don't when you don't need to. But no, it wouldn't be very hard:

```<code>class MyModule {
    constructor() {
        this.settings: {
            myage: 25
        };
        //init code here
    }
    someFunction1(param1) {
        //function code here
    }
    someFunction2() {
        this.someFunction1(myparam);
    }
}
</code>```

Instead of doing myModule.init(), you'd call var myModule = new MyModule();.

Title: Javascript from Module to Class

Body:
I have a javascript module which looks like this:

var myModule = {

    settings: {
        myage: 25
    },

    init: function() {

        //init code here

    },

    someFunction1: function(param1) {

        //function code here

    },

    someFunction2: function() {

       myModule.someFunction1(myparam);

    }

}

I like the structure of modules because it can keep related functions together.

My question is...

Is it bad coding practice to use modules and not classes?

How can I convert the code above to a class? Would it be very hard?

Body:
Is is bad coding practice to use modules and not classes?

No!

At least if your module is immutable. If you are dynamically modifying it, you essentially have introduced global state, and that is a bad practise. Also I'm not sure whether these "settings" are supposed to be global or not - if there is any reason (and be it for testing only) to have multiple module instances with different settings, then a class would be appropriate.

How can I convert the code above to a class? Would it be very hard?

Don't when you don't need to. But no, it wouldn't be very hard:

class MyModule {
    constructor() {
        this.settings: {
            myage: 25
        };
        //init code here
    }
    someFunction1(param1) {
        //function code here
    }
    someFunction2() {
        this.someFunction1(myparam);
    }
}

Instead of doing myModule.init(), you'd call var myModule = new MyModule();.


问:
Android Google Maps [React Native?] "API key not found. Check that.." Error
Hi I am new to react native. I just made a new application. When I don't have a map component in my application and my other components work fine. However when I add this in my render(){return(..

```<code>  <MapView
    ref={ref => { this.map = ref; }}
    mapType={MAP_TYPES.TERRAIN}
    style={styles.map}
    initialRegion={this.state.region}
    onRegionChange={region => this.onRegionChange(region)}
  />
</code>```

I get the error:

I did a search of the project folder to find a AndroidMainfest.xml and I found a couple. I changed the one in: \android\app\build\intermediates\manifests\full\debug

from this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- Include required permissions for Google Maps API to run. -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>
</code>```

To this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- Include required permissions for Google Maps API to run. -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC-V3J1Wz4wqgHqrqffIeZqhVM0gDfTsIg" />

    </application>

</manifest>
</code>```

I even just tried it with only the meta-deta API Key one.

Some other information:
I got the API key from here: https://developers.google.com/maps/documentation/android-api/signup.

After I changed it I just saved the file and restarted the simulator restarted the app with react-native run-android in the directory with command prompt. I'm not sure if this is the correct way to "Rebuild" the project.

I am using the Airbnb react-native-maps component that Facebook recommends using: https://github.com/airbnb/react-native-maps

I did the npm install react-native-maps --save and react-native link react-native-maps recently because this is a brand new project (error in the new version they provide or something?). The emulator is android 7.1.1.

Here is the SDK Manager for the android studio simulator:

答:
You are doing the correct change of adding the API_KEY element. However, edit the file at location:

```<code>\android\app\\**src**\main (Source directory)
</code>```

instead of

```<code>\android\app\\**build**\intermediates\manifests\full\debug (Build directory)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi I am new to react native. I just made a new application. When I don't have a map component in my application and my other components work fine. However when I add this in my render(){return(..

  <MapView
    ref={ref => { this.map = ref; }}
    mapType={MAP_TYPES.TERRAIN}
    style={styles.map}
    initialRegion={this.state.region}
    onRegionChange={region => this.onRegionChange(region)}
  />

I get the error:

I did a search of the project folder to find a AndroidMainfest.xml and I found a couple. I changed the one in: \android\app\build\intermediates\manifests\full\debug

from this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

To this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC-V3J1Wz4wqgHqrqffIeZqhVM0gDfTsIg" />

    </application>

</manifest>

I even just tried it with only the meta-deta API Key one.

Some other information:
I got the API key from here: https://developers.google.com/maps/documentation/android-api/signup.

After I changed it I just saved the file and restarted the simulator restarted the app with react-native run-android in the directory with command prompt. I'm not sure if this is the correct way to "Rebuild" the project.

I am using the Airbnb react-native-maps component that Facebook recommends using: https://github.com/airbnb/react-native-maps

I did the npm install react-native-maps --save and react-native link react-native-maps recently because this is a brand new project (error in the new version they provide or something?). The emulator is android 7.1.1.

Here is the SDK Manager for the android studio simulator:

Body:
You are doing the correct change of adding the API_KEY element. However, edit the file at location:

\android\app\\**src**\main (Source directory)

instead of

\android\app\\**build**\intermediates\manifests\full\debug (Build directory)


问:
restrict access to the second form page
Helloo, I have a mutistep form functionality where
in "Step1" ( page 1 ) i have a form with three radioButton

And in step 2 (page2 ) I have another form.
So, My problem is that I want to restrict access to page2 via URL like if I type in Browser Addressbar : localhost/page1.php then it should load page1.php  but when I write localhost/page2.php then it should restrict user to have access for page2  and I would like to be redirected to localhost/page1.php

so i tried this :

page1 :

```<code>  <form class="type" action="page2.php" method="post">
   <label style="text-align:center;"> Type de compte :  </label>
                </br> </br>
   <input  type="radio" name="typeCompte" value="enseig"  required>
                 Enseignant </br>
   <input type="radio" name="typeCompte" value="etud" required>
                  Etudiant </br>
   <input type="radio"  name="typeCompte" value="admin" required>
                  Adminstrateur </br>
    </br></br>
   <input type="submit" class="make" name="submit" value="Valider">
   </form>

   <?php
    if(isset($_POST['submit']))
    {
       $_SESSION['log']=1;
    }
   ?>
</code>```

page 2 :

```<code> <?php
      session_start();
      if($_SESSION['log']!=1)
          header("location: page1.php");//redirecting to first page
 ?>
</code>```

答:
Try putting session variable as bool like...

In Page1.php

```<code><?php
    session_start();
    if($_POST['submit']){
        $_SESSION['log'] = "true";
         header("Location: page2.php");
  }
  ?>
</code>```

Then In Page2.php

```<code> if(!isset($_SESSION['log']) && $_SESSION['log'] == "false"){
     //send them back
     header("Location: page1.php");
  }
 else{
     //your logic if any.
  }
</code>```

I think in Php session might be working on true false basis only..

Title: restrict access to the second form page

Body:
Helloo, I have a mutistep form functionality where
in "Step1" ( page 1 ) i have a form with three radioButton

And in step 2 (page2 ) I have another form.
So, My problem is that I want to restrict access to page2 via URL like if I type in Browser Addressbar : localhost/page1.php then it should load page1.php  but when I write localhost/page2.php then it should restrict user to have access for page2  and I would like to be redirected to localhost/page1.php

so i tried this :

page1 :

  <form class="type" action="page2.php" method="post">
    Type de compte :

   <input  type="radio" name="typeCompte" value="enseig"  required>
                 Enseignant

   <input type="radio" name="typeCompte" value="etud" required>
                  Etudiant

   <input type="radio"  name="typeCompte" value="admin" required>
                  Adminstrateur

   <input type="submit" class="make" name="submit" value="Valider">
   </form>

   <?php
    if(isset($_POST['submit']))
    {
       $_SESSION['log']=1;
    }
   ?>

page 2 :

 <?php
      session_start();
      if($_SESSION['log']!=1)
          header("location: page1.php");//redirecting to first page
 ?>

Body:
Try putting session variable as bool like...

In Page1.php

<?php
    session_start();
    if($_POST['submit']){
        $_SESSION['log'] = "true";
         header("Location: page2.php");
  }
  ?>

Then In Page2.php

 if(!isset($_SESSION['log']) && $_SESSION['log'] == "false"){
     //send them back
     header("Location: page1.php");
  }
 else{
     //your logic if any.
  }

I think in Php session might be working on true false basis only..


问:
Temporarily Stop One Function Execution with setTimeOut() when a Button is Clicked
I have an animation triggered by a scroll event, which makes a menu slide out of view. There is also a button that when clicked brings the menu back into view.

Because the menu can be closed by scrolling, when the user clicks the button to bring the menu in, if they scroll during this period of the animation, the menu disappears again without the animation completing.

I have put together a simplified version of the animation here http://codepen.io/emilychews/pen/evbzMQ

I need to temporarily prevent the scroll function working after the button is clicked, which I'm assuming would be best done with the setTimeout() method on the click function?  I've tried a number of things but can't seem to solve it/ get it to work.

Any help would be awesome.  For quick reference as well the code is below

JQUERY

```<code>jQuery(document).ready(function($){

    // slide menu to left on scroll
    function hideOnScroll() {
      $(window).scroll(function() {
        if ( $(document).scrollTop() > 1) {

          $('.menubox').css('left', '-25%');

      }

    });

  }

  hideOnScroll(); // call hideOnScroll function

  // click handler to bring menu back in
  $('.mybutton').on('click', function() {

      $('.menubox').css('left', '0%');

      var scrollPause = setTimeout(hideOnScroll, 2000)  // temporarily pause hideOnScroll function

    });

}); //end of jQuery
</code>```

CSS

```<code>body {
 margin: 0;
 padding: 0;
 height: 200vh;}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 2s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}
</code>```

HTML

```<code><div class="menubox">Menu Box</div>

<button class="mybutton">Click to bring back menu</button>
</code>```

** Also please note I've simplified the animation for the sake of the forum, the actual animation function contains Greensock code, but I didn't want to include this in case it confused the issue. I can't therefore just use the .addClass() and .removeClass() or have a workaround that changes the given CSS or scrollTop() values.  I need to disable the hideOnScroll() function when the button is clicked for the duration of the click invoked animation - which in the examples is 2s. Thus I think the only way to achieve this is with the setTimeOut() method (i may be wrong on this).  But I can't get it to work.

Many thanks

Emily

答:
I have made a few changes in your javascript. Have a look

```<code>var animating = false;
    $(document).ready(function(){
        function hideOnScroll() {
            $(window).scroll(function() {
                event.preventDefault();
                if ( $(document).scrollTop() > 1 && !animating){
                    console.log("Hiding")
                    animating = true;
                    $('.menubox').animate({'left': '-25%'},2000,function(){
                        animating = false;
                    });
                }
            });
        }

        hideOnScroll();

        $('.mybutton').click(function() {
            var pos = $(window).scrollTop();
            animating = true;
            $('.menubox').animate({'left':'0%'},2000,function(){
                console.log("Finished Opening");
                animating = false;
            });
            console.log("Animating Open");
            var siId = setInterval(function(){
                if(animating){
                    console.log("Preventing Window Scrolling.");
                    $(window).scrollTop(pos);
                }
                else{
                    console.log("Stopping setInterval");
                    animating = false;
                    clearInterval(siId);
                }
            },0);
        });

    });
</code>```

This will stop your browser window from scrolling until your Menu Open Animation is finished.

Also I have removed the transitionproperty from style.

Tested in Google Chrome.

Kindly inform me if i have misinterpreted your question.

Body:
I have an animation triggered by a scroll event, which makes a menu slide out of view. There is also a button that when clicked brings the menu back into view.

Because the menu can be closed by scrolling, when the user clicks the button to bring the menu in, if they scroll during this period of the animation, the menu disappears again without the animation completing.

I have put together a simplified version of the animation here http://codepen.io/emilychews/pen/evbzMQ

I need to temporarily prevent the scroll function working after the button is clicked, which I'm assuming would be best done with the setTimeout() method on the click function?  I've tried a number of things but can't seem to solve it/ get it to work.

Any help would be awesome.  For quick reference as well the code is below

JQUERY

jQuery(document).ready(function($){

    // slide menu to left on scroll
    function hideOnScroll() {
      $(window).scroll(function() {
        if ( $(document).scrollTop() > 1) {

          $('.menubox').css('left', '-25%');

      }

    });

  }

  hideOnScroll(); // call hideOnScroll function

  // click handler to bring menu back in
  $('.mybutton').on('click', function() {

      $('.menubox').css('left', '0%');

      var scrollPause = setTimeout(hideOnScroll, 2000)  // temporarily pause hideOnScroll function

    });

}); //end of jQuery

CSS

body {
 margin: 0;
 padding: 0;
 height: 200vh;}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 2s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}

HTML

Menu Box

<button class="mybutton">Click to bring back menu</button>

** Also please note I've simplified the animation for the sake of the forum, the actual animation function contains Greensock code, but I didn't want to include this in case it confused the issue. I can't therefore just use the .addClass() and .removeClass() or have a workaround that changes the given CSS or scrollTop() values.  I need to disable the hideOnScroll() function when the button is clicked for the duration of the click invoked animation - which in the examples is 2s. Thus I think the only way to achieve this is with the setTimeOut() method (i may be wrong on this).  But I can't get it to work.

Many thanks

Emily

Body:
I have made a few changes in your javascript. Have a look

var animating = false;
    $(document).ready(function(){
        function hideOnScroll() {
            $(window).scroll(function() {
                event.preventDefault();
                if ( $(document).scrollTop() > 1 && !animating){
                    console.log("Hiding")
                    animating = true;
                    $('.menubox').animate({'left': '-25%'},2000,function(){
                        animating = false;
                    });
                }
            });
        }

        hideOnScroll();

        $('.mybutton').click(function() {
            var pos = $(window).scrollTop();
            animating = true;
            $('.menubox').animate({'left':'0%'},2000,function(){
                console.log("Finished Opening");
                animating = false;
            });
            console.log("Animating Open");
            var siId = setInterval(function(){
                if(animating){
                    console.log("Preventing Window Scrolling.");
                    $(window).scrollTop(pos);
                }
                else{
                    console.log("Stopping setInterval");
                    animating = false;
                    clearInterval(siId);
                }
            },0);
        });

    });

This will stop your browser window from scrolling until your Menu Open Animation is finished.

Also I have removed the transitionproperty from style.

Tested in Google Chrome.

Kindly inform me if i have misinterpreted your question.


问:
questions and solutions on a csv file
How can a system identify the device and load a file specifically for the device which contains suitable questions and responses  such as how many inches is the screen.
I was able to do this on python however I don’t know how to do the same on a csv file.
I have   3 devices that the system should identify however because the code is long I will just show one device .

The user must be able to interact with the program via input.

答:
I would suggest using the JSON format to store your data, this gives you more flexibility on how to store data. If your JSON file looks like this:

```<code>{
    "phone": {
        "iphone": {
            "iphone6": {
                "8GB": [
                    [
                        [
                            "keyword1",
                            "keyword2"
                        ],
                        "solution1"
                    ],
                    [
                        [
                            "keyword3",
                            "keyword4"
                        ],
                        "solution2"
                    ]
                ],
                "16GB": [
                    ...
                ]
            },
            "iphone7": {
                "8GB": ...,
                "16GB": ...
            },
        }
        "samsung": ...
    },
    "tablet": ...
}
</code>```

(The ... represents the data you put there)  Then you can use the user input data directly as keys for your data:

```<code>import json

# read your data from a file
with open("data.json") as f:
    data = json.load(f)

# ask for device
while True:
    device = input("Enter your device: ")
    try:
        device_data = data[device.strip().lower()]
    except KeyError:
        print("Please enter a valid device.")
    else:
        break

# ask for manufacturer
while True:
    manufacturer = input("Enter the manifacturer of your device: ")
    try:
        manufacturer_data = device_data[manufacturer.strip().lower()]
    except KeyError:
        print("Please enter a valid manufacturer.")
    else:
        break

# ask for model
while True:
    model = input("Enter your model: ")
    try:
        model_data = manufacturer_data[model.strip().lower()]
    except KeyError:
        print("Please enter a valid model.")
    else:
        break

# ask for memory
while True:
    memory = input("Enter the amount of internal memory you have: ")
    try:
        memory_data = model_data[memory.strip().lower()]
    except KeyError:
        print("Please enter a valid amount.")
    else:
        break

# ask for problem
while True:
    problem = input("Enter your problem: ")
    words = problem.strip().lower().split(" ")
    for keywords, solution in memory_data:
        if set(words) & set(keywords):
            print(solution)
            break
    else:
        print("A solution could not be found, please describe your problem more clearly.")
</code>```

I included .strip().lower() to make more of the possible inputs valid. This accepts "iphone", "IPhone", "IPHONE" and "   Iphone" as valid inputs. To give your users an overview of what options are possible you could also output the options in your questions. This is an example for manufacturers:

```<code>options = list(device_data.values())
output = "Enter the manifacturer of your device ["+"/".join(options)+"]: "
manufacturer = input(output)
</code>```

This solutions only works if you want to ask the same questions for every device. If this is not the case (e.g. you do not want to ask the user how much internal memory he has when talking about a camera), then you can include the question in the JSON file and ask the questions recursively.

Title: questions and solutions on a csv file

Body:
I would suggest using the JSON format to store your data, this gives you more flexibility on how to store data. If your JSON file looks like this:

{
    "phone": {
        "iphone": {
            "iphone6": {
                "8GB": [
                    [
                        [
                            "keyword1",
                            "keyword2"
                        ],
                        "solution1"
                    ],
                    [
                        [
                            "keyword3",
                            "keyword4"
                        ],
                        "solution2"
                    ]
                ],
                "16GB": [
                    ...
                ]
            },
            "iphone7": {
                "8GB": ...,
                "16GB": ...
            },
        }
        "samsung": ...
    },
    "tablet": ...
}

(The ... represents the data you put there)  Then you can use the user input data directly as keys for your data:

import json

# read your data from a file
with open("data.json") as f:
    data = json.load(f)

# ask for device
while True:
    device = input("Enter your device: ")
    try:
        device_data = data[device.strip().lower()]
    except KeyError:
        print("Please enter a valid device.")
    else:
        break

# ask for manufacturer
while True:
    manufacturer = input("Enter the manifacturer of your device: ")
    try:
        manufacturer_data = device_data[manufacturer.strip().lower()]
    except KeyError:
        print("Please enter a valid manufacturer.")
    else:
        break

# ask for model
while True:
    model = input("Enter your model: ")
    try:
        model_data = manufacturer_data[model.strip().lower()]
    except KeyError:
        print("Please enter a valid model.")
    else:
        break

# ask for memory
while True:
    memory = input("Enter the amount of internal memory you have: ")
    try:
        memory_data = model_data[memory.strip().lower()]
    except KeyError:
        print("Please enter a valid amount.")
    else:
        break

# ask for problem
while True:
    problem = input("Enter your problem: ")
    words = problem.strip().lower().split(" ")
    for keywords, solution in memory_data:
        if set(words) & set(keywords):
            print(solution)
            break
    else:
        print("A solution could not be found, please describe your problem more clearly.")

I included .strip().lower() to make more of the possible inputs valid. This accepts "iphone", "IPhone", "IPHONE" and "   Iphone" as valid inputs. To give your users an overview of what options are possible you could also output the options in your questions. This is an example for manufacturers:

options = list(device_data.values())
output = "Enter the manifacturer of your device ["+"/".join(options)+"]: "
manufacturer = input(output)

This solutions only works if you want to ask the same questions for every device. If this is not the case (e.g. you do not want to ask the user how much internal memory he has when talking about a camera), then you can include the question in the JSON file and ask the questions recursively.


问:
Unity predict endpoint from current velocity
My rocket's rigidbody velocity is Vector2(0,100) when I call a function. How can I calculate the world coordinate (enpoint) when the velocity reaches 0?

Gravity should be included in the formula.

Thanks!

答:
It sounds like you want the integral of the velocity function, which should provide the total distance respective to time.

Your velocity is going to be v = (100 - ('t'ime * 'g'ravity)). We can solve for time like t = (-v + 100)/g -> t = (0 + 100)/g = 100/g. So you should reach zero velocity at t = 100/g (assuming all the same units).

The integral of your velocity will give you distance traveled. An integral calculator is here: http://www.integral-calculator.com/

The integral function of your velocity is 100t - (g*t^2)/2

From zero to a particular time t, you can just plug and play. So for example, if for a particular gravity you reach zero velocity at t = 10 seconds, you will have traveled (100 * 10) - ((g * 10^2)/2) distance. (so for gravity 9, you would get 1000 - (9 * 100)/2 = 550 units

Edit: To be clear - first you want to calculate how long it takes to get to velocity zero at a particular starting velocity and gravity:

t = vStart/g

Then plug that time value into the integral function above:

distance = (vStart * t) - ((g * t^2)/2)

(or clearly you could turn it into one function by replacing t with vStart/g in the second function, but if I were coding I would definitely calculate them in two steps to provide a sanity check in case my units were wrong)


问:
BadZipFile while downloading from Kaggle
I am trying to download and unzip Kaggle dataset by python script(Python 3.5), but I get an error.

```<code>import io
from zipfile import ZipFile
import csv
import urllib.request

url = 'https://www.kaggle.com/c/quora-question-pairs/download/test.csv.zip'
response = urllib.request.urlopen(url)
c=ZipFile(io.BytesIO(response.read()))
</code>```

After running this code, I get the following error.

BadZipFile: File is not a zip file

How can I get rid of this error? What's the cause?

答:
Using requests module and some minor fix to http://ramhiser.com/2012/11/23/how-to-download-kaggle-data-with-python-and-requests-dot-py/ the solution is:</p>

```<code>import io
from zipfile import ZipFile
import csv
import requests

# The direct link to the Kaggle data set
data_url = 'https://www.kaggle.com/c/quora-question-pairs/download/test.csv.zip'

# The local path where the data set is saved.
local_filename = "test.csv.zip"

# Kaggle Username and Password
kaggle_info = {'UserName': "my_username", 'Password': "my_password"}

# Attempts to download the CSV file. Gets rejected because we are not logged in.
r = requests.get(data_url)

# Login to Kaggle and retrieve the data.
r = requests.post(r.url, data = kaggle_info)

# Writes the data to a local file one chunk at a time.
f = open(local_filename, 'wb')
for chunk in r.iter_content(chunk_size = 512 * 1024): # Reads 512KB at a time into memory
    if chunk: # filter out keep-alive new chunks
        f.write(chunk)
f.close()

c = ZipFile(local_filename)
</code>```

Body:
I am trying to download and unzip Kaggle dataset by python script(Python 3.5), but I get an error.

import io
from zipfile import ZipFile
import csv
import urllib.request

url = 'https://www.kaggle.com/c/quora-question-pairs/download/test.csv.zip'
response = urllib.request.urlopen(url)
c=ZipFile(io.BytesIO(response.read()))

After running this code, I get the following error.

BadZipFile: File is not a zip file

How can I get rid of this error? What's the cause?

Body:
Using requests module and some minor fix to http://ramhiser.com/2012/11/23/how-to-download-kaggle-data-with-python-and-requests-dot-py/ the solution is:

import io
from zipfile import ZipFile
import csv
import requests

# The direct link to the Kaggle data set
data_url = 'https://www.kaggle.com/c/quora-question-pairs/download/test.csv.zip'

# The local path where the data set is saved.
local_filename = "test.csv.zip"

# Kaggle Username and Password
kaggle_info = {'UserName': "my_username", 'Password': "my_password"}

# Attempts to download the CSV file. Gets rejected because we are not logged in.
r = requests.get(data_url)

# Login to Kaggle and retrieve the data.
r = requests.post(r.url, data = kaggle_info)

# Writes the data to a local file one chunk at a time.
f = open(local_filename, 'wb')
for chunk in r.iter_content(chunk_size = 512 * 1024): # Reads 512KB at a time into memory
    if chunk: # filter out keep-alive new chunks
        f.write(chunk)
f.close()

c = ZipFile(local_filename)


问:
How to give for each image a different link in a For
so I made a for to get all the images, but I also want that each image has a own link (when you click on it). how do I do that?

```<code><div class="container">

    <h2>Champions</h2>
    <hr>

    <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
    @for ($i = 0; $i < count($champions); $i++)

            <span class="col-lg-3 col-sm-12">

            <img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">

            </span>
    @endfor
</code>```

答:
You can link the image to link as follows:

simply wrap it up in "a" tag

```<code><a href="PUT_YOUR_CUSTOM_LINK_HERE">
<img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">
</a> <!-- close link tag-->
</code>```

Body:
so I made a for to get all the images, but I also want that each image has a own link (when you click on it). how do I do that?

Champions

    <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
    @for ($i = 0; $i < count($champions); $i++)

            <img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">

    @endfor

Body:
You can link the image to link as follows:

simply wrap it up in "a" tag

<a href="PUT_YOUR_CUSTOM_LINK_HERE">
<img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">
</a> <!-- close link tag-->


问:
How to append an image to a specific class
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine

jQuery (1st function)

```<code>    function getOffers(key) {
            dict = {
                'key': key// pk value of post sent to retrieve offers to it
            };

            generateCSRFToken();
            $.ajax({
                url: "/retrieve_offers/",
                method: "POST",
                data: JSON.stringify(dict),
                success: function (data) {
                    data = JSON.parse(data);

                    console.log(appendUserImage(38));
                    $("#offercontainer").empty();
                    $(".offer").empty();
                    for (var i = 0; i < data.length; i++) {

                        var string = data[i].fields.author_name;
                        $("#offercontainer").append(
                            "<div class='offer'>" +
                            "<p class=offername>" + string + "</p>" +
                            "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
                            "</div>"
                        );
                        appendUserImage(data[i].fields.author);
                    }
                },
                error: function () {
                }

            })
        }
</code>```

jQuery (2nd function)

```<code>  function appendUserImage(key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('<img />', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer'))

            },
            error: function () {
            }

        });

    }
</code>```

I just want to append the image to its respective offer div pls help

答:
thanks for the people who tried answering I managed to fix my problem by using nth child and doing this:

```<code> for (var i = 0; i < data.length; i++) {

                    var string = data[i].fields.author_name;
                    $("#offercontainer").append(
                        "<div class='offer'>" +
                        "<p class=offername>" + string + "</p>" +
                        "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
                        "</div>"
                    );
                    appendUserImage(i,data[i].fields.author);
                }
</code>```

2nd function:

```<code>function appendUserImage(i,key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('<img />', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer:nth-child(' + (i+1) + ')'))

            },
            error: function () {
            }

        });

    }
</code>```

Body:
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine

jQuery (1st function)

    function getOffers(key) {
            dict = {
                'key': key// pk value of post sent to retrieve offers to it
            };

            generateCSRFToken();
            $.ajax({
                url: "/retrieve_offers/",
                method: "POST",
                data: JSON.stringify(dict),
                success: function (data) {
                    data = JSON.parse(data);

                    console.log(appendUserImage(38));
                    $("#offercontainer").empty();
                    $(".offer").empty();
                    for (var i = 0; i < data.length; i++) {

                        var string = data[i].fields.author_name;
                        $("#offercontainer").append(
                            "
" +
                            "
" + string + "
" +
                            "
 offered his " + " " + data[i].fields.item_name +  "
" +
                            "
"
                        );
                        appendUserImage(data[i].fields.author);
                    }
                },
                error: function () {
                }

            })
        }

jQuery (2nd function)

  function appendUserImage(key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer'))

            },
            error: function () {
            }

        });

    }

I just want to append the image to its respective offer div pls help

Body:
thanks for the people who tried answering I managed to fix my problem by using nth child and doing this:

 for (var i = 0; i < data.length; i++) {

                    var string = data[i].fields.author_name;
                    $("#offercontainer").append(
                        "<div class='offer'>" +
                        "<p class=offername>" + string + "</p>" +
                        "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
                        "</div>"
                    );
                    appendUserImage(i,data[i].fields.author);
                }

2nd function:

function appendUserImage(i,key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('<img />', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer:nth-child(' + (i+1) + ')'))

            },
            error: function () {
            }

        });

    }


问:
add background image in active class css bootstrap
I am using bootstrap tabs. I want to use a down arrow for active class on tabs.

```<code><ul class="nav nav-tabs" style="font-size:20px;">
                  <li><a  class="active" data-toggle="tab" href="#menu1"><span class="glyphicon glyphicon-sound-dolby"></span></a></li>
                  <li><a data-toggle="tab" href="#menu2"><span class="glyphicon glyphicon-send"></span></a></li>
                  <li><a data-toggle="tab" href="#menu3"><span class="glyphicon glyphicon-earphone"></span></a></li>
                  <li><a data-toggle="tab" href="#menu4"><span class="glyphicon glyphicon-send"></span></a></li>
                </ul>
</code>```

Here is css of active class.

```<code>.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
    color: #555;
    cursor: default;
    background-color: #fff;
    background: url('../image/down.png') no-repeat !important;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
</code>```

Right now its just displaying white background for active class.
But not the image.
Kindly help me. Thank you

答:
The problem in css class. You assigned it to anappropriate selector.  In html class assigned to  tag, but in css to <li>. You need to wright correct css rule.
So your code will looks like this:</p>

```<code>.nav-tabs>li>a.active {
    background: #fff url('../image/down.png') right center no-repeat ;
}
</code>```

Body:
I am using bootstrap tabs. I want to use a down arrow for active class on tabs.

Here is css of active class.

.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
    color: #555;
    cursor: default;
    background-color: #fff;
    background: url('../image/down.png') no-repeat !important;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}

Right now its just displaying white background for active class.
But not the image.
Kindly help me. Thank you

Body:
The problem in css class. You assigned it to anappropriate selector.  In html class assigned to  tag, but in css to
. You need to wright correct css rule.
So your code will looks like this:

.nav-tabs>li>a.active {
    background: #fff url('../image/down.png') right center no-repeat ;
}


问:
How do I run a simple project of Selenium web driver with c#
I am trying to learn Selenium Web driver with c# and I have created a simple project by using code as mentioned in the image

And have already add the references, that use in for selenium, but when I am try to run this piece of code. I am getting error as mentioned below

Kindly let me know, how do I run this piece of code, waiting for reply

Thanks

答:
You might need to specify the file path of the drivers in your environmental variables. Alternatively, you can specify its location when creating an instance of a webdriver, or set the environment variable in your code.

You can download the driver for firefox:
https://github.com/mozilla/geckodriver/releases

For Firefox:

```<code>// Gecko driver is extracted to "C:\GeckoDriverLocation\geckodriver.exe"
Environment.SetEnvironmentVariable("PATH", @"C:\GeckoDriverLocation\");
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com");
</code>```

Driver for chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads

For Chrome:

```<code>//e.g. Chrome driver location is in C:\ChromeDriverLocation\chromedriver.exe
IWebDriver driver = new ChromeDriver(@"C:\ChromeWebDriverLocation\");
driver.Navigate().GoToUrl("http://www.google.com");
</code>```

Body:
You might need to specify the file path of the drivers in your environmental variables. Alternatively, you can specify its location when creating an instance of a webdriver, or set the environment variable in your code.

You can download the driver for firefox:
https://github.com/mozilla/geckodriver/releases

For Firefox:

// Gecko driver is extracted to "C:\GeckoDriverLocation\geckodriver.exe"
Environment.SetEnvironmentVariable("PATH", @"C:\GeckoDriverLocation\");
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com");

Driver for chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads

For Chrome:

//e.g. Chrome driver location is in C:\ChromeDriverLocation\chromedriver.exe
IWebDriver driver = new ChromeDriver(@"C:\ChromeWebDriverLocation\");
driver.Navigate().GoToUrl("http://www.google.com");


问:
VB.NET 2010 - Process.Start("filePath\Test.bat") not opening test.bat?
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

```<code>    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub
</code>```

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

答:
Try declaring a new process and specify the WorkingDirectory property.

Use the following code to achieve this

```<code>Dim myProcess As New Process
myProcess.StartInfo.WorkingDirectory = Environment.GetFolderPath(SpecialFolder.ApplicationData)
myProcess.StartInfo.FileName = "Test.bat"
myProcess.Start()
</code>```

Body:
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

Body:
Try declaring a new process and specify the WorkingDirectory property.

Use the following code to achieve this

Dim myProcess As New Process
myProcess.StartInfo.WorkingDirectory = Environment.GetFolderPath(SpecialFolder.ApplicationData)
myProcess.StartInfo.FileName = "Test.bat"
myProcess.Start()


问:
Protecting Sections of Source Code
I'm writing a Java class that connects to a server and reads messages in a given queue.

I would like to protect the username and password, which, right now, appear as plain text in the source code.

What I'm wondering, is, what is a good way to do this?  If I encrypt the username and password in a text file, won't I need to store the key, in plain text, in any source code that accesses this file?  And then anyone else who decides to use my class will be able to gain access to these fields.

There is no prompt where someone can enter the key, either, as this class will autonomously be used by the system.

EDIT:  this will become a java lib file.  But those can easily be decompiled and thus are basically the original class files anyway, right?  And the people this is being protected from are fellow developers of other systems who will gain access to this lib file.

My End Goal: is to have the username and password strings not appear as plain text anywhere, and for them to be as difficult as possible to crack.

答:
There are a few ways of handling this problem.  The challenge as you've noted is associating an account with this automated process.  So, here are some of the possibilities (from least secure to more secure):

Encrypt the username and password with a calculated key.

The calculated key is based on something both the client and the server can infer (like machine name and IP address)

Associate an authentication token with the client (OAuth style).

The token is negotiated by a one time user interaction to set up the client

The negotiated token is used for all future requests

The negotiated token is only valid for that client on that machine using that user account (server uses socket info to determine the match)

Use multiple forms of authentication

OAuth style token

Calculated token based on time + secondary id (requires clients and servers to be synched to the same time server)

It is important to note that your security measures should be more restrictive than it is worth to crack.  In short, if all the potential bad guy is only going to be able to get your food preferences of the day you might not need to be as vigilent as protecting something more high profile like a bank account.  User names and paswords are not the only means of authentication.

Title: Protecting Sections of Source Code


问:
why does $_GET['name'] is Nothing, when i navigate to http://example.com/test.php?<<<Apple>>>
I have a website which gets variables with GET method (assume it replies with properties like http://example.com/test.php?id=Apple will return properties of Apple), and it uses $_GET['id'] Global variable in php to retrieve requested id.

Problem is whenever I navigate to that site

```<code>http://example.com/test.php?id=<<<Apple>>>
</code>```

it just doesnt work, because $GET['id'] is empty. Why ?

I have to use GET, because I will be sharing it with customers and they can modify it to whatever they want. If I cannot use GET, what are my options ?

php file:

test.php

echo $_GET['id'];

答:
$_GET['id'] is empty because each time you are putting & character is like you are adding another parameter to the url, so if you print_r($_GET) you'll see something like this:

```<code>Array
(
    [id] =>
    [lt;] =>
    [lt;Apple] =>
    [gt;] =>
)
</code>```

You can try substringing $_SERVER['QUERY_STRING'].
In this case, $_SERVER['QUERY_STRING'] should be something like id=<<<Apple>>>, so you can just echo substr($_SERVER['QUERY_STRING'],3).

Body:
I have a website which gets variables with GET method (assume it replies with properties like http://example.com/test.php?id=Apple will return properties of Apple), and it uses $_GET['id'] Global variable in php to retrieve requested id.

Problem is whenever I navigate to that site

http://example.com/test.php?id=&lt;&lt;&lt;Apple&gt;&gt;&gt;

it just doesnt work, because $GET['id'] is empty. Why ?

I have to use GET, because I will be sharing it with customers and they can modify it to whatever they want. If I cannot use GET, what are my options ?

php file:

test.php

echo $_GET['id'];

Body:
$_GET['id'] is empty because each time you are putting & character is like you are adding another parameter to the url, so if you print_r($_GET) you'll see something like this:

Array
(
    [id] =>
    [lt;] =>
    [lt;Apple] =>
    [gt;] =>
)

You can try substringing $_SERVER['QUERY_STRING'].
In this case, $_SERVER['QUERY_STRING'] should be something like id=<<<Apple>>>, so you can just echo substr($_SERVER['QUERY_STRING'],3).


答:
Try this:

```<code><div class="container">

    <h2>Champions</h2>
    <hr>

    <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
    @for ($i = 0; $i < count($champions); $i++)

            <span class="col-lg-3 col-sm-12">

            <a href="http://gameinfo.euw.leagueoflegends.com/en/game-info/champions/<?php echo strtolower($champions[$i]); ?>" target="_new"><img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png"></a>

            </span>
    @endfor
</code>```

For different link just edit href="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]; ?>.png"

For example I want to open Yahoo:href="http://yahoo.com"

If you don't like have new window (new tab) just remove target="_new"

Title: How to give for each image a different link in a For

Body:
Try this:

<div class="container">

    <h2>Champions</h2>
    <hr>

    <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
    @for ($i = 0; $i < count($champions); $i++)

            <span class="col-lg-3 col-sm-12">

            <a href="http://gameinfo.euw.leagueoflegends.com/en/game-info/champions/<?php echo strtolower($champions[$i]); ?>" target="_new"><img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png"></a>

            </span>
    @endfor

For different link just edit href="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]; ?>.png"

For example I want to open Yahoo:href="http://yahoo.com"

If you don't like have new window (new tab) just remove target="_new"


问:
Extract number from a GUID
Is there any possiblity to extract only the numbers from a GUID? I'm trying to achieve this because I don't want to display the GUID in a form, but the numbers within, which also are unique. </p>

答:
You can use IsDigit to get only the numbers

```<code>   var guidstring = Guid.NewGuid().ToString("N");
   var getNumbers = (from t in guidstring
                              where char.IsDigit(t)
                              select t).ToArray();
</code>```

DEMO

Title: Extract number from a GUID

Body:
You can use IsDigit to get only the numbers

   var guidstring = Guid.NewGuid().ToString("N");
   var getNumbers = (from t in guidstring
                              where char.IsDigit(t)
                              select t).ToArray();

DEMO


问:
Accessing managed server host name and port from webapp
I am working on web application which will be deployed in Weblogic. In this application I need to access the port and host of the managed server. After searching a bit found that JMX with JNDI can help in getting the server details but not sure if host and port details can be accessed in this way, could not find much help in online docs available. Can someone please help me figuring out this?</p>

答:
```<code>    //Get ServerConfiguration
    ctx = new InitialContext();
    MBeanServer mBeanServer = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
    ObjectName ServerConfiguration = (ObjectName) mBeanServer
            .getAttribute(new ObjectName(RuntimeServiceMBean.OBJECT_NAME), "ServerConfiguration");
    // Get ListenPort
    port = mBeanServer.getAttribute(ServerConfiguration, "ListenPort").toString();
</code>```


答:
To add a link to your image, you simply wrap it:</p>

```<code>      <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
@for ($i = 0; $i < count($champions); $i++)

                    <span class="col-lg-3 col-sm-12">

 <a href="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">
     <img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">

    </a>
                    </span>
            @endfor
</code>```

Body:
To add a link to your image, you simply wrap it:

      <?php $champions = array("Ahri", "Akali", "Alistar", "Amumu", "Anivia", "Annie", "Ashe", "Blitzcrank", "Brand", "Caitlyn", "Cassiopeia", "Chogath", "Corki", "DrMundo", "Evelynn", "Ezreal", "FiddleSticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gragas", "Graves", "Hecarim", "Heimerdinger", "Irelia", "Janna", "JarvanIV", "Jax", "Karma", "Karthus", "Kassadin", "Katarina", "Kayle", "Kennen", "KogMaw", "Leblanc", "LeeSin", "Leona", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai", "MasterYi", "MissFortune", "Mordekaiser", "Morgana", "Nasus", "Nautilus", "Nidalee", "Nocturne", "Nunu", "Olaf", "Orianna", "Pantheon", "Poppy", "Rammus", "Renekton", "Riven", "Rumble", "Ryze", "Sejuani", "Shaco", "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Talon", "Taric", "Teemo", "Tristana", "Trundle", "Tryndamere", "TwistedFate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Viktor", "Vladimir", "Volibear", "Warwick", "MonkeyKing", "Xerath", "XinZhao", "Yorick", "Ziggs", "Zilean");?>
@for ($i = 0; $i < count($champions); $i++)

                    <span class="col-lg-3 col-sm-12">

 <a href="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">
     <img class="img" src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/<?php echo $champions[$i]?>.png">

    </a>
                    </span>
            @endfor


问:
ASP .NET MVC Controller Injection issue
In my ASP .NET MVC WebApi project I have controller constructor that receive a parameter, I don't have a prameterless constructor.

The dependecies are injected using Ninject:

Ninject 3.2.0.0 (3.2.2)

Ninject.Web.Common 3.2.0.0 (3.2.3)

Ninject.Web.WebApi 3.2.0.0 (3.2.4)

When I call the API I get:

An exception of type 'Ninject.ActivationException' occurred in
  Ninject.dll but was not handled in user code

Additional information: Error activating IHubRepository

No matching bindings are available, and the type is not self-bindable.

Activation path:

2) Injection of dependency IHubRepository into parameter
  repHub of constructor of type ResultController

1) Request for ResultController

Suggestions:

1) Ensure that you have defined a binding for IHubRepository.

2) If the binding was defined in a module, ensure that the module
  has been loaded into the kernel.

3) Ensure you have not accidentally created more than one kernel.

4) If you are using constructor arguments, ensure that the parameter
  name matches the constructors parameter name.

5) If you are using automatic module loading, ensure the search path
  and filters are correct.

The code is the following.

Controller:

```<code>public class ResultController : BaseHubController
{
    public ResultController(IHubRepository repHub)
    {
        _rep = repHub;
    }

    public async Task<IHttpActionResult> Get(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return BadRequest();

        return Ok();
    }
}
</code>```

NinjectResolver

```<code>public sealed class NinjectResolver : NinjectScope, IDependencyResolver
{
    private IKernel kernel;

    public NinjectResolver(IKernel kernelParam)
        : base(kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(kernel.BeginBlock());
    }

    public void AddBindings()
    {
        kernel.Bind<Hub.Dal.IHubRepository>().To<Hub.Dal.HubRepository>();
        kernel.Bind<System.Data.Entity.DbContext>().To<Hub.Dal.Context>();
    }
}

public class NinjectScope : IDependencyScope
{
    protected IResolutionRoot resolutionRoot;
    public NinjectScope(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)resolutionRoot;
        if (disposable != null) disposable.Dispose();
        resolutionRoot = null;
    }
}
</code>```

IHubRepository

```<code>public interface IHubRepository
{
    bool LogRequest(SHApiLog logData);
}
</code>```

HubRepository

```<code>public class HubRepository : IHubRepository
{
    private DbContext _ctx;

    public HubRepository(DbContext curCtx)
    {
        this._ctx = curCtx;
    }

    public bool LogRequest(SHApiLog logData)
    {
        try
        {
            _ctx.Set<SHApiLog>().Add(logData);
            _ctx.SaveChanges();
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}
</code>```

I can't understand why it won't work.

答:
The error message already states the possible problems.
Since the relevant code is not making any use of modules you can disregard the options mentioning modules and module loading => 2) and 5).
Since you're not using named parameters you can also ignore 4)

For number 1) => missing binding, there's also the possibility that you have two different IHubRepository (in different namespaces) and furthermore have created a binding for one of these but not the one you're requesting. You have a binding for Hub.Dal.IHubRepository but maybe ResultController wants Foo.Bar.IHubRepository.

To check for multiple kernels you can resort to service locator - inject IKernel (or IResolutionRoot) into the Controller instead of IHubRepository. Set a breakpoint at the controller constructor and inside the controller of NinjectResolver. When hitting the first break point, set object ID on the kernel reference. When hitting the second, check if there's an object ID and if it's the same. If it isn't.. well then you've got multiple kernels.

Title: ASP .NET MVC Controller Injection issue

Body:
In my ASP .NET MVC WebApi project I have controller constructor that receive a parameter, I don't have a prameterless constructor.

The dependecies are injected using Ninject:

Ninject 3.2.0.0 (3.2.2)

Ninject.Web.Common 3.2.0.0 (3.2.3)

Ninject.Web.WebApi 3.2.0.0 (3.2.4)

When I call the API I get:

An exception of type 'Ninject.ActivationException' occurred in
  Ninject.dll but was not handled in user code

Additional information: Error activating IHubRepository

No matching bindings are available, and the type is not self-bindable.

Activation path:

2) Injection of dependency IHubRepository into parameter
  repHub of constructor of type ResultController

1) Request for ResultController

Suggestions:

1) Ensure that you have defined a binding for IHubRepository.

2) If the binding was defined in a module, ensure that the module
  has been loaded into the kernel.

3) Ensure you have not accidentally created more than one kernel.

4) If you are using constructor arguments, ensure that the parameter
  name matches the constructors parameter name.

5) If you are using automatic module loading, ensure the search path
  and filters are correct.

The code is the following.

Controller:

public class ResultController : BaseHubController
{
    public ResultController(IHubRepository repHub)
    {
        _rep = repHub;
    }

    public async Task<IHttpActionResult> Get(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return BadRequest();

        return Ok();
    }
}

NinjectResolver

public sealed class NinjectResolver : NinjectScope, IDependencyResolver
{
    private IKernel kernel;

    public NinjectResolver(IKernel kernelParam)
        : base(kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(kernel.BeginBlock());
    }

    public void AddBindings()
    {
        kernel.Bind<Hub.Dal.IHubRepository>().To<Hub.Dal.HubRepository>();
        kernel.Bind<System.Data.Entity.DbContext>().To<Hub.Dal.Context>();
    }
}

public class NinjectScope : IDependencyScope
{
    protected IResolutionRoot resolutionRoot;
    public NinjectScope(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)resolutionRoot;
        if (disposable != null) disposable.Dispose();
        resolutionRoot = null;
    }
}

IHubRepository

public interface IHubRepository
{
    bool LogRequest(SHApiLog logData);
}

HubRepository

public class HubRepository : IHubRepository
{
    private DbContext _ctx;

    public HubRepository(DbContext curCtx)
    {
        this._ctx = curCtx;
    }

    public bool LogRequest(SHApiLog logData)
    {
        try
        {
            _ctx.Set<SHApiLog>().Add(logData);
            _ctx.SaveChanges();
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}

I can't understand why it won't work.


问:
How to access the instance variable initialized with some value inside a method of superclass in subclass Java
Base Class

```<code>public class Base
{
    public X obj;
    public void setValue()
    {
        obj = new A();
    }

}
</code>```

Util class

```<code>public class Util extends Base
{
    public X obj;

    public Util(X obj)
    {
        this.obj = obj;
    }

    public void function1()
    {
        obj.m1();  //obj is null
    }

    public void function2()
    {
        obj.m2();  //obj is null
    }

}
</code>```

Test Class

```<code>class Test extends Base
{
    // obj inherited from superclass is null.
    Util utilObj = new Util(obj)

    public void testMethod()
    {
         utilObj.function1();
         utilObj.function2();

    }

}
</code>```

How can i pass the  initialized value in constructor of  util class while creating its object inside Test class so that i can use the method of util class .It is giving Null pointer exception. I dont want to expose the call of setValue() method inside each Test class and can not declare it as static. i.e  public static X obj;in Base class .

Is there any way to access the initialized value of non-static variable initialized inside any method of superclass directly inside its subclass like static variable. Please help to solve this problem.

答:
Remove the public X obj; line from the Util class.  That line creates a different variable in Util that "hides" the one from Base because it has the same name.  If you remove the obj variable from Util, writing obj in Util methods will get you the Base variable.

Instead of having the Util constructor initialize obj directly, it'd be a good idea to give Base a constructor:

```<code>public Base(X obj)
{
    this.obj = obj;
}
</code>```

and then change the Util constructor to call it:

```<code>public Util(X obj)
{
    super(obj);  // Calls Base constructor
}
</code>```

Body:
Base Class

public class Base
{
    public X obj;
    public void setValue()
    {
        obj = new A();
    }

}

Util class

public class Util extends Base
{
    public X obj;

    public Util(X obj)
    {
        this.obj = obj;
    }

    public void function1()
    {
        obj.m1();  //obj is null
    }

    public void function2()
    {
        obj.m2();  //obj is null
    }

}

Test Class

class Test extends Base
{
    // obj inherited from superclass is null.
    Util utilObj = new Util(obj)

    public void testMethod()
    {
         utilObj.function1();
         utilObj.function2();

    }

}

How can i pass the  initialized value in constructor of  util class while creating its object inside Test class so that i can use the method of util class .It is giving Null pointer exception. I dont want to expose the call of setValue() method inside each Test class and can not declare it as static. i.e  public static X obj;in Base class .

Is there any way to access the initialized value of non-static variable initialized inside any method of superclass directly inside its subclass like static variable. Please help to solve this problem.

Body:
Remove the public X obj; line from the Util class.  That line creates a different variable in Util that "hides" the one from Base because it has the same name.  If you remove the obj variable from Util, writing obj in Util methods will get you the Base variable.

Instead of having the Util constructor initialize obj directly, it'd be a good idea to give Base a constructor:

public Base(X obj)
{
    this.obj = obj;
}

and then change the Util constructor to call it:

public Util(X obj)
{
    super(obj);  // Calls Base constructor
}


问:
Enterprise Architect - relation between observer and processed object
I have quick and simple question about specific class diagram model issue.

I have Observer and Observable classes and objects representing the notification (types of objects that are sent to the Observer) - see model below

ObjectType1 and ObjectType2 are classes whose instances are sent to the Observer as an argument of method update(Observable o, Object arg) by ObservableSubject instance.

My question is, how to model the relation between ObjectType1|ObjectType2 and Observer class?

答:
ObservableSubject should be an <<interface>> and both ObjectTypeX realize that interface. So the have the method update to inform the Observer.

You should show the method update inside ObservableSubject. That would have made your question clear from the beginning.