问:
How to add an onclick method on dynamically created button using jquery
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

```<code>'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
</code>```

but it leaves me an error saying the test function isn't defined.

here's my whole code:

```<code>$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

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

            //test();
            $('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
             items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
             items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
             items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr>');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});
</code>```

答:
Add this function to attach the test function for dynamically add button and remove test() function from the Ajax request

```<code>$(document).on("click", "#btnHistory", function(){
  alert ('test');
});
</code>```

Remove onclick attribute from button

Body:
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '

but it leaves me an error saying the test function isn't defined.

here's my whole code:

$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

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

            //test();
            $('#myTable').append('
' + items[i].unitId + '	'+
             items[i].pcName +'	'+ items[i].user + '	'+
             items[i].department+'	'+items[i].location+ '	'+
             items[i].dateAssigned + '	' + items[i].status +'	' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '
');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});

Body:
Add this function to attach the test function for dynamically add button and remove test() function from the Ajax request

$(document).on("click", "#btnHistory", function(){
  alert ('test');
});

Remove onclick attribute from button


来源: stackexchange

问:
Mach-O Linker Error on Xcode 4.6
I have an iOS app on Xcode 4.6 and when I recently tried to build and run in the iPhone 6.1 simulator I got a "Mach-O Linker Error." It continued to say:

ld: 17 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Does anyone know how to solve this?

Thanks so much!

答:
Quit Xcode

Restart the System

Select Xcode -> Preferences -> Locations

In Locations, you will see 'Derived Data'. Click on the arrow icon right next to the path.

This will open a folder containing 'Derived Data', delete it.

Clean the Product and Run

if still not works then

Build Settings > Enable Bitcode > No

ContentLicense: CC BY-SA 3.0

Title: Mach-O Linker Error on Xcode 4.6


问:
Webpack doesn't create react build production version
I have the following webpack-production.config.js file:

```<code>/* jshint node: true */
var webpack = require('webpack');
process.env.NODE_ENV = JSON.stringify('production');
module.exports = {
    watch: false,
    entry: {
        index: './client/js/index.js',
        article: './client/js/article.js',
        error: './client/js/error.js'
    },
    output: {
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            // JSON
            { test: /\.json$/, loader: "json-loader" },
            // React & ES2015
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false }
        })
    ]
};
</code>```

When I run this task using the command webpack --config webpack-production.config.js the bundle files are generated but when I open my site in brawser the React devtool extensions says: This page is using the development build of React..

What is wrong in my config file? How can I generate the React production version?

I mention that the official site of React says that I have to use the above  two plugins and it should be enough.

UPDATED

I added the path option in output settings and now I have the following error
in the braoser console:

```<code>Uncaught TypeError: Cannot read property '_' of undefined
</code>```

I mention that I use underscore like this:

```<code>import _ from 'underscore'
</code>```

答:
My guess would be that this is the cause:

```<code>process.env.NODE_ENV = JSON.stringify('production');
</code>```

It should be:

```<code>process.env.NODE_ENV = 'production';
</code>```

Alternatively, you can use the Webpack -p command line option that sets the NODE_ENV environment variable to production.

Body:
I have the following webpack-production.config.js file:

/* jshint node: true */
var webpack = require('webpack');
process.env.NODE_ENV = JSON.stringify('production');
module.exports = {
    watch: false,
    entry: {
        index: './client/js/index.js',
        article: './client/js/article.js',
        error: './client/js/error.js'
    },
    output: {
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            // JSON
            { test: /\.json$/, loader: "json-loader" },
            // React & ES2015
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false }
        })
    ]
};

When I run this task using the command webpack --config webpack-production.config.js the bundle files are generated but when I open my site in brawser the React devtool extensions says: This page is using the development build of React..

What is wrong in my config file? How can I generate the React production version?

I mention that the official site of React says that I have to use the above  two plugins and it should be enough.

UPDATED

I added the path option in output settings and now I have the following error
in the braoser console:

Uncaught TypeError: Cannot read property '_' of undefined

I mention that I use underscore like this:

import _ from 'underscore'

Body:
My guess would be that this is the cause:

process.env.NODE_ENV = JSON.stringify('production');

It should be:

process.env.NODE_ENV = 'production';

Alternatively, you can use the Webpack -p command line option that sets the NODE_ENV environment variable to production.


问:
Tests passing when run by ant but fail when run by maven?
Does anyone have any ideas why a test would pass when run with ant, but fail when run with maven?

I'm running my tests on windows and apparently there are some issues with surefire and windows? I've tried changing useSystemClassLoader=False and useManifestOnlyJar=true, but haven't been able to get them to work. The stack is below for the error I am getting when running the test with maven.

One thing I noticed is that there are $Proxy.someMethod calls in the stack, I have no idea where they are coming from.

Thanks for any help.

```<code>javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:678)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
        at $Proxy27.persist(Unknown Source)
        at cheetah.repositories.businessdata.jpa.JpaAttributeRepository.create(JpaAttributeRepository.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at $Proxy29.create(Unknown Source)
        at cheetah.tests.integration.util.BusinessDataLookupData.createAttributeLookupData(BusinessDataLookupData.java:19)
        at cheetah.tests.integration.util.BusinessDataLookupData.create(BusinessDataLookupData.java:10)
        at cheetah.tests.integration.util.LookupData.create(LookupData.java:7)
        at cheetah.tests.integration.util.TestUtil.prepareData(TestUtil.java:23)
        at cheetah.repositories.businessdata.tests.integration.AttributeRepositoryTest.setUpClass(AttributeRepositoryTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
        at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
        at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
        at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
        at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:672)
        ... 43 more
</code>```

答:
If it's related to 'pre test code' not being ran then maybe check out Maven failsafe plugin and look into the pre and post integration test phases of the lifecycle.  </p>

<p>Also, Maven is quite possibly using a different classpath to Ant - referring to JARS in it's own local repo.  Something to watch out for.  </p>

ContentLicense: CC BY-SA 2.5

Body:
Does anyone have any ideas why a test would pass when run with ant, but fail when run with maven?

I'm running my tests on windows and apparently there are some issues with surefire and windows? I've tried changing useSystemClassLoader=False and useManifestOnlyJar=true, but haven't been able to get them to work. The stack is below for the error I am getting when running the test with maven.

One thing I noticed is that there are $Proxy.someMethod calls in the stack, I have no idea where they are coming from.

