问:
Design Pattern to handle actions based on multiple inputs in C#
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

```<code>if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}
</code>```

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

答:
You can use a combination of two patterns in order to improve this situation Chain of Responsibility && Strategy Pattern.

Strategy Pattern -- this pattern will help you to solve the country's conditional. You'll have to make an AbstractCountryStrategy + a concrete Strategy class for each country in our system.

The Strategy class will incapsulate a pretty simple line of code (the line that uses the other pattern Chain of Responsibility)

```<code>class USCountryStrategy {

    public void execute(type) {
        new USCountryTypeAHandler()
              .setNext(new USCountryTypeBHandler()
              .setNext(...))
           .executeBasedOn(type)
    }
}
</code>```

Chain of Responsibility -- this pattern will help you to solve the type's conditional (but you'll still need to use a small if/else for this pattern just to check if your current handler has a next handler attached).

Overall Idea: For each type you'll have a small class that checks if it's able to solve your request ... similar to:

```<code>if(paramType.equals(this.type)
    this.execute();
    // if I can solve your request than I'll execute it myself
else if(this.next)
    this.next.executeBasedOn(paramType);
    // if I can't solve your request than I'll pass it on to the next handler
else
    throw RuntimeException(...)
    // nobody can solve your request (because I can't && this.next is null)
</code>```

Is this useful or I'm just adding complexity to my code source?

Yes, it's useful when you have switch in your code, remember that soon you'll have to change this function/class. A switch is not extendable, is hard to maintain, gets very complex fast ("spaghetti code") and you might need to use it twice in your code base.

See https://github.com/kamranahmedse/design-patterns-for-humans for better & complete examples.

Body:
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

Body:
You can use a combination of two patterns in order to improve this situation Chain of Responsibility && Strategy Pattern.

Strategy Pattern -- this pattern will help you to solve the country's conditional. You'll have to make an AbstractCountryStrategy + a concrete Strategy class for each country in our system.

The Strategy class will incapsulate a pretty simple line of code (the line that uses the other pattern Chain of Responsibility)

class USCountryStrategy {

    public void execute(type) {
        new USCountryTypeAHandler()
              .setNext(new USCountryTypeBHandler()
              .setNext(...))
           .executeBasedOn(type)
    }
}

Chain of Responsibility -- this pattern will help you to solve the type's conditional (but you'll still need to use a small if/else for this pattern just to check if your current handler has a next handler attached).

Overall Idea: For each type you'll have a small class that checks if it's able to solve your request ... similar to:

if(paramType.equals(this.type)
    this.execute();
    // if I can solve your request than I'll execute it myself
else if(this.next)
    this.next.executeBasedOn(paramType);
    // if I can't solve your request than I'll pass it on to the next handler
else
    throw RuntimeException(...)
    // nobody can solve your request (because I can't && this.next is null)

Is this useful or I'm just adding complexity to my code source?

Yes, it's useful when you have switch in your code, remember that soon you'll have to change this function/class. A switch is not extendable, is hard to maintain, gets very complex fast ("spaghetti code") and you might need to use it twice in your code base.

See https://github.com/kamranahmedse/design-patterns-for-humans for better & complete examples.


来源: stackexchange

问:
Mysql Database error connection
Might sound obvious but my database isn't connecting to my phpmyadmin.

is there something I did wrong? I'm using mamp as a backend server for php use.

```<code> <?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','blurt');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }

    $connection = mysqli_connect('localhost', 'root', '', 'blurt');
    if (!$connection) {
        die("Database Connection Failed" . mysqli_error($connection));
    } $select_db = mysqli_select_db($connection, 'blurt');
    if (!$select_db) {
        die("Database Selection Failed" . mysqli_error($connection));
    }
    ?>
</code>```

答:
the solution is very sample

here : http://curs.io/KN97HAOB

ContentLicense: CC BY-SA 3.0

Title: Mysql Database error connection

Body:
Might sound obvious but my database isn't connecting to my phpmyadmin.

is there something I did wrong? I'm using mamp as a backend server for php use.

 <?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','blurt');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }

    $connection = mysqli_connect('localhost', 'root', '', 'blurt');
    if (!$connection) {
        die("Database Connection Failed" . mysqli_error($connection));
    } $select_db = mysqli_select_db($connection, 'blurt');
    if (!$select_db) {
        die("Database Selection Failed" . mysqli_error($connection));
    }
    ?>


问:
How to add progress bar until loop execution is finished?
I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.

here is my java code

```<code>    public class Image_Recognition extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image__recognition);

        Button btnNextPage = (Button) findViewById(R.id.btnNextPage);

            btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                        SparseArray<TextBlock> items = textRecognizer.detect(frame);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < items.size(); ++i) {
                            TextBlock item = items.valueAt(i);
                            stringBuilder.append(item.getValue());
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append('.');
                        txtResult.setText(stringBuilder.toString());

                        str = stringBuilder.toString();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);

                }
            });
        }
    //}
}
</code>```

答:
You can try with this.</p>

```<code>final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    dialog.show(Image_Recognition.this, "", "Please wait...", true);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                            if (!textRecognizer.isOperational())
                                Log.e("ERROR", "Detector dependencies are not yet available");
                            else {

                                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                                SparseArray<TextBlock> items = textRecognizer.detect(frame);
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int i = 0; i < items.size(); ++i) {
                                    TextBlock item = items.valueAt(i);
                                    stringBuilder.append(item.getValue());
                                    stringBuilder.append("\n");
                                }
                                stringBuilder.append('.');
                                txtResult.setText(stringBuilder.toString());

                                str = stringBuilder.toString();
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    dialog.setCancelable(true);
                                    Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                                    myintent.putExtra("translate", str);
                                    startActivity(myintent);
                                }
                            });
                        }
                    },5000);
</code>```

Body:
I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.

here is my java code

    public class Image_Recognition extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image__recognition);

        Button btnNextPage = (Button) findViewById(R.id.btnNextPage);

            btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                        SparseArray<TextBlock> items = textRecognizer.detect(frame);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < items.size(); ++i) {
                            TextBlock item = items.valueAt(i);
                            stringBuilder.append(item.getValue());
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append('.');
                        txtResult.setText(stringBuilder.toString());

                        str = stringBuilder.toString();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);

                }
            });
        }
    //}
}

Body:
You can try with this.

final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    dialog.show(Image_Recognition.this, "", "Please wait...", true);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                            if (!textRecognizer.isOperational())
                                Log.e("ERROR", "Detector dependencies are not yet available");
                            else {

                                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                                SparseArray<TextBlock> items = textRecognizer.detect(frame);
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int i = 0; i < items.size(); ++i) {
                                    TextBlock item = items.valueAt(i);
                                    stringBuilder.append(item.getValue());
                                    stringBuilder.append("\n");
                                }
                                stringBuilder.append('.');
                                txtResult.setText(stringBuilder.toString());

                                str = stringBuilder.toString();
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    dialog.setCancelable(true);
                                    Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                                    myintent.putExtra("translate", str);
                                    startActivity(myintent);
                                }
                            });
                        }
                    },5000);


问:
python 3.6 sql database connection
I am trying to insert a row into my postgresql database with a table created from

```<code>    CREATE TABLE public.coinbase_btc_usd
(
  id bigserial primary key,
  price integer NOT NULL,
  buy integer NOT NULL,
  sell integer NOT NULL,
  "timestamp" timestamp with time zone
)
</code>```

However when my python 3.6 script runs and tries to add a row using psycopg2 like this it returns an error saying "no results to fetch" and nothing is added to my db.

```<code>        sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
                " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"

    print(sql_query)

    cur.execute(sql_query)
</code>```

I also printed the sql_query variable to see exactly what was getting attempted to execute and this was printed to the output

```<code>INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (16392.10, 16563.40, 16235.42, '2015-10-10 06:44:33.8672177')
</code>```

答:
Make sure that you are committing the transaction:

```<code>cur.execute(sql_query)
conn.commit()
</code>```

Or you can enable auto commit to commit each query immediately after execution:

```<code>conn.autocommit = True
</code>```

Furthermore, it costs nothing to prevent SQL injection attack - just use parametersied queries. In fact your code will actually be cleaner as well as safer:

```<code>sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)"
cur.execute(sql_query, (exchange_rate, buy_rate, sell_rate, timestamp))
conn.commit()
</code>```

Title: python 3.6 sql database connection

Body:
I am trying to insert a row into my postgresql database with a table created from

    CREATE TABLE public.coinbase_btc_usd