Thanks for any help.

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:678)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
        at $Proxy27.persist(Unknown Source)
        at cheetah.repositories.businessdata.jpa.JpaAttributeRepository.create(JpaAttributeRepository.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at $Proxy29.create(Unknown Source)
        at cheetah.tests.integration.util.BusinessDataLookupData.createAttributeLookupData(BusinessDataLookupData.java:19)
        at cheetah.tests.integration.util.BusinessDataLookupData.create(BusinessDataLookupData.java:10)
        at cheetah.tests.integration.util.LookupData.create(LookupData.java:7)
        at cheetah.tests.integration.util.TestUtil.prepareData(TestUtil.java:23)
        at cheetah.repositories.businessdata.tests.integration.AttributeRepositoryTest.setUpClass(AttributeRepositoryTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
        at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
        at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
        at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
        at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:672)
        ... 43 more

Body:
If it's related to 'pre test code' not being ran then maybe check out Maven failsafe plugin and look into the pre and post integration test phases of the lifecycle.

Also, Maven is quite possibly using a different classpath to Ant - referring to JARS in it's own local repo.  Something to watch out for.


问:
Javamail Message[] into Javafx TableView
I have a method what gives me an Java mail Message[] back. Now I will show the subject string, the from string and the income date into a javafx table view. If I click than on a data in the table I will try to get the email text from the Message into a text field. I have no idea how to realise it.</p>

答:
You need to assign the values to the TableView including email, you can hide it if you want. Then create a mouse event in the TableView to get the email text and set it to the TextField.    </p>

```<code>public void printTable(TableView<ObservableList> table, String subject, String from, Date date, String email) {

    //Data.
    ObservableList<ObservableList> data = FXCollections.observableArrayList();

    //Columns.
    javafx.scene.control.TableColumn col = new javafx.scene.control.TableColumn();
    col.setText("Subject");
    table.getColumns().addAll(col);

    javafx.scene.control.TableColumn col2 = new javafx.scene.control.TableColumn();
    col.setText("From");
    table.getColumns().addAll(col2);

    javafx.scene.control.TableColumn col3 = new javafx.scene.control.TableColumn();
    col.setText("Date");
    table.getColumns().addAll(col3);

    javafx.scene.control.TableColumn col4 = new javafx.scene.control.TableColumn();
    col.setText("Email");
    table.getColumns().addAll(col4);

    //Row.
    ObservableList<String> row = FXCollections.observableArrayList();

    row.add(subject);
    row.add(from);
    row.add(date.toString());
    row.add(email);

    //Adding the row to the data.
    data.add(row);

    //Setting the data of the table.
    table.setItems(data);

    //Hiding the email column.
    table.getColumns().get(4).setVisible(false);
}

@FXML
private void tablePressed() {
    if(table.getSelectionModel().getSelectedItem() != null) {
        String message = table.getSelectionModel().getSelectedItem().get(4).toString();
        textField.setText(message);
    }
}
</code>```

Body:
You need to assign the values to the TableView including email, you can hide it if you want. Then create a mouse event in the TableView to get the email text and set it to the TextField.

public void printTable(TableView<ObservableList> table, String subject, String from, Date date, String email) {

    //Data.
    ObservableList<ObservableList> data = FXCollections.observableArrayList();

    //Columns.
    javafx.scene.control.TableColumn col = new javafx.scene.control.TableColumn();
    col.setText("Subject");
    table.getColumns().addAll(col);

    javafx.scene.control.TableColumn col2 = new javafx.scene.control.TableColumn();
    col.setText("From");
    table.getColumns().addAll(col2);

    javafx.scene.control.TableColumn col3 = new javafx.scene.control.TableColumn();
    col.setText("Date");
    table.getColumns().addAll(col3);

    javafx.scene.control.TableColumn col4 = new javafx.scene.control.TableColumn();
    col.setText("Email");
    table.getColumns().addAll(col4);

    //Row.
    ObservableList<String> row = FXCollections.observableArrayList();

    row.add(subject);
    row.add(from);
    row.add(date.toString());
    row.add(email);

    //Adding the row to the data.
    data.add(row);

    //Setting the data of the table.
    table.setItems(data);

    //Hiding the email column.
    table.getColumns().get(4).setVisible(false);
}

@FXML
private void tablePressed() {
    if(table.getSelectionModel().getSelectedItem() != null) {
        String message = table.getSelectionModel().getSelectedItem().get(4).toString();
        textField.setText(message);
    }
}


问:
How to get rid of underlined links
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <div class="container">
    <div class="row">
      <div class="col-xs-2">

          <button class="btn btn-block">
          About</button>
      </div>
      <div class="col-xs-2">

          <button class="btn btn-block">Portfolio</button>
      </div>

      <div class="col-xs-2">

          <button class="btn btn-block">Contact</button>
      </div>
    </div>
    <!-- close ROW -->
  </div>
  <!-- close HEAD -->

  <div class="about">
    <h2 style="text-align: center">

      ABOUT </h2>

      <img src="https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAzEAAAAJDkwZTM5NmY4LWYwMzQtNDhmOS1hYzExLTM4YWI5NTZmMGI5ZA.jpg" alt="picture of me" class="img-responsive photo">
      <center>
        <p> I am a book-lover translator, and an excellent-organised personal assistant.
          <br> I help my team daily to get through the week from chaos to clarity,
          <br> and I provide my colleagues with comprehensive translations and proofreading.
          <br> Recently I am also a coding hobbyist and a Front-End Developer wannabe.
        </p>
      </center>
  </div>

  <div id="port">
    <h2 style="text-align: center"> PORTFOLIO</h2>
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">
        <img class="small-img" src="http://www.drodd.com/images15/1-12.jpg">
        <img class="small-img" src="http://www.edu.xunta.gal/centros/ceipramoncajal/?q=system/files/u2/globo2fantasia.jpg">
        <img class="small-img" src="https://rfclipart.com/image/big/67-84-40/strawberry-style-font-number-3-Download-Royalty-free-Vector-File-EPS-71206.jpg">
      </div>
      <!-- close COL -->
    </div>
    <!--- close ROW -->
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">

        <img class="small-img" src="http://3.bp.blogspot.com/-9cSZuRMO65M/UOYn20oxGUI/AAAAAAAALgg/zTyw-uLPkO8/s1600/number4.jpg">
        <img class="small-img" src="https://thebitterlemon.files.wordpress.com/2016/09/5.jpg?w=400">
        <img class="small-img" src="https://thumbs.dreamstime.com/z/liczby-kresk%C3%B3wki-%C5%9Bmieszny-r%C3%B3%C5%BCowy-flaming-31350873.jpg">
      </div>
      <!--close COL -->
    </div>
    <!--close ROW -->
  </div>
  <!-- close PORT -->
  <div class="ctcMe">
    <h2 style="text-align: center">

    CONTACT ME</h2>
      <br>
      <div class="row" style="margin-top: 10px;">
        <div class="col-xs-7">
          <p class="contact">If you have any requests or questions<br>I am very eager to answer them :) </p>
        </div>
        <!-- close COL -->

        <div class="col-xs-2">
          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>
        </div>
        <!-- close COL -->
      </div>
      <!-- close ROW -->

  </div>
  <!-- close CtcMe -->

  <div class="web">
    <center>
      <p class="footnote">
        Around the web:
        <br>
        <img class="fc" src="https://yt3.ggpht.com/-bWUaHwGz7To/AAAAAAAAAAI/AAAAAAAAAAA/xEUD6X5iT2Y/s900-c-k-no-mo-rj-c0xffffff/photo.jpg">
        <img class="fc" src="http://www.blitzcleaned.com/wp-content/uploads/2014/07/LI-Logo-1.png">
        <img class="fc" src="http://www.freeiconspng.com/uploads/github-logo-icon-0.png">
        href="https://codepen.io/Broccolina/"><img class="fc" src="https://blog.codepen.io/wp-content/uploads/2012/06/Button-Black-Large.png">
      </p>
    </center>
  </div>

  <div class="coded">
    <center>
      <p class="footnote">
        Written and coded by
        href="https://www.facebook.com/broccolina19"> Agnieszka Kozub
      </p>
    </center>
  </div>
</body></code>```

答:
by default browser style a tag text underline,

to remove

select that element and add text-decoration-line: none;

```<code>a {
    text-decoration-line:  none !important;
}
</code>```

best way to do is not to use !important, so add a class name to that a tags e.g. like noline

```<code>a.noline {
    text-decoration-line: none;
}
</code>```

edited your code

Title: How to get rid of underlined links

Body:
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

  <meta name="viewport" content="width=device-width, initial-scale=1">

          <button class="btn btn-block">
          About</button>

          <button class="btn btn-block">Portfolio</button>

          <button class="btn btn-block">Contact</button>

      ABOUT

 I am a book-lover translator, and an excellent-organised personal assistant.

 I help my team daily to get through the week from chaos to clarity,

 and I provide my colleagues with comprehensive translations and proofreading.

 Recently I am also a coding hobbyist and a Front-End Developer wannabe.

 PORTFOLIO

    CONTACT ME

If you have any requests or questions
I am very eager to answer them :)

          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>

        Around the web:

        Written and coded by
         Agnieszka Kozub

Body:
by default browser style a tag text underline,

to remove

select that element and add text-decoration-line: none;

a {
    text-decoration-line:  none !important;
}

best way to do is not to use !important, so add a class name to that a tags e.g. like noline

a.noline {
    text-decoration-line: none;
}

edited your code


问:
How to place image correctly in input tag
I created a input tag with two images cross and arrow.

Here is my code.

```<code><div id="chart_line" style="position: relative;">
    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">
        <div id="triggers">
            <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
            <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
        </div>
</div>
</code>```

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

答:
The first problem is this:

```<code>#container {
  position: relative;
  width: 30%;
}
</code>```

What used to be #container is now #chart_line, so if you change the above CSS to this:

```<code>#chart_line {
  position: relative;
  width: 30%;
}
</code>```

That should do something.

The next job is to change every width: 30%; in your code to width: 30vw;.

Then you need to give #myInput some padding:

```<code>  padding: 0 55px 0 7px;
</code>```

Now all you need to do is remove the CSS left: 110px from #triggers and replace it with right: 6px;

* {
  box-sizing: border-box;
}
#myInput {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  height: 30px;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0 55px 0 7px;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
#chart_line {
  position: relative;
  width: 30vw;
}
#textfield {
  height: 30px;
  width: 100%;
}
.trigger {
  width: 20px;
}
#triggers {
  position: absolute;
  right: 6px;
  top: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="chart_line">
  <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30vw;">
  <div id="triggers">
    <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
    <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
  </div>
</div></code>```

CodePen

Body:
I created a input tag with two images cross and arrow.

Here is my code.

    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

Body:
The first problem is this:

#container {
  position: relative;
  width: 30%;
}

What used to be #container is now #chart_line, so if you change the above CSS to this:

#chart_line {
  position: relative;
  width: 30%;
}

That should do something.

The next job is to change every width: 30%; in your code to width: 30vw;.

Then you need to give #myInput some padding:

  padding: 0 55px 0 7px;

Now all you need to do is remove the CSS left: 110px from #triggers and replace it with right: 6px;

* {
  box-sizing: border-box;
}
#myInput {
  position: relative;
  border: 1px solid #95B8E7;
  background-color: #fff;
  height: 30px;
  vertical-align: middle;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin: 0;
  padding: 0 55px 0 7px;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
#chart_line {
  position: relative;
  width: 30vw;
}
#textfield {
  height: 30px;
  width: 100%;
}
.trigger {
  width: 20px;
}
#triggers {
  position: absolute;
  right: 6px;
  top: 5px;
}

<div id="chart_line">
  <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30vw;">
  <div id="triggers">
    <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
    <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
  </div>
</div>

CodePen


问:
Centering a view in its superview using Visual Format Language
I just started learning AutoLayout for iOS and had a look at Visual Format Language.

It all works fine except for one thing: I just can't get a view to center within its superview.

Is this possible with VFL or do I need to manually create a constraint myself?

答:
Thanks to the answer from @Evgenii, I create a full example in gist:

center the red square vertically with custom height

https://gist.github.com/yallenh/9fc2104b719742ae51384ed95dcaf626

You can center a view vertically by useing either VFL (which is not quite intuitive) or use constraints manually.
By the way, I cannot combine both centerY and height together in VFL like:

```<code>"H:[subView]-(<=1)-[followIcon(==customHeight)]"
</code>```

In the current solution VFL constraints are added separately.

Body:
Thanks to the answer from @Evgenii, I create a full example in gist:

center the red square vertically with custom height

https://gist.github.com/yallenh/9fc2104b719742ae51384ed95dcaf626

You can center a view vertically by useing either VFL (which is not quite intuitive) or use constraints manually.
By the way, I cannot combine both centerY and height together in VFL like:

"H:[subView]-(<=1)-[followIcon(==customHeight)]"

In the current solution VFL constraints are added separately.


问:
Swifty way to get value associated with another in struct
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

```<code>struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}
</code>```

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

答:
Using discrete properties for the colours is not particularly scalable; you are dealing with with specific strings in your code, which are difficult to resolve at runtime.

I would suggest that you expand your structs to include a colour pair struct and enumeration to access the appropriate colour pair. Since an enumeration doesn't conform to hashable you can't use it as a dictionary key directly, but we can use a string raw value to get around that.

Something like:

```<code>struct CustomColors {

    struct Colors {
        let primary: UIColor
        let secondary: UIColor
    }

    enum Theme:String {
        case orange
        case blue
        case yellow
    }

    private let colors: [String:Colors] = [
        Theme.orange.rawValue: Colors(primary: UIColor(r: 255, g: 110, b: 64, a: 1),secondary: UIColor(r: 230, g: 74, b: 25, a: 1)),
        Theme.blue.rawValue: Colors(primary:UIColor(r: 24, g: 255, b: 255, a: 1), secondary:UIColor(r: 24, g: 255, b: 255, a: 1)),
        Theme.yellow.rawValue: Colors(primary:  UIColor(r: 255, g: 255, b: 0, a: 1), secondary: UIColor(r: 255, g: 193, b: 7, a: 1))

    ]

    func colorFor(theme: Theme) -> Colors {
        return colors[theme.rawValue]!
    }

}
</code>```

Now you can, for example, track the currently active theme and use a variable to access the colours. Once you have the Colors struct, simply access the primary and secondary properties

```<code>let cc = CustomColors()
let activeTheme: CustomColors.Theme = .blue
print(cc.colorFor(theme: activeTheme).primary)
</code>```

You can also use the raw value to easily identify and create a Theme

```<code>print(activeTheme)
if let someOtherTheme = CustomColors.Theme(rawValue: "yellow") {
    print(someOtherTheme)
}
</code>```

Body:
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

Body:
Using discrete properties for the colours is not particularly scalable; you are dealing with with specific strings in your code, which are difficult to resolve at runtime.

I would suggest that you expand your structs to include a colour pair struct and enumeration to access the appropriate colour pair. Since an enumeration doesn't conform to hashable you can't use it as a dictionary key directly, but we can use a string raw value to get around that.