(
  id bigserial primary key,
  price integer NOT NULL,
  buy integer NOT NULL,
  sell integer NOT NULL,
  "timestamp" timestamp with time zone
)

However when my python 3.6 script runs and tries to add a row using psycopg2 like this it returns an error saying "no results to fetch" and nothing is added to my db.

        sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
                " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"

    print(sql_query)

    cur.execute(sql_query)

I also printed the sql_query variable to see exactly what was getting attempted to execute and this was printed to the output

INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (16392.10, 16563.40, 16235.42, '2015-10-10 06:44:33.8672177')

Body:
Make sure that you are committing the transaction:

cur.execute(sql_query)
conn.commit()

Or you can enable auto commit to commit each query immediately after execution:

conn.autocommit = True

Furthermore, it costs nothing to prevent SQL injection attack - just use parametersied queries. In fact your code will actually be cleaner as well as safer:

sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)"
cur.execute(sql_query, (exchange_rate, buy_rate, sell_rate, timestamp))
conn.commit()


问:
How to add JavaFX Preloader ProgressBar on top of an FXML scene
I am new to Java and JavaFX all together, so please be patient with me if I am asking the wrong question here.

I am trying to add preloader Scene to an application I built: I was able to add the preloader using the code below. It's the default preloader and it looks very basic. So, here is my question. 1) how to add percentage progress status instead of progressbar. 2) Is it possible to load this progress bar on top of an FXML scene

```<code>Preloader

public class JavaFXPreloader3 extends Preloader {

    ProgressBar bar;
    Stage stage;

private Scene createPreloaderScene() throws IOException {

    Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml"));

    ProgressIndicator pi = new ProgressIndicator();
    BorderPane p = new BorderPane();
    p.setCenter(pi);
    return new Scene(p, 300, 150);

}

    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;
        stage.setScene(createPreloaderScene());
        stage.show();
    }

    @Override
    public void handleStateChangeNotification(StateChangeNotification scn) {
        if (scn.getType() == StateChangeNotification.Type.BEFORE_START) {
            stage.hide();
        }
    }

    @Override
    public void handleProgressNotification(ProgressNotification pn) {
        bar.setProgress(pn.getProgress());
    }

}
</code>```

How do I return root scene instead of  the BorderPane p including the Progress Indicator:

```<code> ProgressIndicator pi = new ProgressIndicator();
    BorderPane p = new BorderPane();
    p.setCenter(pi);
    return new Scene(p, 300, 150);
</code>```

答:
This is a excellent tutorial for creating a PreLoader.

https://docs.oracle.com/javafx/2/deployment/preloaders.htm

Body:
I am new to Java and JavaFX all together, so please be patient with me if I am asking the wrong question here.

I am trying to add preloader Scene to an application I built: I was able to add the preloader using the code below. It's the default preloader and it looks very basic. So, here is my question. 1) how to add percentage progress status instead of progressbar. 2) Is it possible to load this progress bar on top of an FXML scene

Preloader

public class JavaFXPreloader3 extends Preloader {

    ProgressBar bar;
    Stage stage;

private Scene createPreloaderScene() throws IOException {

    Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml"));

    ProgressIndicator pi = new ProgressIndicator();
    BorderPane p = new BorderPane();
    p.setCenter(pi);
    return new Scene(p, 300, 150);

}

    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;
        stage.setScene(createPreloaderScene());
        stage.show();
    }

    @Override
    public void handleStateChangeNotification(StateChangeNotification scn) {
        if (scn.getType() == StateChangeNotification.Type.BEFORE_START) {
            stage.hide();
        }
    }

    @Override
    public void handleProgressNotification(ProgressNotification pn) {
        bar.setProgress(pn.getProgress());
    }

}

How do I return root scene instead of  the BorderPane p including the Progress Indicator:

 ProgressIndicator pi = new ProgressIndicator();
    BorderPane p = new BorderPane();
    p.setCenter(pi);
    return new Scene(p, 300, 150);


问:
How to include Javascript and CSS files with Express.js
I have a simple node server running in a file called page.js just as a test of a system I am trying to setup.  In that file I have the following:

```<code>var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.sendFile('/Users/JohnFarkerson/Documents/SublimeFolder/index.html');
});

app.get('/*', function(req, res) {
    res.send("404 –– Page not found");
});

var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port
});
</code>```

That path to the index file leads to the same directory (SublimeFolder) as the .js file is saved in.  Also in that directory are my javascript and css files. Within index.html, I have the following lines:

```<code><script language="javascript" type="text/javascript" src="myScript.js"></script>
<link rel="stylesheet" type="text/css" href="myStyleSheet.css">
</code>```

I have tried changing those paths within index.html to the full path on my computer, but that didn't solve my problem.  When I find the index.html file in Finder and double click, it opens file:///Users/JohnFarkerson/Documents/SublimeFolder/index.html in Chrome, which looks perfect.  However, when I run the server in node and then go to http://localhost:8080/, the page loads a very bare-bones version without any of my javascript or css.  What am I doing wrong here?

Edit:

It now works.  index.html looks like:

```<code>var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/css', express.static(__dirname + '/css'));

app.get('/', function(req, res) {
    res.sendFile('/Users/JohnFarkerson/Documents/SublimeFolder/index.html');
});

app.get('/*', function(req, res) {
    res.send("404 –– Page not found");
});

var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port
});
</code>```

答:
If you open file:///Users/JohnFarkerson/Documents/SublimeFolder/index.html in Chrome, the protocol is file protocol.  But if you open http://localhost:8080/, it's a http protocol. The express create a http server. The .html .css and .js files are static files of http server.

Maybe your directory look like this:

```<code>SublimeFolder
|--- index.html
|--- myScript.js
|--- myStyleSheet.css
</code>```

In a file protocol, you use absolute path in your disk, the root path is /, so it works fine.

But in a http protocol, the root path is http server root, may it will defined in your code, such as:

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

The http server root is your_project_path/public, and you should put your js and css files in your_project_path/public directory, and then use root path to link theme. For example, the public directory structure is:

```<code>your_project_path/public
|--- myScript.js
|--- myStyleSheet.css
</code>```

And the script tag is .

You can use Express application generator to create an express project, and check the project structure, then you could understand it.

Body:
I have a simple node server running in a file called page.js just as a test of a system I am trying to setup.  In that file I have the following:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.sendFile('/Users/JohnFarkerson/Documents/SublimeFolder/index.html');
});

app.get('/*', function(req, res) {
    res.send("404 –– Page not found");
});

var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port
});

That path to the index file leads to the same directory (SublimeFolder) as the .js file is saved in.  Also in that directory are my javascript and css files. Within index.html, I have the following lines:

<link rel="stylesheet" type="text/css" href="myStyleSheet.css">

I have tried changing those paths within index.html to the full path on my computer, but that didn't solve my problem.  When I find the index.html file in Finder and double click, it opens file:///Users/JohnFarkerson/Documents/SublimeFolder/index.html in Chrome, which looks perfect.  However, when I run the server in node and then go to http://localhost:8080/, the page loads a very bare-bones version without any of my javascript or css.  What am I doing wrong here?

Edit:

It now works.  index.html looks like:

var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/css', express.static(__dirname + '/css'));

app.get('/', function(req, res) {
    res.sendFile('/Users/JohnFarkerson/Documents/SublimeFolder/index.html');
});

app.get('/*', function(req, res) {
    res.send("404 –– Page not found");
});

var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port
});

Body:
If you open file:///Users/JohnFarkerson/Documents/SublimeFolder/index.html in Chrome, the protocol is file protocol.  But if you open http://localhost:8080/, it's a http protocol. The express create a http server. The .html .css and .js files are static files of http server.

Maybe your directory look like this:

SublimeFolder
|--- index.html
|--- myScript.js
|--- myStyleSheet.css

In a file protocol, you use absolute path in your disk, the root path is /, so it works fine.

But in a http protocol, the root path is http server root, may it will defined in your code, such as:

app.use(express.static(path.join(__dirname, 'public')));

The http server root is your_project_path/public, and you should put your js and css files in your_project_path/public directory, and then use root path to link theme. For example, the public directory structure is:

your_project_path/public
|--- myScript.js
|--- myStyleSheet.css

And the script tag is <script src="/myScript.js"></script>.

You can use Express application generator to create an express project, and check the project structure, then you could understand it.