Something like:

struct CustomColors {

    struct Colors {
        let primary: UIColor
        let secondary: UIColor
    }

    enum Theme:String {
        case orange
        case blue
        case yellow
    }

    private let colors: [String:Colors] = [
        Theme.orange.rawValue: Colors(primary: UIColor(r: 255, g: 110, b: 64, a: 1),secondary: UIColor(r: 230, g: 74, b: 25, a: 1)),
        Theme.blue.rawValue: Colors(primary:UIColor(r: 24, g: 255, b: 255, a: 1), secondary:UIColor(r: 24, g: 255, b: 255, a: 1)),
        Theme.yellow.rawValue: Colors(primary:  UIColor(r: 255, g: 255, b: 0, a: 1), secondary: UIColor(r: 255, g: 193, b: 7, a: 1))

    ]

    func colorFor(theme: Theme) -> Colors {
        return colors[theme.rawValue]!
    }

}

Now you can, for example, track the currently active theme and use a variable to access the colours. Once you have the Colors struct, simply access the primary and secondary properties

let cc = CustomColors()
let activeTheme: CustomColors.Theme = .blue
print(cc.colorFor(theme: activeTheme).primary)

You can also use the raw value to easily identify and create a Theme

print(activeTheme)
if let someOtherTheme = CustomColors.Theme(rawValue: "yellow") {
    print(someOtherTheme)
}


问:
How to extract part of a file saved in HDFS and save it as csv?
My Device file is saved in HDFS and I need to take 100 rows from that saved file
and save as csv in my local filesystem.

I have tried this command:

```<code>hdfs dfs -text /path to hdfs/Device/* > DEvice.csv
</code>```

答:
```<code> hdfs dfs -text /path to hdfs/Device/* | head -100 > DEvice.csv
</code>```

<p>This will get the first 100 lines, uncompressed from the Hadoop file and store them to the csv file in your local filesystem. </p>

Body:
My Device file is saved in HDFS and I need to take 100 rows from that saved file
and save as csv in my local filesystem.

I have tried this command:

hdfs dfs -text /path to hdfs/Device/* > DEvice.csv

Body:
 hdfs dfs -text /path to hdfs/Device/* | head -100 > DEvice.csv

This will get the first 100 lines, uncompressed from the Hadoop file and store them to the csv file in your local filesystem.


问:
How to move show entries column to below of datatables
i am trying to do the load on demand by using datatables on my mvc page

if you see in the picture, the show entries is on the top of the datatables

can i move the show 10 entries to the below of the showing 1 to 10 entries there?.

the following is my html code

```<code>        <div class="dataTables_hideonload m-b-10">
            <table class="table table-condensed table-vertical-middle table-layout-fixed table-noajax" id="tableCategoryList" width="100%">
                <thead>
                    <tr>
                        <th class="text-left">Category ID</th>
                        <th class="text-left">Category Name</th>
                        <th class="text-left">Sort order</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
</code>```

答:
You can re-position it by using:

```<code>"dom": '<"top"i>rt<"bottom"flp><"clear">'
</code>```

Re-positioning reference

Body:
i am trying to do the load on demand by using datatables on my mvc page

if you see in the picture, the show entries is on the top of the datatables

can i move the show 10 entries to the below of the showing 1 to 10 entries there?.

the following is my html code

                        Category ID
                        Category Name
                        Sort order

Body:
You can re-position it by using:

"dom": '<"top"i>rt<"bottom"flp><"clear">'

Re-positioning reference


问:
How to avoid generating duplicate numbers using RandomStringUtils.random of Apache Commons Jar
I am using Apache Commons Lang3 package class RandomStringUtils. After generating some numbers, RandomStringUtils.randomNumeric is generating duplicate numbers in an infinite loop. How can I prevent this from happening?

Here is my code:

```<code>quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 1;

while (insertedNum < quantity) {
    String random=RandomStringUtils.randomNumeric(length);
    numGen[idx - 1] = random;
    if (idx == 100) {
        insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
        idx = 1;
        numGen = new String[100];
    }
    else
        idx++;
    }
}
</code>```

答:
Firstly you have a bug numGen[idx - 1] = random;

When first entering the loop the idx is 0 so you are assigning to -1 field in numGen.
2ndly it will not continue forever, but if it does for a long time you can take different approach when generating strings, instead of deleting whole batch, regenerate them one by one if they exist in the current batch.

Try checking after each generation if the number has not yet been generated in this batch. You can use java map or set to mark all seen numbers in the batch for lookup to be faster.

So add code for your solution to look something along those lines:

```<code>quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 0;
Set<string> seenThisBatch = new HashSet<string>();
while (insertedNum < quantity) {
            String random=RandomStringUtils.randomNumeric(length);
            //in case of duplicates, keep on generating
            while(seenThisBatch.contains(random){
                  random=RandomStringUtils.randomNumeric(length);
            }
            //add it to set
            seenThisBatch.add(random);
            numGen[idx - 1] = random;
            if (idx == 100) {
                //clear the batch set
                seenThisBatch.clear();
                insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
                idx = 1;
                numGen = new String[100];
            }
            else
              idx++;
        }
</code>```

Body:
I am using Apache Commons Lang3 package class RandomStringUtils. After generating some numbers, RandomStringUtils.randomNumeric is generating duplicate numbers in an infinite loop. How can I prevent this from happening?

Here is my code:

quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 1;

while (insertedNum < quantity) {
    String random=RandomStringUtils.randomNumeric(length);
    numGen[idx - 1] = random;
    if (idx == 100) {
        insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
        idx = 1;
        numGen = new String[100];
    }
    else
        idx++;
    }
}

Body:
Firstly you have a bug numGen[idx - 1] = random;

When first entering the loop the idx is 0 so you are assigning to -1 field in numGen.
2ndly it will not continue forever, but if it does for a long time you can take different approach when generating strings, instead of deleting whole batch, regenerate them one by one if they exist in the current batch.

Try checking after each generation if the number has not yet been generated in this batch. You can use java map or set to mark all seen numbers in the batch for lookup to be faster.

So add code for your solution to look something along those lines:

quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 0;
Set<string> seenThisBatch = new HashSet<string>();
while (insertedNum < quantity) {
            String random=RandomStringUtils.randomNumeric(length);
            //in case of duplicates, keep on generating
            while(seenThisBatch.contains(random){
                  random=RandomStringUtils.randomNumeric(length);
            }
            //add it to set
            seenThisBatch.add(random);
            numGen[idx - 1] = random;
            if (idx == 100) {
                //clear the batch set
                seenThisBatch.clear();
                insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
                idx = 1;
                numGen = new String[100];
            }
            else
              idx++;
        }


问:
Boostrap Carousel Scroll clashing with JS page scroller
I am using a JS script that offsets page content from depth of the Nav, however this is interfering with my page scroll (using the id as anchors) -  I have no idea how to correct this and am not clued up on JS. Any help will be appreciated.

THIS IS MY JS:

```<code>    function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");

    // You could easily calculate this dynamically if you prefer
    var mq = window.matchMedia( "(max-width: 991px)" );
        if (mq.matches) {
            var fromTop = 0;
        }
        else {
            var fromTop = 130;
        }

    // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
    // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
    if(href.indexOf("#") == 0) {
        var $target = $(href);

        // Older browser without pushState might flicker here, as they momentarily
        // jump to the wrong position (IE < 10)
        if($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
            if(history && "pushState" in history) {
                history.pushState({}, document.title, window.location.pathname + href);
                return false;
            }
        }
    }
}
</code>```

THIS IS MY HTML

```<code>    <div id="carousel1" class="carousel slide" data-ride="carousel">

  <div class="carousel-inner" role="listbox">

       <?php
           $loop = new WP_Query(array(
                'post_type' => 'banner', 'orderyby' => 'post_id', 'order' => 'ASC',
                'posts_per_page' => 1
            ));
           while ( $loop->have_posts() ) :
           $loop->the_post();
        ?>

   <div class="item active">
     <?php the_post_thumbnail('full');?>
       </div><!-- item active -->
    <?php
   endwhile;
   wp_reset_postdata();
  ?>

      <?php
           $loop = new WP_Query(array(
                'post_type' => 'banner', 'orderyby' => 'post_id', 'order' => 'ASC',
                'posts_per_page' => 10,
                'offset' => 1
            ));
           while ( $loop->have_posts() ) :
           $loop->the_post();
      ?>

   <div class="item">
    <?php the_post_thumbnail('full');?>
   </div><!-- item -->

    <?php
       endwhile;
       wp_reset_postdata();
    ?>

  </div> <!-- CAROUSEL inner -->

  <a class="left carousel-control" href="#carousel1" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a><a class="right carousel-control" href="#carousel1" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a>

  </div> <!-- CAROUSEL -->
</code>```

答:
I found a solution:</p>

```<code>$(document).ready(function(){
    // Enable Carousel Controls
    $(".left").click(function(){
        $("#carousel1").carousel("prev");
    });
    $(".right").click(function(){
        $("#carousel1").carousel("next");
    });

});
</code>```

Body:
I am using a JS script that offsets page content from depth of the Nav, however this is interfering with my page scroll (using the id as anchors) -  I have no idea how to correct this and am not clued up on JS. Any help will be appreciated.

THIS IS MY JS:

    function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");

    // You could easily calculate this dynamically if you prefer
    var mq = window.matchMedia( "(max-width: 991px)" );
        if (mq.matches) {
            var fromTop = 0;
        }
        else {
            var fromTop = 130;
        }

    // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
    // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
    if(href.indexOf("#") == 0) {
        var $target = $(href);

        // Older browser without pushState might flicker here, as they momentarily
        // jump to the wrong position (IE < 10)
        if($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
            if(history && "pushState" in history) {
                history.pushState({}, document.title, window.location.pathname + href);
                return false;
            }
        }
    }
}

THIS IS MY HTML

       <?php
           $loop = new WP_Query(array(
                'post_type' => 'banner', 'orderyby' => 'post_id', 'order' => 'ASC',
                'posts_per_page' => 1
            ));
           while ( $loop->have_posts() ) :
           $loop->the_post();
        ?>

     <?php the_post_thumbnail('full');?>

    <?php
   endwhile;
   wp_reset_postdata();
  ?>

      <?php
           $loop = new WP_Query(array(
                'post_type' => 'banner', 'orderyby' => 'post_id', 'order' => 'ASC',
                'posts_per_page' => 10,
                'offset' => 1
            ));
           while ( $loop->have_posts() ) :
           $loop->the_post();
      ?>

    <?php the_post_thumbnail('full');?>

    <?php
       endwhile;
       wp_reset_postdata();
    ?>

  PreviousNext

Body:
I found a solution:

$(document).ready(function(){
    // Enable Carousel Controls
    $(".left").click(function(){
        $("#carousel1").carousel("prev");
    });
    $(".right").click(function(){
        $("#carousel1").carousel("next");
    });

});


问:
Smart Table not refreshing on setTimeout
The code related to table generation is not working in the below function

```<code>function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}
</code>```

the populateDataTable is being populated by the below code

```<code>setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);
</code>```

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

答:
you have to try like this</p>

```<code>setTimeout(function() {
   populateDataTable($scope.repo_contributor,$scope.repo_languages);
  }, 4000)
</code>```

Body:
The code related to table generation is not working in the below function

function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}

the populateDataTable is being populated by the below code

setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

Body:
you have to try like this

setTimeout(function() {
   populateDataTable($scope.repo_contributor,$scope.repo_languages);
  }, 4000)


问:
Simple way of converting list from character to numeric in R?
I have looking into other threads on this problem and could not find an easy solution. I have imported data from Excel tables, and joined them in lists which generally look like this:

```<code>> Hemo
[[1]]
V1 V2 V3 V4  V5  V6  V7
1 0d 3d 6d 9d 12d 15d 18d
2 10 40 20 60  50  30  40
3 20 30 30 30  30  30  30
4 20 20 30 20  40  20  50

[[2]]
V1 V2 V3 V4  V5  V6  V7
1 0d 3d 6d 9d 12d 15d 18d
2  0 10 10  0   0   0   0
3  0 10 20 20  20   0   0
4  0  0 10 20  20   0   0
</code>```

However I'd like them to look like this (which is an array):

```<code>, , 1

0d 3d 6d 9d 12d 15d 18d
V2 10 40 20 60  50  30  40
V3 20 30 30 30  30  30  30
V4 20 20 30 20  40  20  50

, , 2

0d 3d 6d 9d 12d 15d 18d
V2  0 10 10  0   0   0   0
V3  0 10 20 20  20   0   0
V4  0  0 10 20  20   0   0
</code>```

In the first case all elements are characters and I am not being able to coerse them to numbers. Ultimately I'd like to convert the first list into the second array where the first imported line figures as the column names. There must be some package enabling this? Please let us find a simple workaround as I am a newbie. Thanks

答:
It appears as though you imported the data from excel, but the columnnames were interpreted as data. You didn't specify which function you used to do the importing, but with most of them you can specify that the first row of data are columnnames.

```<code>library(readxl)
data <- read_excel(filename, col_names = TRUE)
</code>```

When you import your data properly, it won't confuse the actual data, and should automatically read it as numerics. This way you won't have to convert it yourself.

Body:
I have looking into other threads on this problem and could not find an easy solution. I have imported data from Excel tables, and joined them in lists which generally look like this:

> Hemo
[[1]]
V1 V2 V3 V4  V5  V6  V7
1 0d 3d 6d 9d 12d 15d 18d
2 10 40 20 60  50  30  40
3 20 30 30 30  30  30  30
4 20 20 30 20  40  20  50

[[2]]
V1 V2 V3 V4  V5  V6  V7
1 0d 3d 6d 9d 12d 15d 18d
2  0 10 10  0   0   0   0
3  0 10 20 20  20   0   0
4  0  0 10 20  20   0   0

However I'd like them to look like this (which is an array):

, , 1

0d 3d 6d 9d 12d 15d 18d
V2 10 40 20 60  50  30  40
V3 20 30 30 30  30  30  30
V4 20 20 30 20  40  20  50

, , 2

0d 3d 6d 9d 12d 15d 18d
V2  0 10 10  0   0   0   0
V3  0 10 20 20  20   0   0
V4  0  0 10 20  20   0   0

In the first case all elements are characters and I am not being able to coerse them to numbers. Ultimately I'd like to convert the first list into the second array where the first imported line figures as the column names. There must be some package enabling this? Please let us find a simple workaround as I am a newbie. Thanks

Body:
It appears as though you imported the data from excel, but the columnnames were interpreted as data. You didn't specify which function you used to do the importing, but with most of them you can specify that the first row of data are columnnames.

library(readxl)
data <- read_excel(filename, col_names = TRUE)

When you import your data properly, it won't confuse the actual data, and should automatically read it as numerics. This way you won't have to convert it yourself.


问:
IntelliJ getter/setter format (single-line versus multi-line)
How can you get IntelliJ to generate getter/setters accessor methods on one line like this:

```<code>public String getAbc() { return abc; }
</code>```

… instead of multiple lines like this:

```<code>public String getAbc() {
   return abc;
}
</code>```

答:
For Idea 2016.

Getter template

Merge the last 3 lines into a single line:

```<code>${name}() { return $field.name; }
</code>```

Setter template

Add double hash (without a space) at the end of the longest line:

```<code>[...] ($field.type, $paramName) {##
</code>```

Merge the last 2 lines into a single line:

```<code>$field.name = $paramName; }
</code>```

Note: as commented by @mindas, you will probably want instead the visual auto folding that doesn't get versioned.

ContentLicense: CC BY-SA 4.0

Body:
How can you get IntelliJ to generate getter/setters accessor methods on one line like this:

public String getAbc() { return abc; }

… instead of multiple lines like this:

public String getAbc() {
   return abc;
}

Body:
For Idea 2016.

Getter template

Merge the last 3 lines into a single line:

${name}() { return $field.name; }

Setter template

Add double hash (without a space) at the end of the longest line:

[...] ($field.type, $paramName) {##

Merge the last 2 lines into a single line:

$field.name = $paramName; }

Note: as commented by @mindas, you will probably want instead the visual auto folding that doesn't get versioned.


问:
Show/hide a record based on condition inside ng-repeat not working
Below are my records :

```<code>$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];
</code>```

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records">
         <div ng-show="currentSelection=='Admin' && item.id=='Statistics'">{{item.id}}
         </div>
    </li>
</ul></code>```

答:
Your check is wrong,

1) It should be ng-show="currentSelection=='Admin' if you want to show every list items.

2) It should be ng-show="currentSelection=='Guest ' ||currentSelection=='Employee' && item.id!=='Statistics'" if you want to show every list items except statistics.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
<ul ng-show="currentSelection=='Admin'">
    <li ng-repeat="item in records">
        {{item.id}}
    </li>
</ul>
<ul ng-show="currentSelection=='Guest' || currentSelection=='Employee'">
     <li ng-repeat="item in records" ng-if="item.id!=='Statistics'">
         {{item.id}}
    </li>
</ul>
</div></code>```

Body:
Below are my records :

$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });

{{item.id}}

Body:
Your check is wrong,

1) It should be ng-show="currentSelection=='Admin' if you want to show every list items.

2) It should be ng-show="currentSelection=='Guest ' ||currentSelection=='Employee' && item.id!=='Statistics'" if you want to show every list items except statistics.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];

        });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
<ul ng-show="currentSelection=='Admin'">
    <li ng-repeat="item in records">
        {{item.id}}
    </li>
</ul>
<ul ng-show="currentSelection=='Guest' || currentSelection=='Employee'">
     <li ng-repeat="item in records" ng-if="item.id!=='Statistics'">
         {{item.id}}
    </li>
</ul>
</div>


问:
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.

I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.

The problem is that I don't know where to start investigating how to do this.  Let's say I have a script called:

file_arranger.py

What do I need to do to have a webpage execute that script?  This isn't meant for public consumption, so anything lightweight would be great.  For bonus points, what do I need to look into to provide the web user with the output from such scripts?

edit:  The first answer made me realize I forgot to include that this is a Win2k3 system.

答:
When setting this up, please be careful to restrict access to the scripts that take some action on your web server. It is not sufficient to place them in a directory where you just don't publish the URL, because sooner or later somebody will find them.

At the very least, put these scripts in a location that is password protected. You don't want just anybody out there on the internet being able to run your scripts.

OwnerDisplayName: Therms

LastEditorDisplayName: J.F. Sebastian

OwnerDisplayName: Greg Hewgill


问:
Bootstrap 3 breakpoints and media queries
On the Bootstrap 3 media queries documentation it says:

We use the following media queries in our Less files to create the key breakpoints in our grid system.

Extra small devices (phones, less than 768px):
  No media query since this is the default in Bootstrap

Small devices (tablets, 768px and up):
  @media (min-width: @screen-sm-min) { ... }

Medium devices (desktops, 992px and up):
  @media (min-width: @screen-md-min) { ... }

Large devices (large desktops, 1200px and up):
  @media (min-width: @screen-lg-min) { ... }

Are we supposed to be able to use the @screen-sm, @screen-md, and @screen-lg names in our media queries as well? Because it doesn't work for me. I have to use pixel measurements such as @media (min-width: 768px) {...} before it will work. Am I doing something wrong?

<s>Also, is the reference to 480px for extra small devices a typo? Shouldn't that say up to 767px?</s> (since removed from the documentation)

答:
Here are the selectors used in Bootstrap 4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.</p>

```<code>@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
</code>```

Body:
Here are the selectors used in Bootstrap 4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}


问:
MySQL - At least one of something and greater than between 3 tables
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

```<code>SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom
</code>```

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

答:
You could use a nested query:

```<code>   SELECT s.name FROM
   (Sellers as s JOIN Sales as sp on sp.commercial_id = s.id) JOIN
   Product as p on p.id = sp.product_id
   WHERE MONTH(sp.date) = 1  AND YEAR(sp.date) = 2017 AND
   (SELECT SUM(Amount) FROM Sales as sp2 WHERE sp2.commercial_id = s.id
    AND sp2.product_id = p.id
    AND MONTH(sp2.date) = 1 AND YEAR(sp2.date) = 2017) > 1000
</code>```

First, join the three tables on foreign keys, and then run a nested query to compute amount of the selected seller on a specific product to check to pass the amount limitation.

Body:
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

Body:
You could use a nested query:

   SELECT s.name FROM
   (Sellers as s JOIN Sales as sp on sp.commercial_id = s.id) JOIN
   Product as p on p.id = sp.product_id
   WHERE MONTH(sp.date) = 1  AND YEAR(sp.date) = 2017 AND
   (SELECT SUM(Amount) FROM Sales as sp2 WHERE sp2.commercial_id = s.id
    AND sp2.product_id = p.id
    AND MONTH(sp2.date) = 1 AND YEAR(sp2.date) = 2017) > 1000

First, join the three tables on foreign keys, and then run a nested query to compute amount of the selected seller on a specific product to check to pass the amount limitation.


问:
NSURLSession tries to access local server over HTTPS
I am developing an ios app that makes request to a server, by making a POST request to example_url, using NSURLSession dataTaskWithRequest method.

By mistake during debugging it turned https redirection on on my local server. Of course this doesn't work but my app tried to issue some request at that time.

Now I removed https redirection on my local server settings, but my app still fails when it tries to connect to example_url, with the error

```<code>kCFStreamErrorDomainSSL, -9806
</code>```

On the server side (django) I get something like:

```<code>ERROR [django.server:basehttp:114] You're accessing the development server over HTTPS, but it only supports HTTP.
</code>```

If I change the url to example_url_2, and keep everything else unchanged (redirecting example_url_2 to the very same function call on the server), things work again.

To me it seems that NSURLSession has cached somewhere that it expects this url to be secure, and I would like to know how to reset this.

答:
Can you just try using

```<code>NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
</code>```

And use the session object with  [NSURLSession sessionWithConfiguration:configuration];

Use dataTask using that session object

Body:
I am developing an ios app that makes request to a server, by making a POST request to example_url, using NSURLSession dataTaskWithRequest method.

By mistake during debugging it turned https redirection on on my local server. Of course this doesn't work but my app tried to issue some request at that time.

Now I removed https redirection on my local server settings, but my app still fails when it tries to connect to example_url, with the error

kCFStreamErrorDomainSSL, -9806

On the server side (django) I get something like:

ERROR [django.server:basehttp:114] You're accessing the development server over HTTPS, but it only supports HTTP.

If I change the url to example_url_2, and keep everything else unchanged (redirecting example_url_2 to the very same function call on the server), things work again.

To me it seems that NSURLSession has cached somewhere that it expects this url to be secure, and I would like to know how to reset this.

Body:
Can you just try using

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

And use the session object with  [NSURLSession sessionWithConfiguration:configuration];

Use dataTask using that session object


问:
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause?

```<code>CREATE TABLE `foo` (
  `ProductID` INT(10) UNSIGNED NOT NULL,
  `AddedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;
</code>```

The error that results:

Error Code : 1293

Incorrect table definition; there can
  be only one TIMESTAMP column with
  CURRENT_TIMESTAMP in DEFAULT or ON
  UPDATE clause

答: Well a fix for you could be to put it on the UpdatedDate field and have a trigger that updates the AddedDate field with the UpdatedDate value only if AddedDate is null.</p>

Body:
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause?

CREATE TABLE `foo` (
  `ProductID` INT(10) UNSIGNED NOT NULL,
  `AddedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;

The error that results:

Error Code : 1293

Incorrect table definition; there can
  be only one TIMESTAMP column with
  CURRENT_TIMESTAMP in DEFAULT or ON
  UPDATE clause


问:
How to get the first five character of a String
I have read this question to get first char  of the string. Is there a way to get the first n number of characters from a string in C#?</p>

答:
Or you could use String.ToCharArray().

It takes int startindex and and int length as parameters and returns a char[]

```<code>new string(stringValue.ToCharArray(0,5))
</code>```

You would still need to make sure the string has the proper length, otherwise it will throw a ArgumentOutOfRangeException

Body:
Or you could use String.ToCharArray().

It takes int startindex and and int length as parameters and returns a char[]

new string(stringValue.ToCharArray(0,5))

You would still need to make sure the string has the proper length, otherwise it will throw a ArgumentOutOfRangeException


问:
Is it possible to extract scss with a specific variable into css using gulp?
I'm using gulp to compile sass into css. Right now I have color variable defined in sass.
In _varibales.scss.

```<code>  $color: #009999;
</code>```

In app.scss I have used this variable in multiple places.

```<code>    .button{
      color:$color
    }
    .background{
       background :$color
       padding:10px
    }
    .element{
       margin:0 auto
    }
</code>```

So is there a way to extract classes or id's having this variable and generate a new file called color.css using gulp?

答:
You can do two tasks in gulp to extract separate files and then get them with a link in your document:

```<code>gulp.task('scss-variables', function() {
   return gulp.src('path/variables.scss')
        .pipe(gulp.dest('variables.css'))
});
gulp.task('scss-app', function() {
   return gulp.src('path/app.scss')
        .pipe(gulp.dest('app.css'))
});
</code>```

But it is much more appropiate to import one file into the other with scss:

```<code>/* app.scss */
import 'variables';