问:
Subtracts values one list from another in javascript
How to remove all values from var a = [1,2,2,2,3] which are present in var b=[2]If a values is present in b variable all of its occurrences must be remove

```<code> var a = [1,2,2,2,5];
 var b = [2];
 const result = a.filter(function(el){

  return /// which condition .?

 });
</code>```

How to remove the b var value. and we have many logics please answer it briefly

答:
 var a = [1,2,2,2,5];
 var b = [2];
var result= a.filter(function(x) {
  return b.indexOf(x) < 0;
});
console.log(result)```

Body:
How to remove all values from var a = [1,2,2,2,3] which are present in var b=[2]If a values is present in b variable all of its occurrences must be remove

 var a = [1,2,2,2,5];
 var b = [2];
 const result = a.filter(function(el){

  return /// which condition .?

 });

How to remove the b var value. and we have many logics please answer it briefly


问:
VBA and concatenate function
I'm actually looking to optimize my existing concatenate formula that I use to configure a bunch of controller (networking)

I have Sheet1 where I enter all the details requiered from A2 to E2
I have Sheet2 where that produce the overall concatenate, that include the valude from Sheet1.A2 and include some command, here is the concatenate formula:

=CONCATENATE("ap ",Imported_Data!B2,CHAR(10)," ip enable ",CHAR(10)," ip mode static ",CHAR(10)," ip addr ",Imported_Data!A2," ",Imported_Data!L$2," gateway ",Imported_Data!L$3,CHAR(10)," ip name-server ",Imported_Data!L$4," ",Imported_Data!L$5,CHAR(10)," devname ",Imported_Data!C2,CHAR(10)," description ",CHAR(147),Imported_Data!D2,CHAR(147),CHAR(10)," location ",CHAR(147),Imported_Data!E2,CHAR(147),CHAR(10)," end")

and the result below:

```<code>"ap 00:00:00:00:00:00
 ip enable
 ip mode static
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description “Description“
 location “location“
 end"
</code>```

in order to have it accepted on the controller is to manipulate the result, copy the concatenate result into notepad++, remove the "" that added from the concatenate formula, and replace the CHAR(147) by "" ( that the only way I've found to have it working)

what I would like to have in VBA is a filter that will:

1) remove the "" at the begining and end of the block of concatenate
2) replace the `` with "" at the description and location

end result should be:

```<code>ap 00:00:00:00:00:00
 ip enable
 ip mode static
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description "Description"
 location "location"
 end
</code>```

any suggestion/advise?

答:
Here's one way which you should check if it suits your purpose.

First edit formula to replace CHAR(147) to CHAR(34) like below:

=CONCATENATE("ap ",Imported_Data!B2,CHAR(10)," ip enable ",CHAR(10)," ip mode static ",CHAR(10)," ip addr ",Imported_Data!A2," ",Imported_Data!L$2," gateway ",Imported_Data!L$3,CHAR(10)," ip name-server ",Imported_Data!L$4," ",Imported_Data!L$5,CHAR(10)," devname ",Imported_Data!C2,CHAR(10)," description ",CHAR(34),Imported_Data!D2,CHAR(34),CHAR(10)," location ",CHAR(34),Imported_Data!E2,CHAR(34),CHAR(10)," end")

And then paste below code to VBE. Make sure to update cell references to suit.

```<code>Public Sub CopyConcatToNotepad()
    Dim objDataObj As Object
    Dim strFormula

    strFormula = Split(Sheets(2).Range("A1").Value, vbCrLf) 'Write correct cell reference for CONCATENATE formula cell!
    Dim strOut As String
    strOut = Join(strFormula, vbCrLf)

    'This is ClsID of MSFORMS Data Object
    Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    objDataObj.SetText strOut, 1
    objDataObj.PutInClipboard

    Set objDataObj = Nothing
End Sub
</code>```

Then run this code to copy text as desired to clipboard. If you will do CTRL+V in Notepad++ then it will give desired results!

EDIT: Revised code to incorporate requirements.

```<code>Public Sub CopyConcatToNotepadSelCells()
Dim objDataObj As Object
Dim rG As Range
Dim strFormula
Dim strOut As String

'Loop through all selected cells and build concat string
For Each rG In Selection
    strFormula = Split(rG.Value, vbCrLf)
    If Len(strOut) = 0 Then
        strOut = Join(strFormula, vbCrLf)
    Else
        strOut = strOut & vbCrLf & Join(strFormula, vbCrLf)
    End If
Next rG

'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strOut, 1
objDataObj.PutInClipboard

Set objDataObj = Nothing
End Sub
</code>```

Title: VBA and concatenate function

Body:
I'm actually looking to optimize my existing concatenate formula that I use to configure a bunch of controller (networking)

I have Sheet1 where I enter all the details requiered from A2 to E2
I have Sheet2 where that produce the overall concatenate, that include the valude from Sheet1.A2 and include some command, here is the concatenate formula:

=CONCATENATE("ap ",Imported_Data!B2,CHAR(10)," ip enable ",CHAR(10)," ip mode static ",CHAR(10)," ip addr ",Imported_Data!A2," ",Imported_Data!L$2," gateway ",Imported_Data!L$3,CHAR(10)," ip name-server ",Imported_Data!L$4," ",Imported_Data!L$5,CHAR(10)," devname ",Imported_Data!C2,CHAR(10)," description ",CHAR(147),Imported_Data!D2,CHAR(147),CHAR(10)," location ",CHAR(147),Imported_Data!E2,CHAR(147),CHAR(10)," end")

and the result below:

"ap 00:00:00:00:00:00
 ip enable
 ip mode static
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description “Description“
 location “location“
 end"

in order to have it accepted on the controller is to manipulate the result, copy the concatenate result into notepad++, remove the "" that added from the concatenate formula, and replace the CHAR(147) by "" ( that the only way I've found to have it working)

what I would like to have in VBA is a filter that will:

1) remove the "" at the begining and end of the block of concatenate
2) replace the `` with "" at the description and location

end result should be:

ap 00:00:00:00:00:00
 ip enable
 ip mode static
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description "Description"
 location "location"
 end

any suggestion/advise?

Body:
Here's one way which you should check if it suits your purpose.

First edit formula to replace CHAR(147) to CHAR(34) like below:

=CONCATENATE("ap ",Imported_Data!B2,CHAR(10)," ip enable ",CHAR(10)," ip mode static ",CHAR(10)," ip addr ",Imported_Data!A2," ",Imported_Data!L$2," gateway ",Imported_Data!L$3,CHAR(10)," ip name-server ",Imported_Data!L$4," ",Imported_Data!L$5,CHAR(10)," devname ",Imported_Data!C2,CHAR(10)," description ",CHAR(34),Imported_Data!D2,CHAR(34),CHAR(10)," location ",CHAR(34),Imported_Data!E2,CHAR(34),CHAR(10)," end")

And then paste below code to VBE. Make sure to update cell references to suit.

Public Sub CopyConcatToNotepad()
    Dim objDataObj As Object
    Dim strFormula

    strFormula = Split(Sheets(2).Range("A1").Value, vbCrLf) 'Write correct cell reference for CONCATENATE formula cell!
    Dim strOut As String
    strOut = Join(strFormula, vbCrLf)

    'This is ClsID of MSFORMS Data Object
    Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    objDataObj.SetText strOut, 1
    objDataObj.PutInClipboard

    Set objDataObj = Nothing
End Sub

Then run this code to copy text as desired to clipboard. If you will do CTRL+V in Notepad++ then it will give desired results!

EDIT: Revised code to incorporate requirements.

Public Sub CopyConcatToNotepadSelCells()
Dim objDataObj As Object
Dim rG As Range
Dim strFormula
Dim strOut As String

'Loop through all selected cells and build concat string
For Each rG In Selection
    strFormula = Split(rG.Value, vbCrLf)
    If Len(strOut) = 0 Then
        strOut = Join(strFormula, vbCrLf)
    Else
        strOut = strOut & vbCrLf & Join(strFormula, vbCrLf)
    End If
Next rG

'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strOut, 1
objDataObj.PutInClipboard

Set objDataObj = Nothing
End Sub


问:
How to Remove tabs in specific page in ionic2?
I am new to ionic2, I want to remove tabs from specific page.
I am using below code :

```<code>import { NavController, App } from 'ionic-angular';