.button{
  color:$color
}
.background{
   background :$color
   padding:10px
}
.element{
   margin:0 auto
}
</code>```

Body:
I'm using gulp to compile sass into css. Right now I have color variable defined in sass.
In _varibales.scss.

  $color: #009999;

In app.scss I have used this variable in multiple places.

    .button{
      color:$color
    }
    .background{
       background :$color
       padding:10px
    }
    .element{
       margin:0 auto
    }

So is there a way to extract classes or id's having this variable and generate a new file called color.css using gulp?

Body:
You can do two tasks in gulp to extract separate files and then get them with a link in your document:

gulp.task('scss-variables', function() {
   return gulp.src('path/variables.scss')
        .pipe(gulp.dest('variables.css'))
});
gulp.task('scss-app', function() {
   return gulp.src('path/app.scss')
        .pipe(gulp.dest('app.css'))
});

But it is much more appropiate to import one file into the other with scss:

/* app.scss */
import 'variables';

.button{
  color:$color
}
.background{
   background :$color
   padding:10px
}
.element{
   margin:0 auto
}


问:
sleep(1) + fflush(stdout) works via curl. NOT via web browser
the pauses (sleep(1)), work fine when script is ran via curl command

rather than run on a web browser.

but via web browser.. it will pause the sum of all pauses (3 x sleep(1)) and then  print them all at once

what can be done to ensure the web browser behaves like curl ?

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

int main() {
    printf("Content-type: text/plain\n\n");

    printf("%s\n", "test 1");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 2");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 3");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 4");
    fflush(stdout);

    return 0;
}
</code>```