constructor(public navCtrl: NavController, public app: App){

this.navCtrl.push(MainPage);
}
</code>```

but whenever using above code all pages tabs are removed.
I want to remove specific page only.
Please help me....

答:
You can hide tabs on sub pages of a tab by using the tabsHideOnSubPages attribute:

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Contacts" tabIcon="contacts"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Profile" tabIcon="information-circle" tabsHideOnSubPages="true"></ion-tab>
</ion-tabs>
</code>```

This will not show tabs for sub pages within this tab.

Body:
I am new to ionic2, I want to remove tabs from specific page.
I am using below code :

import { NavController, App } from 'ionic-angular';

constructor(public navCtrl: NavController, public app: App){

this.navCtrl.push(MainPage);
}

but whenever using above code all pages tabs are removed.
I want to remove specific page only.
Please help me....

Body:
You can hide tabs on sub pages of a tab by using the tabsHideOnSubPages attribute:

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Contacts" tabIcon="contacts"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Profile" tabIcon="information-circle" tabsHideOnSubPages="true"></ion-tab>
</ion-tabs>

This will not show tabs for sub pages within this tab.

ContentLicense: CC BY-SA 4.0


问:
a:contains(".obj")') to a variable
I'm trying to check all my links for the word .obj in a certain text.
So far I've bin able to hide that link. But I need to get that link in a variable and output it to the console.
How would I do this right?

$(document).ready(function () {
    //Hides all link containing .obj
    $('a:contains(".obj")').hide();

    //Get link in variable (DOES NOT WORK)
    var $objlink = $('a:contains(".obj")');

    //Show variable in console
    console.log($objlink);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

.obj 1
.obj 2
.foobar</code>```

答:
Instead of outputting the whole jquery object, go through it and log the href.

```<code>$objlink.each(function(){

   console.log($(this).attr('href'))

})
</code>```

Title: a:contains(".obj")') to a variable

Body:
I'm trying to check all my links for the word .obj in a certain text.
So far I've bin able to hide that link. But I need to get that link in a variable and output it to the console.
How would I do this right?

$(document).ready(function () {
    //Hides all link containing .obj
    $('a:contains(".obj")').hide();

    //Get link in variable (DOES NOT WORK)
    var $objlink = $('a:contains(".obj")');

    //Show variable in console
    console.log($objlink);
});

.obj 1
.obj 2
.foobar

Body:
Instead of outputting the whole jquery object, go through it and log the href.

$objlink.each(function(){

   console.log($(this).attr('href'))

})


问:
How to inject Models, Services in all Controllers by default while creating a node js app with express
I have a little experience with Sails and I really like the way it automatically injects all the models and services inside controllers so we save ourself from requiring all those at the beginning of the script, but the framework is very bulky.

So, I am making a project using express framework and want to implement this feature where I do not need to require Services and Models in each and every Controller script.

Thanks.

答:
you can create a index file for exporting all services and models. Then just include it into your controllers

in service.js

```<code>exports = {
    auth    : require('./auth'),
    user    : require('./user'),
    and many more
}
</code>```

in controller

```<code>var service = require('service')
</code>```

use services as service.auth, service.user

Thanks

Body:
you can create a index file for exporting all services and models. Then just include it into your controllers

in service.js

exports = {
    auth    : require('./auth'),
    user    : require('./user'),
    and many more
}

in controller

var service = require('service')

use services as service.auth, service.user

Thanks


问:
Can i parse SQL query using vb.net?
I want to convert my MySQL to MSsql using an automated program using vb.net. Do you have any links or parsing engine that could parse Mysql?

I heard i could be done with regex, but the process is somewhat confusing.
Please Help.

答:
My experience with both: blah. They really do things in a way that is frustratingly different, and any "tool" meant to streamline this process is going to mean more debugging and rabbit-holing than is worth. This is a penny-wise, pound-foolish equation, IMHO.

If it really is complex, consider porting to ADO.NET or some other connector library that abstracts the actual SQL generation away from the code itself. Otherwise, just do it manually and test, test, test, and retest. My understanding of both is it's not worth it to "automagicallymate it".

ContentLicense: CC BY-SA 2.5

Title: Can i parse SQL query using vb.net?


问:
How do I read data from an SQLite database?
I am trying to read a row using a column name as key but I am somehow unable to get it.

Example I entered a string "name"

the list just shows "1" in the ListView

here's my insert code

```<code>public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }
</code>```

And here's how I query the data:

```<code>public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();
        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {

                allStudents.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        return allStudents;
    }
</code>```

```<code>package test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDBAdapter {
    public static final String DATABASE_NAME = "data";

    private Context mContext;
    private MyDBHelper mDbHelper;
    private SQLiteDatabase mSqliteDatabase;
    private int DATABASE_VERSION = 1;

    public MyDBAdapter(Context context){
        this.mContext = context;
        mDbHelper = new MyDBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void open(){
        mSqliteDatabase = mDbHelper.getWritableDatabase();
    }

    public class MyDBHelper extends SQLiteOpenHelper{
        public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db){
            String query = "CREATE TABLE students(id integer primary key autoincrement, name text, faculty integer);";
            db.execSQL(query);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            String query = "DROP TABLE IF EXISTS students;";
            db.execSQL(query);
            onCreate(db);
        }
    }

    public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

//    public List<String> selectAllStudents(){
//        List<String> allStudents = new ArrayList<>();
//        Cursor cursor = mSqliteDatabase.query("students", null, null, null, null, null, null);
//        if(cursor != null && cursor.moveToFirst()){
//            do {
//                allStudents.add(cursor.getString(1));
//            } while (cursor.moveToNext());
//        }
//        return allStudents;
//    }

    public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();

        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {
                if(cursor.getString(cursor.getColumnIndex("faculty")).equals("1")){
                    allStudents.add(cursor.getString(cursor.getColumnIndex("name")));
                }
//                allStudents.add(cursor.getString(0));

            } while (cursor.moveToNext());
        }
        return allStudents;
    }

    public void deleteAllEngineers(){
        mSqliteDatabase.delete("students", null, null);
    }
}
</code>```

I added my DB java file please see it.

答:
Using cursor.getString(0) is (IMO) bad practice. That assumes you actually know the column index, and while you can find it fairly easily, it's better doing this:

```<code>allStudents.add(cursor.getString(cursor.getColumnIndex("name")));
</code>```

Preferably declaring the column name as a static constant though, but this still works assuming you write the name right.

The reason you're getting "1" as the output is most likely because the column at 0 doesn't point to the name column.

Body:
I am trying to read a row using a column name as key but I am somehow unable to get it.

Example I entered a string "name"

the list just shows "1" in the ListView

here's my insert code

public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

And here's how I query the data:

public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();
        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {

                allStudents.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        return allStudents;
    }

package test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDBAdapter {
    public static final String DATABASE_NAME = "data";

    private Context mContext;
    private MyDBHelper mDbHelper;
    private SQLiteDatabase mSqliteDatabase;
    private int DATABASE_VERSION = 1;

    public MyDBAdapter(Context context){
        this.mContext = context;
        mDbHelper = new MyDBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void open(){
        mSqliteDatabase = mDbHelper.getWritableDatabase();
    }

    public class MyDBHelper extends SQLiteOpenHelper{
        public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db){
            String query = "CREATE TABLE students(id integer primary key autoincrement, name text, faculty integer);";
            db.execSQL(query);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            String query = "DROP TABLE IF EXISTS students;";
            db.execSQL(query);
            onCreate(db);
        }
    }

    public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

//    public List<String> selectAllStudents(){
//        List<String> allStudents = new ArrayList<>();
//        Cursor cursor = mSqliteDatabase.query("students", null, null, null, null, null, null);
//        if(cursor != null && cursor.moveToFirst()){
//            do {
//                allStudents.add(cursor.getString(1));
//            } while (cursor.moveToNext());
//        }
//        return allStudents;
//    }

    public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();

        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {
                if(cursor.getString(cursor.getColumnIndex("faculty")).equals("1")){
                    allStudents.add(cursor.getString(cursor.getColumnIndex("name")));
                }
//                allStudents.add(cursor.getString(0));

            } while (cursor.moveToNext());
        }
        return allStudents;
    }

    public void deleteAllEngineers(){
        mSqliteDatabase.delete("students", null, null);
    }
}

I added my DB java file please see it.

Body:
Using cursor.getString(0) is (IMO) bad practice. That assumes you actually know the column index, and while you can find it fairly easily, it's better doing this:

allStudents.add(cursor.getString(cursor.getColumnIndex("name")));

Preferably declaring the column name as a static constant though, but this still works assuming you write the name right.

The reason you're getting "1" as the output is most likely because the column at 0 doesn't point to the name column.


问:
How can I divide one for loop to several loops and run them with threads to get shorter run time?
I am new to C# multi-threading. I have defined a simple for loop that when I press a button it starts counting from 0 to 10000 and using a stopwatch I captured the time period that it takes to finish this loop.

```<code>private void button2_Click(object sender, EventArgs e)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (double i = 0; i < 5000; i++)
        {
            Console.WriteLine(i.ToString() + ", ");

        }
        sw.Stop();
        TimeSpan ts = sw.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
        MessageBox.Show(elapsedTime);
    }