答:
HTTP is originally designed to deliver a document. It has a header describing the document and the document itself follows in the body, normally all in one piece.

One of the headers is Content-Length:, containing the size of the body, so the client knows how much data to expect. A browser will typically attempt do fetch the whole document before starting to display it. As in your example, there's no Content-Length:, the browser just waits until the connection is closed.

Of course, setting Content-Length: will not help you here, the browser would still wait for the whole document. But there's also chunked transfer encoding for delivering a document in several pieces. You could implement it yourself, e.g. like this:

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

int main(){
    char buffer[1024];

    // note that "Content-Type" has an uppercase T, be exact when
    // implementing a protocol!
    printf("Content-Type: text/plain\n");
    printf("Transfer-Encoding: chunked\n\n");

    // snprintf() just for demonstration, you might need it for output
    // of anything more complex than just fixed strings.
    snprintf(buffer, 1024, "%s", "test 1");

    // size of next chunk:
    printf("%zx\n", strlen(buffer));

    printf("%s\n", buffer);

    fflush(stdout);
    sleep(1); // or something more sensible, like, actual work...

    // more data, finally indicate this was the last chunk:
    printf("\n");

    return 0;
}
</code>```

Some notes on the feasibility of this solution:

With CGI, as shown here, there's normally a limit on the running duration of the "script". It might be possible to configure the webserver without a time limit, otherwise this will just run into a CGI timeout. A better solution is to write this as a self-hosted web service, see Basile's answer for some links.

The nice thing about this approach is that it doesn't require client-side code, so it will work with nearly any browser (chunked transfer support is very common). The downside is you might loose the TCP connection due to some environmental condition and the only way to recover is to manually reload the page. Therefore you might want to use javascript if available and go for WebSockets (preferable, see Basile's answer) or, if not available, perform long polling.

Body:
the pauses (sleep(1)), work fine when script is ran via curl command

rather than run on a web browser.

but via web browser.. it will pause the sum of all pauses (3 x sleep(1)) and then  print them all at once

what can be done to ensure the web browser behaves like curl ?

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

int main() {
    printf("Content-type: text/plain\n\n");

    printf("%s\n", "test 1");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 2");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 3");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 4");
    fflush(stdout);

    return 0;
}

Body:
HTTP is originally designed to deliver a document. It has a header describing the document and the document itself follows in the body, normally all in one piece.

One of the headers is Content-Length:, containing the size of the body, so the client knows how much data to expect. A browser will typically attempt do fetch the whole document before starting to display it. As in your example, there's no Content-Length:, the browser just waits until the connection is closed.

Of course, setting Content-Length: will not help you here, the browser would still wait for the whole document. But there's also chunked transfer encoding for delivering a document in several pieces. You could implement it yourself, e.g. like this:

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

int main(){
    char buffer[1024];

    // note that "Content-Type" has an uppercase T, be exact when
    // implementing a protocol!
    printf("Content-Type: text/plain\n");
    printf("Transfer-Encoding: chunked\n\n");

    // snprintf() just for demonstration, you might need it for output
    // of anything more complex than just fixed strings.
    snprintf(buffer, 1024, "%s", "test 1");

    // size of next chunk:
    printf("%zx\n", strlen(buffer));

    printf("%s\n", buffer);

    fflush(stdout);
    sleep(1); // or something more sensible, like, actual work...

    // more data, finally indicate this was the last chunk:
    printf("\n");

    return 0;
}

Some notes on the feasibility of this solution:

With CGI, as shown here, there's normally a limit on the running duration of the "script". It might be possible to configure the webserver without a time limit, otherwise this will just run into a CGI timeout. A better solution is to write this as a self-hosted web service, see Basile's answer for some links.

The nice thing about this approach is that it doesn't require client-side code, so it will work with nearly any browser (chunked transfer support is very common). The downside is you might loose the TCP connection due to some environmental condition and the only way to recover is to manually reload the page. Therefore you might want to use javascript if available and go for WebSockets (preferable, see Basile's answer) or, if not available, perform long polling.


问:
How to close all children and parent windows?
I need to close all the children and parent windows when I close one window in the hierarchy.

I have three lines of windows:

My windows hierarchy - All lines start in one MainWindow. Only LoadPlayers and CreatePlayers are dialogs. All other windows are frames.

E.g. I close TablesOverview in the first line - I need to close all other windows in this line.

But windows in other lines must stay open.

Notice that TablesOverview is in two lines.

I can write the code, where I named every window that must close. But I need cleaner solution.

This code give me all opened windows - I don't know how to take only windows in one line.

```<code>Window[] windows = Window.getWindows();
</code>```

This codes give me nothing.

```<code>Window[] windows = frame.getOwnedWindows();
Component comp = frame.getParent();
</code>```

答:
Java don't provides this support implicitly. So, you have to use some work around:

Solution:

Create a new class which extends JFrame

Create a data member children of type ArrayList<Your class name>. This holds the instance created by current window

Create an member method createChildWindow(). This method will create a child window and add it in to variable children

Register for event on closing the window. For this use addWindowListener() and override public void windowClosing(java.awt.event.WindowEvent windowEvent) method. In this method traverse throw the children collection and close each child(This will eventually close its subsequent children also).

Following is the complete working code

WindowTracker.java

```<code>package com.cse.test.awt;

import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class WindowTracker extends JFrame
{
    ArrayList<WindowTracker> children;
    JLabel childrenCount;

    public WindowTracker()
    {
        children = new ArrayList<>();
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Closing..." + this.hashCode());
                for(WindowTracker child:children)
                {
                    child.dispatchEvent(new WindowEvent(child, WindowEvent.WINDOW_CLOSING));
                }
                System.out.println("Closed..." + this.hashCode());
            }
        });

        this.setLayout(new FlowLayout(FlowLayout.RIGHT));
        childrenCount = new JLabel("Children count: 0");
        this.add(childrenCount);
        JButton btn = new JButton("Create new child");
        btn.addActionListener(e -> {WindowTracker child = getNewChild();});
        this.add(btn);

        this.setSize(300, 300);
        this.setTitle("" + this.hashCode());
        this.setVisible(true);
    }

    public WindowTracker getNewChild()
    {
        WindowTracker child = new WindowTracker();
        children.add(child);
        childrenCount.setText("Children count: " + children.size());
        return child;
    }
}
</code>```

Executer.java

```<code>package com.cse.test.common;

import com.cse.test.awt.WindowTracker;

public class Executer {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new WindowTracker();

    }

}
</code>```

Body:
I need to close all the children and parent windows when I close one window in the hierarchy.

I have three lines of windows:

My windows hierarchy - All lines start in one MainWindow. Only LoadPlayers and CreatePlayers are dialogs. All other windows are frames.

E.g. I close TablesOverview in the first line - I need to close all other windows in this line.

But windows in other lines must stay open.

Notice that TablesOverview is in two lines.

I can write the code, where I named every window that must close. But I need cleaner solution.

This code give me all opened windows - I don't know how to take only windows in one line.

Window[] windows = Window.getWindows();

This codes give me nothing.

Window[] windows = frame.getOwnedWindows();
Component comp = frame.getParent();

Body:
Java don't provides this support implicitly. So, you have to use some work around:

Solution:

Create a new class which extends JFrame

Create a data member children of type ArrayList<Your class name>. This holds the instance created by current window

Create an member method createChildWindow(). This method will create a child window and add it in to variable children

Register for event on closing the window. For this use addWindowListener() and override public void windowClosing(java.awt.event.WindowEvent windowEvent) method. In this method traverse throw the children collection and close each child(This will eventually close its subsequent children also).

Following is the complete working code

WindowTracker.java

package com.cse.test.awt;

import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class WindowTracker extends JFrame
{
    ArrayList<WindowTracker> children;
    JLabel childrenCount;

    public WindowTracker()
    {
        children = new ArrayList<>();
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Closing..." + this.hashCode());
                for(WindowTracker child:children)
                {
                    child.dispatchEvent(new WindowEvent(child, WindowEvent.WINDOW_CLOSING));
                }
                System.out.println("Closed..." + this.hashCode());
            }
        });

        this.setLayout(new FlowLayout(FlowLayout.RIGHT));
        childrenCount = new JLabel("Children count: 0");
        this.add(childrenCount);
        JButton btn = new JButton("Create new child");
        btn.addActionListener(e -> {WindowTracker child = getNewChild();});
        this.add(btn);

        this.setSize(300, 300);
        this.setTitle("" + this.hashCode());
        this.setVisible(true);
    }

    public WindowTracker getNewChild()
    {
        WindowTracker child = new WindowTracker();
        children.add(child);
        childrenCount.setText("Children count: " + children.size());
        return child;
    }
}

Executer.java

package com.cse.test.common;

import com.cse.test.awt.WindowTracker;

public class Executer {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new WindowTracker();

    }

}