</code>```

On my laptop it takes: 15':28''

On the other hand, I tried multi-threading in order to see whether I can shorten this time or not. What I did was:

1) Defining 5 functions (Func1,Func2, ...., Func5)

2) Inside each function I defined a for loop that counts one fifth of the main for loop:

Func1: 0 - 1000

Func2: 1000 - 2000

Func3: 2000 - 3000

Func4: 3000 - 4000

Func5: 4000 - 4000

3) Finally I defined five different threads and called each function in each of the threads.

Logically I expected to get the result in a shorter time, but the run time was the same as the time that I got without threads.

```<code>private void button1_Click(object sender, EventArgs e)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Thread T1 = new Thread(new ThreadStart(Func1));
        T1.Start();

        Thread T2 = new Thread(new ThreadStart(Func2));
        T2.Start();

        Thread T3 = new Thread(new ThreadStart(Func3));
        T3.Start();

        Thread T4 = new Thread(new ThreadStart(Func4));
        T4.Start();

        Thread T5 = new Thread(new ThreadStart(Func5));
        T5.Start();

        T1.Join();
        T2.Join();
        T3.Join();
        T4.Join();
        T5.Join();
        sw.Stop();
        TimeSpan ts = sw.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
        MessageBox.Show(elapsedTime);
    }
</code>```

Can I shorten the run time using threads? If yes, how? and if no, what method should I use?

I tested this code to see the functionality of C# threads, It may seem useless but I will use it in an image processing app to shorten the run time of several for loops.

Please help.

答:
You have a restaurant. You only have one cook that cooks great but he's darn slow. You have one waiter that takes all the orders and hands them down to the cook. This is too slow and customers are starting to complain.

You have a bright idea (or not). You hire 100 waiters, that should make things much faster! Ok, now you've got orders getting to the cook a whole lot faster, but the food is still coming out at the same speed. How's that possible?

Change cook for Console.WriteLine and waiters for Threads and thats essentially what you are trying to do. You see how pointless it is?

Now, a whole different story would be if you have 10 cooks (processors) and only one waiter (thread). In that case, hiring 9 more waiters would make perfect sense.

Moral of the story? Use more threads and parallelize when you have processor bound tasks to perform and you have processors waiting around idly. Otherwise, there is normally better ways to do things than spinning up useless threads.

Body:
I am new to C# multi-threading. I have defined a simple for loop that when I press a button it starts counting from 0 to 10000 and using a stopwatch I captured the time period that it takes to finish this loop.

private void button2_Click(object sender, EventArgs e)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (double i = 0; i < 5000; i++)
        {
            Console.WriteLine(i.ToString() + ", ");

        }
        sw.Stop();
        TimeSpan ts = sw.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
        MessageBox.Show(elapsedTime);
    }

On my laptop it takes: 15':28''

On the other hand, I tried multi-threading in order to see whether I can shorten this time or not. What I did was:

1) Defining 5 functions (Func1,Func2, ...., Func5)

2) Inside each function I defined a for loop that counts one fifth of the main for loop:

Func1: 0 - 1000

Func2: 1000 - 2000

Func3: 2000 - 3000

Func4: 3000 - 4000

Func5: 4000 - 4000

3) Finally I defined five different threads and called each function in each of the threads.

Logically I expected to get the result in a shorter time, but the run time was the same as the time that I got without threads.

private void button1_Click(object sender, EventArgs e)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Thread T1 = new Thread(new ThreadStart(Func1));
        T1.Start();

        Thread T2 = new Thread(new ThreadStart(Func2));
        T2.Start();

        Thread T3 = new Thread(new ThreadStart(Func3));
        T3.Start();

        Thread T4 = new Thread(new ThreadStart(Func4));
        T4.Start();

        Thread T5 = new Thread(new ThreadStart(Func5));
        T5.Start();

        T1.Join();
        T2.Join();
        T3.Join();
        T4.Join();
        T5.Join();
        sw.Stop();
        TimeSpan ts = sw.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
        MessageBox.Show(elapsedTime);
    }

Can I shorten the run time using threads? If yes, how? and if no, what method should I use?

I tested this code to see the functionality of C# threads, It may seem useless but I will use it in an image processing app to shorten the run time of several for loops.

Please help.


问:
Quotes generating html entity
I'm trying to replace a bunch of consecutive

```<code>var: $("#var").val()
</code>```

lines in my JS script with a simple loop in c# like this:

```<code>@foreach(var q in myList){
    @(q.var + ": $('#" + q.var + "').val()," + Environment.NewLine);
}
</code>```

But any symbol I try to pass (', \" or "") generates the html entity (&-#39; or &-quot;).

```<code>var: $("#var").val()
</code>```

and JS errors.

With a view only solution, is it possible to fix this?

答:
To have an official answer in this post (or for futur readers) I will put my comment as an answer, which seems to have resolved the issue.

What you should use is Html.Raw to print raw content.

```<code>@(q.var + Html.Raw(": $(\"#") + q.var + Html.Raw("\").val(),") + Environment.NewLine);
</code>```

Title: Quotes generating html entity

Body:
I'm trying to replace a bunch of consecutive

var: $("#var").val()

lines in my JS script with a simple loop in c# like this:

@foreach(var q in myList){
    @(q.var + ": $('#" + q.var + "').val()," + Environment.NewLine);
}

But any symbol I try to pass (', \" or "") generates the html entity (&-#39; or &-quot;).

var: $("#var").val()

and JS errors.

With a view only solution, is it possible to fix this?

Body:
To have an official answer in this post (or for futur readers) I will put my comment as an answer, which seems to have resolved the issue.

What you should use is Html.Raw to print raw content.

@(q.var + Html.Raw(": $(\"#") + q.var + Html.Raw("\").val(),") + Environment.NewLine);


问:
react-native-fb sdk com.android.support dependency error
```<code> > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified
</code>```

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

答:
I also have the same issue. I was able to successfully build by updating my

 ROOT : android/build.gradle file.

STEPS :

1. All you have to do is add a new maven line to the allprojects section for maven.google.com

2. Add resolutionStrategy Will Restrict your android fbsdk version to 4.28.0

```<code>allprojects {
    repositories {
        mavenLocal()
        jcenter()
        configurations.all {
        resolutionStrategy {
            force 'com.facebook.android:facebook-android-sdk:4.28.0'
        }
    }
        maven {
            url "https://maven.google.com"
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
      }
  }
</code>```

Body:
 > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

Body:
I also have the same issue. I was able to successfully build by updating my

 ROOT : android/build.gradle file.

STEPS :

1. All you have to do is add a new maven line to the allprojects section for maven.google.com

2. Add resolutionStrategy Will Restrict your android fbsdk version to 4.28.0

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        configurations.all {
        resolutionStrategy {
            force 'com.facebook.android:facebook-android-sdk:4.28.0'
        }
    }
        maven {
            url "https://maven.google.com"
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
      }
  }


问:
Send huge data from client to server
I am working with Go and Grpc. I have one XML file to be sent from client to server. When server calls a method on client, client responds back with an XML document which could range from few kB to 100s MB or may be more. Please help me with how should I do it? Should I

assign the value to a string variable and send normally -> rpc GetCMData (CmRequest) returns (CmReply) {}

assign the value to a string variable and send as a stream -> rpc GetCMData (CmRequest) returns (stream CmReply) {}

Is there any other better way to do so?

This is how CmReply looks like:

```<code>message CmReply {
  string name = 1;
}
</code>```

答:
You have two options:

Implement client-side streaming protocol in the way you have described above (split your file into chunks and send them one-by-one to the server):
https://github.com/grpc/grpc-go/issues/414#issuecomment-284515856

Extend the default 4 MB limits for a message size for your GRPC client and server (then you'll be able to send and receive big messages without streaming):
https://godoc.org/google.golang.org/grpc#MaxMsgSize
https://godoc.org/google.golang.org/grpc#WithMaxMsgSize

Title: Send huge data from client to server

Body:
I am working with Go and Grpc. I have one XML file to be sent from client to server. When server calls a method on client, client responds back with an XML document which could range from few kB to 100s MB or may be more. Please help me with how should I do it? Should I

assign the value to a string variable and send normally -> rpc GetCMData (CmRequest) returns (CmReply) {}

assign the value to a string variable and send as a stream -> rpc GetCMData (CmRequest) returns (stream CmReply) {}

Is there any other better way to do so?

This is how CmReply looks like:

message CmReply {
  string name = 1;
}


问:
Key-Value-Observing a to-many relationship in Cocoa
I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

```<code>@interface MyObservee : NSObject {
    @private int someValue;
    @private NSMutableArray *someArray;
}

@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end
</code>```

The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:

```<code>MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];

[moe addObserver:mobs
      forKeyPath:@"someArray"
         options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
         context:NULL];

[moe.someArray addObject:@"hi there"];
</code>```

How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.

答:
You need to implement the indexed array accessors as defined in the KVC programming guide.  Then you must use those accessors to access the array and the KVO triggering will work.  You can also call -mutableArrayValueForKey: and use that array to addObject: and such and it will in turn call the accessor methods and the KVO triggering will occur as well.  There are also set accessors for use in for NSSets, see here and here.

Example:

```<code>@interface MyClass : NSObject
{
    NSMutableArray *_orders;
}

@property(retain) NSMutableArray *orders;

- (NSUInteger)countOfOrders;
- (id)objectInOrdersAtIndex:(NSUInteger)index;
- (void)insertObject:(id)obj inOrdersAtIndex:(NSUInteger)index;
- (void)removeObjectFromOrdersAtIndex:(NSUInteger)index;
- (void)replaceObjectInOrdersAtIndex:(NSUInteger)index withObject:(id)obj;

@end
</code>```

OwnerDisplayName: Sam Lee

Body:
I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

@interface MyObservee : NSObject {
    @private int someValue;
    @private NSMutableArray *someArray;
}

@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end

The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:

MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];

[moe addObserver:mobs
      forKeyPath:@"someArray"
         options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
         context:NULL];

[moe.someArray addObject:@"hi there"];

How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.

Body:
You need to implement the indexed array accessors as defined in the KVC programming guide.  Then you must use those accessors to access the array and the KVO triggering will work.  You can also call -mutableArrayValueForKey: and use that array to addObject: and such and it will in turn call the accessor methods and the KVO triggering will occur as well.  There are also set accessors for use in for NSSets, see here and here.

Example:

@interface MyClass : NSObject
{
    NSMutableArray *_orders;
}

@property(retain) NSMutableArray *orders;

- (NSUInteger)countOfOrders;
- (id)objectInOrdersAtIndex:(NSUInteger)index;
- (void)insertObject:(id)obj inOrdersAtIndex:(NSUInteger)index;
- (void)removeObjectFromOrdersAtIndex:(NSUInteger)index;
- (void)replaceObjectInOrdersAtIndex:(NSUInteger)index withObject:(id)obj;

@end

OwnerDisplayName: s-bug


问:
Have no idea how to get an average from a text file
I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file:

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200

```<code>def main():

    numbersFile = open ('numbers.dat', 'r')

    for number in numbersFile:

        print number

main()
</code>```

The expected result is:

```<code>"The average is 105"
</code>```

Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!

答:
this works :

```<code>S = open("numbers.dat").read()
from statistics import mean
print(mean(map(int,S.split())))
</code>```

how it works:

open file, read content

split content into pieces using space as default separator

apply conversion to integer to each piece

compute mean using statistics module

Body:
I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file:

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200

def main():

    numbersFile = open ('numbers.dat', 'r')

    for number in numbersFile:

        print number

main()

The expected result is:

"The average is 105"

Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!

Body:
this works :

S = open("numbers.dat").read()
from statistics import mean
print(mean(map(int,S.split())))

how it works:

open file, read content

split content into pieces using space as default separator

apply conversion to integer to each piece

compute mean using statistics module


问:
A function for checking memory allocation for all dimensions of a multidimensional array in C
Here is the code:

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

#define numOfStrings 10
#define sizeOfString 30

void crashControl();
int main()
{
    char **strArray = (char **)malloc(numOfStrings*sizeof(char *));
    crashControl(strArray);

    for (int i = 0; i < numOfStrings; i++)
    {
        strArray[i] = (char *)malloc(sizeOfString*sizeof(char));
        crashControl(strArray[i]);
    }

    return 0;
}

void crashControl(char *A)
{
    if (!A)
    {
        printf("Not enough space.\n");
        exit(1);
    }
}
</code>```

It seems work correctly. When I increase numOfStrings too much crashControl(strArray) works correctly. Likewise when I increase sizeofString too much crashControl(strArray[i]) works correctly as well. But I wonder, am I doing right or wrong? Is there a risk or a bug for this code? The parameter of crashControl() function has one dimensional array, am I free to use this function for any N-dimensional array?

答:
Yes, you may use it for multidimensional arrays. However, it could be good to rewrite it in that case. Instead of taking a char * as argument you should take a void * to make it general.

What your function is testing is basically nothing more than if the pointer is a null pointer or not. Nothing more, nothing less. I'd say it is pretty bad designed since that function gives the impression that it does more. I cannot see any reason to do a null check in a separate function. It is better to just do the check immediately after malloc, like this:

```<code>char **strArray = (char **)malloc(numOfStrings*sizeof(char *));
if(!strArray) {
    printf("Error allocating memory\n");
    exit(1);
}
</code>```

If you really want to do this check in a function I would suggest naming it isNull and write it like this:

```<code>int isNull(void * ptr)
{
    if(ptr)
        return 0;
    else
        return 1;
}
</code>```

but since this function always would be called within an if statement it is pretty pointless.

Body:
Here is the code:

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

#define numOfStrings 10
#define sizeOfString 30

void crashControl();
int main()
{
    char **strArray = (char **)malloc(numOfStrings*sizeof(char *));
    crashControl(strArray);

    for (int i = 0; i < numOfStrings; i++)
    {
        strArray[i] = (char *)malloc(sizeOfString*sizeof(char));
        crashControl(strArray[i]);
    }

    return 0;
}

void crashControl(char *A)
{
    if (!A)
    {
        printf("Not enough space.\n");
        exit(1);
    }
}

It seems work correctly. When I increase numOfStrings too much crashControl(strArray) works correctly. Likewise when I increase sizeofString too much crashControl(strArray[i]) works correctly as well. But I wonder, am I doing right or wrong? Is there a risk or a bug for this code? The parameter of crashControl() function has one dimensional array, am I free to use this function for any N-dimensional array?

Body:
Yes, you may use it for multidimensional arrays. However, it could be good to rewrite it in that case. Instead of taking a char * as argument you should take a void * to make it general.

What your function is testing is basically nothing more than if the pointer is a null pointer or not. Nothing more, nothing less. I'd say it is pretty bad designed since that function gives the impression that it does more. I cannot see any reason to do a null check in a separate function. It is better to just do the check immediately after malloc, like this:

char **strArray = (char **)malloc(numOfStrings*sizeof(char *));
if(!strArray) {
    printf("Error allocating memory\n");
    exit(1);
}

If you really want to do this check in a function I would suggest naming it isNull and write it like this:

int isNull(void * ptr)
{
    if(ptr)
        return 0;
    else
        return 1;
}

but since this function always would be called within an if statement it is pretty pointless.


问:
Google Play Services aar download for above 11.0.4
From where to download the google-play-services aar files for version 11.6.0 OR above 11.0.4

I know just by adding the dependency in apps build.gradle adds the library in it.

```<code>compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.google.android.gms:play-services-ads:11.6.0'
</code>```

This is fair in case of Android Studio.

But as a Unity Developer, I have downloaded the Google Mobile Ads Unity Plugin which after import gives the play services ads, lite, basement, gass of version 11.6.0

Now we have some location dependency in our project. So I have downloaded the Android SDK and its stored in this path.

/Users/USERNAME/Library/Android/sdk

After navigating to /Users/USERNAME/Library/Android/sdk/extras/google/m2repository/com/google/android/gms,

I got the latest play services library of version 11.0.4 only and if I tried to create a Android Studio project by adding GPS dependency of 11.6.0, its getting added properly.

So my question is,

where google play services library of version 11.6.0 is downloaded. So that I can go to that location and get all the aar file needed for my Unity Project

答:
Check the links below:

play-services-ads-11.6.0

play-services-location-11.6.0

Body:
From where to download the google-play-services aar files for version 11.6.0 OR above 11.0.4

I know just by adding the dependency in apps build.gradle adds the library in it.

compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.google.android.gms:play-services-ads:11.6.0'

This is fair in case of Android Studio.

But as a Unity Developer, I have downloaded the Google Mobile Ads Unity Plugin which after import gives the play services ads, lite, basement, gass of version 11.6.0

Now we have some location dependency in our project. So I have downloaded the Android SDK and its stored in this path.

/Users/USERNAME/Library/Android/sdk

After navigating to /Users/USERNAME/Library/Android/sdk/extras/google/m2repository/com/google/android/gms,

I got the latest play services library of version 11.0.4 only and if I tried to create a Android Studio project by adding GPS dependency of 11.6.0, its getting added properly.

So my question is,

where google play services library of version 11.6.0 is downloaded. So that I can go to that location and get all the aar file needed for my Unity Project


问:
Google Progressive App (PWA) Can we use IONIC?
I want to build one Google Progressive App (PWA).

Can anyone suggest me that can I use IONIC 3/angular 4 for Google Progressive App?

Or I have to use Polymer?
Thanks

答:
Ionic comes with base ServiceWorker and Manifest support by default.

Uncomment the following line in index.html:

```<code>  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->
</code>```

You can subsequently change the caching strategy and implementation within src/service-worker.js.

Body:
Ionic comes with base ServiceWorker and Manifest support by default.

Uncomment the following line in index.html:

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

You can subsequently change the caching strategy and implementation within src/service-worker.js.


问:
Jquery click function with image src
I have an image which is as below

```<code> <img alt="" style="cursor: pointer" src="images/plus.png" width="20" height="20" />
</code>```

And I'm changing this img src alternatively by using the below code

```<code>1. $("[src*=plus]").click( function () {
                    $(this).attr("src", "images/minus.png");
                });
2.  $("[src*=minus]").click(function () {
                $(this).attr("src", "images/plus.png");
            });
</code>```

The first function is working as expected- when I click on the button for the first time the image is changing to 'minus',but when I click on this changed  'minus' image  the function call is going again to the same first function.
What am I doing wrong here.
Please help.

Referred  following link Changing the image source using jQuery

答:
you can try to use on() instead of click() or use another attribute like class for check the current status of the image which is much lighter and easy to execute with a single click event.

```<code>$("[src*=plus]").on("click",function () {
                    $(this).attr("src", "images/minus.png");
                });
$("[src*=minus]").on("click",function () {
                    $(this).attr("src", "images/plus.png");
                });
</code>```

or you can use the following as
HTML:

```<code><img alt="" style="cursor: pointer" src="images/plus.png" width="20" height="20" onclick="javascript:return img_click(this);"/>
</code>```

JavaScript :

```<code>function img_click(el)
{
 if($(el).attr("src").toLowerCase().indexOf('plus') != -1)
 {
   $(el).attr("src", "images/plus.png");
 }
 else
 {
   $(el).attr("src", "images/minus.png");
 }

}
</code>```

Title: Jquery click function with image src

Body:
I have an image which is as below

And I'm changing this img src alternatively by using the below code

1. $("[src*=plus]").click( function () {
                    $(this).attr("src", "images/minus.png");
                });
2.  $("[src*=minus]").click(function () {
                $(this).attr("src", "images/plus.png");
            });

The first function is working as expected- when I click on the button for the first time the image is changing to 'minus',but when I click on this changed  'minus' image  the function call is going again to the same first function.
What am I doing wrong here.
Please help.

Referred  following link Changing the image source using jQuery

Body:
you can try to use on() instead of click() or use another attribute like class for check the current status of the image which is much lighter and easy to execute with a single click event.

$("[src*=plus]").on("click",function () {
                    $(this).attr("src", "images/minus.png");
                });
$("[src*=minus]").on("click",function () {
                    $(this).attr("src", "images/plus.png");
                });

or you can use the following as
HTML:

<img alt="" style="cursor: pointer" src="images/plus.png" width="20" height="20" onclick="javascript:return img_click(this);"/>

JavaScript :

function img_click(el)
{
 if($(el).attr("src").toLowerCase().indexOf('plus') != -1)
 {
   $(el).attr("src", "images/plus.png");
 }
 else
 {
   $(el).attr("src", "images/minus.png");
 }

}


问:
Deploying simple nodejs app to Heroku - Procfile not working
I'm trying to deploy my Express server to my Heroku app, but every time I do, I get an error and it crashes.

I setup my Procfile with the following code: web: node /src/server.js

Where server.js is not in the root of the directory. However, when I try to start the server, I get an error in the logs: Error: Cannot find module '/src/server.js'

When I run the app locally, I have to run npm start in order for it to run the server correctly. Here is the relevant "scripts" portion of my package.json file:

```<code>"scripts": {
    "start": "NODE_ENV=dev nodemon ./src/server.js --exec babel-node",
    "prebuild": "rimraf dist",
    "build": "babel ./src -d dist --presets es2015,stage-2 --ignore spec.js,node_modules",
    "serve": "NODE_ENV=production node dist/server.js",
    "start_babel": "babel-node ./server.js --preset=babel-preset-es2015",
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint ."
  }
</code>```

Since the Procfile overrides the package.json script commands, why is it having trouble finding my file when I've explicitly set it?

答: I'm not sure about the leading slash. Does using <code>./src/server.js</code> help at all? </p>

Body:
I'm trying to deploy my Express server to my Heroku app, but every time I do, I get an error and it crashes.

I setup my Procfile with the following code: web: node /src/server.js

Where server.js is not in the root of the directory. However, when I try to start the server, I get an error in the logs: Error: Cannot find module '/src/server.js'

When I run the app locally, I have to run npm start in order for it to run the server correctly. Here is the relevant "scripts" portion of my package.json file:

"scripts": {
    "start": "NODE_ENV=dev nodemon ./src/server.js --exec babel-node",
    "prebuild": "rimraf dist",
    "build": "babel ./src -d dist --presets es2015,stage-2 --ignore spec.js,node_modules",
    "serve": "NODE_ENV=production node dist/server.js",
    "start_babel": "babel-node ./server.js --preset=babel-preset-es2015",
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint ."
  }

Since the Procfile overrides the package.json script commands, why is it having trouble finding my file when I've explicitly set it?

Body: I'm not sure about the leading slash. Does using ./src/server.js help at all?


问:
recursion binary search in a list of names
I am trying to build a function that gets the index of an item form a list

```<code>names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]
</code>```

this is the code

```<code>def find_name(lst,name,low,high):
if low >= high:
    return None
middle = (low + high) / 2
if lst[middle] == name:
    return middle
elif name < lst[middle]:
    return find_name(lst, name, low, middle)
else:
    return find_name(lst, name, middle + 1, high)
</code>```

it works fine and all but the only problem that im having is when I define the low and high values to be equals for the index I want to get
for example

```<code>print find_name(names,('Josh','Belluga'),0,1)
</code>```

returns none when it should return 1 for some reason

答:
```<code>def find_name(lst,name,low,high):
    if high is None:
         high = len(lst) - 1

    if low > high:

         return False

    middle = (low + high) / 2
    if lst[middle] == name:
         return middle
    elif name < lst[middle]:
        return find_name(lst, name, low, middle-1)
    else:
         return find_name(lst, name, middle + 1, high)

names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]

print find_name(names, ('Josh','Belluga'), 0, 1)
</code>```

<p>Here is what you are looking for. Just compare your original code with this and you will see what you did wrong. </p>

Body:
I am trying to build a function that gets the index of an item form a list

names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]

this is the code

def find_name(lst,name,low,high):
if low >= high:
    return None
middle = (low + high) / 2
if lst[middle] == name:
    return middle
elif name < lst[middle]:
    return find_name(lst, name, low, middle)
else:
    return find_name(lst, name, middle + 1, high)

it works fine and all but the only problem that im having is when I define the low and high values to be equals for the index I want to get
for example

print find_name(names,('Josh','Belluga'),0,1)

returns none when it should return 1 for some reason

Body:
def find_name(lst,name,low,high):
    if high is None:
         high = len(lst) - 1

    if low > high:

         return False

    middle = (low + high) / 2
    if lst[middle] == name:
         return middle
    elif name < lst[middle]:
        return find_name(lst, name, low, middle-1)
    else:
         return find_name(lst, name, middle + 1, high)

names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]

print find_name(names, ('Josh','Belluga'), 0, 1)

Here is what you are looking for. Just compare your original code with this and you will see what you did wrong.


问:
Access to database table structure in a .aspx page
I have a table Software in my database with the following columns:

```<code>id [key]
title
manufacturer
</code>```

I have a dropdown list in a webform .aspx file. I want the items in the drop down to be Id, title and manufacturer but I dont want to hard-code the items.

I am going to add more columns in the database table and I want the drop down list items to always remain in sync with the table structure.

How do I accomplish this?

答:
If you use LINQ:

```<code>var columnNames = dataTable1.Columns.OfType<DataColumn>().
                  Select(c => c.ColumnName).ToList();
comboBox1.DataSource = columnNames;
comboBox1.DataBind();
</code>```

Body:
I have a table Software in my database with the following columns:

id [key]
title
manufacturer

I have a dropdown list in a webform .aspx file. I want the items in the drop down to be Id, title and manufacturer but I dont want to hard-code the items.

I am going to add more columns in the database table and I want the drop down list items to always remain in sync with the table structure.

How do I accomplish this?

Body:
If you use LINQ:

var columnNames = dataTable1.Columns.OfType<DataColumn>().
                  Select(c => c.ColumnName).ToList();
comboBox1.DataSource = columnNames;
comboBox1.DataBind();


问:
Load JSON data into dropdown
I have one JSON returning dropdown values (Value and Text). I need to load that data into my dropdown. I have no idea how can i load those data's into dropdown. please tell me the possibilities.

Code

```<code>    $('#SupplierId').change(function () {
    var a = $(this).val();
    $.post('@Url.Action("MatchPoNo", "Subscriptions")', { Id: a }, function (data) {

        $("#PoNo").select2({

        });
    });
});
</code>```

答:
The simplest way would be to use JQuery view engine and just load the array into a dropdown:

```<code>var data = [
    {"text":"North","value":"N"},
    {"text":"West","value":"W"},
    {"text":"South","value":"S","selected":true},
    {"text":"East","value":"E"}
];
$("#dropdown").view(data);
</code>```

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

Title: Load JSON data into dropdown

Body:
I have one JSON returning dropdown values (Value and Text). I need to load that data into my dropdown. I have no idea how can i load those data's into dropdown. please tell me the possibilities.

Code

    $('#SupplierId').change(function () {
    var a = $(this).val();
    $.post('@Url.Action("MatchPoNo", "Subscriptions")', { Id: a }, function (data) {

        $("#PoNo").select2({

        });
    });
});

Body:
The simplest way would be to use JQuery view engine and just load the array into a dropdown:

var data = [
    {"text":"North","value":"N"},
    {"text":"West","value":"W"},
    {"text":"South","value":"S","selected":true},
    {"text":"East","value":"E"}
];
$("#dropdown").view(data);

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown


问:
AJAX update post_meta not updating the_modified_date
Wondering if someone knows a way to trigger an update to the_modified_date of a post when using AJAX to change post_meta?

I believe that this is caused because there is no add_action( 'save_post' passed in the AJAX and is only updating the DB directly.

Can this be done via JS or is it a question of adding to the PHP function?

答:
If you need to change your post modified date, then you need to update the post, not post meta.

I'm sending you simple example how to do that, and for sure that is on the php realm, either in functions.php file or inside your custom plugin file. X is the post number (integer)

```<code>$post = array(
    'post_modified'  => date(),
    'post_modified_gmt'   => date(),
    'ID'          => X, // $post->ID;
);
// update post
wp_update_post( $post );
</code>```

You can change your date via ajax for sure, but for that you need to use use native WP wp_ajax_(action) hook and a little javascript(jQuery).. take a look here for more info: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Your question is very vague and can lead to so many directions that we as community can't possibly know what you really want.. You should post questions that are mcve but if you can't then you should share as much code with us as you can!

OK, I'm gonna hope that maybe, this can be of help to someone who finds it via search engines in the future.

Body:
If you need to change your post modified date, then you need to update the post, not post meta.

I'm sending you simple example how to do that, and for sure that is on the php realm, either in functions.php file or inside your custom plugin file. X is the post number (integer)

$post = array(
    'post_modified'  => date(),
    'post_modified_gmt'   => date(),
    'ID'          => X, // $post->ID;
);
// update post
wp_update_post( $post );

You can change your date via ajax for sure, but for that you need to use use native WP wp_ajax_(action) hook and a little javascript(jQuery).. take a look here for more info: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Your question is very vague and can lead to so many directions that we as community can't possibly know what you really want.. You should post questions that are mcve but if you can't then you should share as much code with us as you can!

OK, I'm gonna hope that maybe, this can be of help to someone who finds it via search engines in the future.


问:
Testing against hacking attempts
I want to make sure my site is protected against hacking attempts and I think the best way to test is to try and hack my site myself. What sort of things do hackers do to try and hack my site?

E.g.,

Test -
they might put javascript in a input field e.g.,

<“open javascript tag">window.location = “www.somewhereelse.com”;<“end javascript tag”>

Protection -
Use php htmlentities function before displaying data.

What other things can I test against to make sure my site is safe?

答:
I think the best way for you to go is to run a vulnerability scan against your website. There are numerous ways hackers can get into your website much of will be Social-Engineering, exploiting unpatched Software. so make sure to update your website as soon as possible each time there is a patch released.

I will recommend you ask a hacker who does not know your personally to try to hack your website.

Title: Testing against hacking attempts


答:
You didn't wrong, just need to use on function, because you changing src after DOM in result it can't find new src, so you need to use live click function:

```<code>$(document).on('click','[src*=plus]',function(){
  $(this).attr("src", "images/minus.png");
});
$(document).on('click','[src*=minus]',function(){
  $(this).attr("src", "images/plus.png");
});
</code>```

$(document).on('click','[src*=plus]',function(){
  $(this).prop("src","images/minus.png");
  console.log('changed to minus');
});

$(document).on('click','[src*=minus]',function(){
  $(this).prop("src","images/plus.png");
  console.log('changed to plus');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="some text" style="cursor: pointer" src="images/plus.png" width="20" height="20" /></code>```

Title: Jquery click function with image src

Body:
You didn't wrong, just need to use on function, because you changing src after DOM in result it can't find new src, so you need to use live click function:

$(document).on('click','[src*=plus]',function(){
  $(this).attr("src", "images/minus.png");
});
$(document).on('click','[src*=minus]',function(){
  $(this).attr("src", "images/plus.png");
});

$(document).on('click','[src*=plus]',function(){
  $(this).prop("src","images/minus.png");
  console.log('changed to minus');
});

$(document).on('click','[src*=minus]',function(){
  $(this).prop("src","images/plus.png");
  console.log('changed to plus');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="some text" style="cursor: pointer" src="images/plus.png" width="20" height="20" />


问:
Applying different themes in angular 4 component
I have a component library that I've designed for lets say theme A.
I want to have most of the components with a slight different variation (in both template and css) in them to make my theme B.

I've taken a look at most of these questions on SO and also on the web but nothing addresses my issue precisely unless I create a new tag with a different name which I don't believe to be an elegant way to address this issue.

I would appreciate if someone can provide me an approach to tackle this.

How to apply themes in angular2?

Can I add two template for one component in angular2?

Angular 2 component with multiple views

答:
if there are few differences and few themes you can
Your css like

```<code>.theme1 .head{..}
.theme1 .title{..}
.theme2 .head{..}
...
.theme3 .head{..}
...
</code>```

your html

```<code><div [ngClass]="themeActual">
<head>..</head>
<div class="title>...</div>
</code>```

your .ts only need use

```<code>themeActual="theme1";
</code>```

If there are so many difference you can change index.html importing the theme.css someway

About component with different views, if the problem it's about mobile layout you can use media querys css or *ngIf, ...

Body:
if there are few differences and few themes you can
Your css like

.theme1 .head{..}
.theme1 .title{..}
.theme2 .head{..}
...
.theme3 .head{..}
...

your html

<div [ngClass]="themeActual">
<head>..</head>
<div class="title>...</div>

your .ts only need use

themeActual="theme1";

If there are so many difference you can change index.html importing the theme.css someway

About component with different views, if the problem it's about mobile layout you can use media querys css or *ngIf, ...