答:
You can simply String.join the strings together and print them. Like:

```<code>public class Foo {

    public static void main(String [] args) {
        System.out.println(<b>String.join(" ",args)</b>);
    }

}</code>```

The first argument, the delimiter, is here " " (a string containing one space). Such that there is a space between two arguments.

Note that this program is almost identical to the echo program you see on a lot of operating systems.

Finally note that although this program does not contain a loop, the String.join definitely need some form of looping inside the method.

Body:
You can simply String.join the strings together and print them. Like:

public class Foo {

    public static void main(String [] args) {
        System.out.println(String.join(" ",args));
    }

}

The first argument, the delimiter, is here " " (a string containing one space). Such that there is a space between two arguments.

Note that this program is almost identical to the echo program you see on a lot of operating systems.

Finally note that although this program does not contain a loop, the String.join definitely need some form of looping inside the method.


来源: stackexchange

问:
Javascript bitwise operators - explanation required
I'm using some code in JS and I bumped into these (unrelated) expressions:

```<code>1) var r = (d + Math.random() * 16) % 16 | 0;

2) return c === 'x' ? r : (r & 0x3 | 0x8);
</code>```

I read some about bitwise operators but it does not help in this context.
Can somebody explain (preferably step-by-step) how do they work ? How this two expressions are logically evaluated and run ?

Thanks in advance.

答:
Basically you could do a brute-force approach and look which values are returned in an object, one for c === '' and c === 'x'.

function x() {
    var r = (d + Math.random() * 16) % 16 | 0;  // the last or returns an integer value
    return c === 'x' ? r : (r & 0x3 | 0x8);
}

var d = 0,  // does not matter, because of % operator
    c = '',
    i,
    values = {},
    v;

for (i = 0; i < 1e6; i++) {
    v = x();
    values[v] = values[v] || 0;
    values[v]++;
}
console.log(values);

values = {};
c = 'x';
for (i = 0; i < 1e6; i++) {
    v = x();
    values[v] = values[v] || 0;
    values[v]++;
}
console.log(values);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using some code in JS and I bumped into these (unrelated) expressions:

1) var r = (d + Math.random() * 16) % 16 | 0;

2) return c === 'x' ? r : (r & 0x3 | 0x8);

I read some about bitwise operators but it does not help in this context.
Can somebody explain (preferably step-by-step) how do they work ? How this two expressions are logically evaluated and run ?

Thanks in advance.

Body:
Basically you could do a brute-force approach and look which values are returned in an object, one for c === '' and c === 'x'.

function x() {
    var r = (d + Math.random() * 16) % 16 | 0;  // the last or returns an integer value
    return c === 'x' ? r : (r & 0x3 | 0x8);
}

var d = 0,  // does not matter, because of % operator
    c = '',
    i,
    values = {},
    v;

for (i = 0; i < 1e6; i++) {
    v = x();
    values[v] = values[v] || 0;
    values[v]++;
}
console.log(values);

values = {};
c = 'x';
for (i = 0; i < 1e6; i++) {
    v = x();
    values[v] = values[v] || 0;
    values[v]++;
}
console.log(values);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Plotting Pandas dataframe matplotlib
I'm using Pandas to read in a .csv file containing dates and a product type and I'm trying to graph the amount of each product over time. Heres my current code:

```<code>    df = df.dropna()
    df= df[df['product'].str.contains("X|Y|Z")]
    df=df.groupby('date')['product'].value_counts()
</code>```

which returns me this dataframe:

```<code>date        product
2013.0      X         2229
            Y         194
            Z         590
2014.0      X         229
            Y         1924
            Z         5902
</code>```

Whats the best way to plot this using matplotlib?

答:
Case 1

```<code>df.unstack().plot.bar()
</code>```

Case 2

```<code>df.unstack(0).plot.bar()
</code>```

Title: Plotting Pandas dataframe matplotlib

Body:
I'm using Pandas to read in a .csv file containing dates and a product type and I'm trying to graph the amount of each product over time. Heres my current code:

    df = df.dropna()
    df= df[df['product'].str.contains("X|Y|Z")]
    df=df.groupby('date')['product'].value_counts()

which returns me this dataframe:

date        product
2013.0      X         2229
            Y         194
            Z         590
2014.0      X         229
            Y         1924
            Z         5902

Whats the best way to plot this using matplotlib?

Body:
Case 1

df.unstack().plot.bar()

Case 2

df.unstack(0).plot.bar()


问:
Bootstrap 4: Fixed Top Navbar with container properties
So by default when you create a Bootstrap 4 Navbar, it will have the properties of a container-fluid instead of container, so how does one get it to have the properties of container

```<code><nav class="navbar fixed-top navbar-light bg-faded">
  <a class="navbar-brand" href="#">Fixed top</a>
</nav>
</code>```

I've seen several similar Questions but I hope my solution helps you out:

答:
The simplest Answer to this question is to add container in you nav class. Below is an example:

```<code><nav class="navbar container fixed-top navbar-light bg-faded">
  <a class="navbar-brand" href="#">Fixed top</a>
</nav>
</code>```

Body:
So by default when you create a Bootstrap 4 Navbar, it will have the properties of a container-fluid instead of container, so how does one get it to have the properties of container

  Fixed top

I've seen several similar Questions but I hope my solution helps you out:

Body:
The simplest Answer to this question is to add container in you nav class. Below is an example:

<nav class="navbar container fixed-top navbar-light bg-faded">
  <a class="navbar-brand" href="#">Fixed top</a>
</nav>


问:
Setting the circle (oval) radius to 10 with others being bigger than the first?
I want to create 12 concentric circles where the first is radius 10 pixels and the rest have different colors. I am stuck on how to change the radius, and I assume making them different colors is easy. I currently output 12 really small circles. I am not sure what is wrong. </p>

```<code>import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Circles extends JComponent {
    public void paintComponent(Graphics g){

    int width = getWidth();
    int height = getHeight();

    int xPoint = width / 2;
    int yPoint = height / 2;

    for(int i = 5; i <= 12; i++){
        g.drawOval(xPoint - (i * 5), yPoint - (i * 5), (i * 10), (i * 10));
    }
}

    @Override
    public Dimension getPreferredSize(){
        return new Dimension(400, 400);
    }
    public static void main(String[] args){
        JFrame frame = new JFrame("Line Loop");

        frame.add(new Circles());

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.pack();

        frame.setVisible(true);

    }

}
</code>```

答:
I was being stupid. Here's how I fixed it.</p>

```<code> for(int i = 0; i <= 12; i++){
        g.drawOval(xPoint - (i * 50), yPoint - (i * 50), (i * 100), (i * 100));
    }
}
</code>```

Body:
I want to create 12 concentric circles where the first is radius 10 pixels and the rest have different colors. I am stuck on how to change the radius, and I assume making them different colors is easy. I currently output 12 really small circles. I am not sure what is wrong.

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Circles extends JComponent {
    public void paintComponent(Graphics g){

    int width = getWidth();
    int height = getHeight();

    int xPoint = width / 2;
    int yPoint = height / 2;

    for(int i = 5; i <= 12; i++){
        g.drawOval(xPoint - (i * 5), yPoint - (i * 5), (i * 10), (i * 10));
    }
}

    @Override
    public Dimension getPreferredSize(){
        return new Dimension(400, 400);
    }
    public static void main(String[] args){
        JFrame frame = new JFrame("Line Loop");

        frame.add(new Circles());

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.pack();

        frame.setVisible(true);

    }

}

Body:
I was being stupid. Here's how I fixed it.

 for(int i = 0; i <= 12; i++){
        g.drawOval(xPoint - (i * 50), yPoint - (i * 50), (i * 100), (i * 100));
    }
}


问:
Get (associative) array of Mongoose models
You can retrieve a Mongoose model like so:

let User = mongoose.model('User');

I am looking to do get an associative array of these models.
Is there some clever way of getting a list of models using object destructuring? Something like:

```<code>const {User, Employees, Managers} = mongoose.model('x');
</code>```

My current solution is to do this:

```<code>/project
  /models
    index.js
</code>```

where index.js looks like:

```<code>module.exports = {
  User: require('./user'),
  Employee: require('./employee'),
  Manager: require('./manager'),
};
</code>```

Where the user.js, employee.js and manager.js files just look like:

```<code>let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let userSchema = new Schema({...});

module.exports = mongoose.model('User', userSchema, 'users');
</code>```

Then I can do this:

```<code> const {User, Employees, Managers} = require('./models');
</code>```

But I am looking for a better solution that requires no manual work if possible.

答:
```<code>const models = {};
mongoose.modelNames().forEach(function(modelName){
    models[modelName] = mongoose.model(modelName);
});
console.log(models);
</code>```

Body:
You can retrieve a Mongoose model like so:

let User = mongoose.model('User');

I am looking to do get an associative array of these models.
Is there some clever way of getting a list of models using object destructuring? Something like:

const {User, Employees, Managers} = mongoose.model('x');

My current solution is to do this:

/project
  /models
    index.js

where index.js looks like:

module.exports = {
  User: require('./user'),
  Employee: require('./employee'),
  Manager: require('./manager'),
};

Where the user.js, employee.js and manager.js files just look like:

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let userSchema = new Schema({...});

module.exports = mongoose.model('User', userSchema, 'users');

Then I can do this:

 const {User, Employees, Managers} = require('./models');

But I am looking for a better solution that requires no manual work if possible.


问:
Drag and drop and mouse events
My question is why mouse events aren't raised on window when I drag some text using drag and drop from another window?

I have a window where I listen to MouseEnter event which is not raised when I try to drag and drop something into it.

How to figure this one out?

答:
This is a known issue:

Drag and Drop in WPF not working for DataFormats.FileDrop

C# Drag drop does not work on windows 7

Title: Drag and drop and mouse events

ContentLicense: CC BY-SA 2.5


问:
eval black magic loses scope
disclaimer I do not endorse the use of eval, and I do not use it when I write code.

I am forking logic on a legacy project and came across some very odd behavior with eval and would like to know an under the hood explanation of why this behavior exists.

```<code>var baz = function(cb) {
    cb('asdf');
}

function foo(qux, callback) {
    setTimeout(function() {
        // eval(callback('asdf')); // works
        // eval(baz(callback)); // works
        // eval(qux + "(" + callback + ")"); // resolve is undefined
    });
}

function bar() {
    return new Promise((resolve, reject) => {
        try {
            foo('baz', function(response){
                resolve(response);
            });
        } catch (e) {
            reject(e);
        }
    });
}

function init() {
    bar()
    .then(response => {
        console.log(response)
    })
    .catch(e => console.log(e));

}

init();
</code>```

I wrote three examples of different ways to use eval, commented off in the function foo
The third example does not work. This is the example I am concerned with as it is how our legacy code works. I know there are other way around this issue. My solution was to just rewrite the function and not use eval at all.

My question is very precisely, why does eval lose scope when you pass in the function name as a string, but it does not lose scope when you pass in an actual reference to the same function?

Here is a jsfiddle:
https://jsfiddle.net/tkcjay4x/6/

答:
I have to admit, the title scares me a little. If I understand this "black magic", does it make me an evil sorcerer?

When you do eval(baz(callback)), baz calls callback, and eval executes the return value of baz, which is undefined. eval(undefined) is equal to eval('undefined') which is equal to undefined. So in this case using eval is essentially no-op – just doing baz(callback) would give the same result.

When you do eval(qux + "(" + callback + ")"), qux + "(" + callback + ")" evaluates to 'baz(function(response){ resolve(response); })'. When you pass that to eval, the code tries to access a function named resolve, which is not present in the current scope. That's why it doesn't work. If you call function directly, it can access variables which were present in the scope in which it was defined, but if you convert a function to a string and pass it to eval, it can only access variables from the current scope.

Title: eval black magic loses scope

Body:
disclaimer I do not endorse the use of eval, and I do not use it when I write code.

I am forking logic on a legacy project and came across some very odd behavior with eval and would like to know an under the hood explanation of why this behavior exists.

var baz = function(cb) {
    cb('asdf');
}

function foo(qux, callback) {
    setTimeout(function() {
        // eval(callback('asdf')); // works
        // eval(baz(callback)); // works
        // eval(qux + "(" + callback + ")"); // resolve is undefined
    });
}

function bar() {
    return new Promise((resolve, reject) => {
        try {
            foo('baz', function(response){
                resolve(response);
            });
        } catch (e) {
            reject(e);
        }
    });
}

function init() {
    bar()
    .then(response => {
        console.log(response)
    })
    .catch(e => console.log(e));

}

init();

I wrote three examples of different ways to use eval, commented off in the function foo
The third example does not work. This is the example I am concerned with as it is how our legacy code works. I know there are other way around this issue. My solution was to just rewrite the function and not use eval at all.

My question is very precisely, why does eval lose scope when you pass in the function name as a string, but it does not lose scope when you pass in an actual reference to the same function?

Here is a jsfiddle:
https://jsfiddle.net/tkcjay4x/6/


问:
N-Gram Analysis in Python
Here is what my sample data looks like:

I need to conduct 1-2 gram on query, and calculate the sum and average of impression associated with the queries. Now I've figured out how to aggregate the impressions using the codes below.

```<code>def n_grams(txt):
grams = list()
words = txt.split(' ')
for i in range(len(words)):
    for k in range(1, len(words) - i + 1):
        grams.append(" ".join(words[i:i+k]))
return pd.Series(grams)

counts = df['query'].apply(n_grams).join(df)
result = counts.drop("query", axis=1).set_index("impression").unstack()    .rename("ngram").dropna().reset_index()    .drop("level_0",
axis=1).groupby("ngram")["impression"].sum()
result = result.to_frame()
result['query'] = result.index
result['ngram'] =result['query'].str.split().apply(len)
result = result.groupby(['ngram','query'])['impression'].sum()
result = result.reset_index()
result = result.sort_values(['ngram', 'impression'], ascending=[True, False])
</code>```

The results return like:

Here I need an another column to show the average impression associated with those queries. For example, the word "nutrition" appear four times, so the avg impression should be 100/4 = 25. Also, I want to show how many times this query appear in another column. The ultimate result should look like this:

答:
This code will help you get the count of unigrams such as 'nutrition' from bigrams. </p>

```<code>2gram=result[result['ngram']==2]
2gram=2gram.reset_index()
#create an empty dictionary to store count of words in bigrams
words=dict()
for i in range(0,len(2gram):
    query_wrds=2gram.loc[i,'query'].split()
        for item in query_words:
            if item not in words:
                words[item]=1
            else:
                words[item]+=1
#to get count of word 'nutrition'
nut_ct=words['nutrition']
</code>```

Title: N-Gram Analysis in Python

Body:
Here is what my sample data looks like:

I need to conduct 1-2 gram on query, and calculate the sum and average of impression associated with the queries. Now I've figured out how to aggregate the impressions using the codes below.

def n_grams(txt):
grams = list()
words = txt.split(' ')
for i in range(len(words)):
    for k in range(1, len(words) - i + 1):
        grams.append(" ".join(words[i:i+k]))
return pd.Series(grams)

counts = df['query'].apply(n_grams).join(df)
result = counts.drop("query", axis=1).set_index("impression").unstack()    .rename("ngram").dropna().reset_index()    .drop("level_0",
axis=1).groupby("ngram")["impression"].sum()
result = result.to_frame()
result['query'] = result.index
result['ngram'] =result['query'].str.split().apply(len)
result = result.groupby(['ngram','query'])['impression'].sum()
result = result.reset_index()
result = result.sort_values(['ngram', 'impression'], ascending=[True, False])

The results return like:

Here I need an another column to show the average impression associated with those queries. For example, the word "nutrition" appear four times, so the avg impression should be 100/4 = 25. Also, I want to show how many times this query appear in another column. The ultimate result should look like this:

Body:
This code will help you get the count of unigrams such as 'nutrition' from bigrams.

2gram=result[result['ngram']==2]
2gram=2gram.reset_index()
#create an empty dictionary to store count of words in bigrams
words=dict()
for i in range(0,len(2gram):
    query_wrds=2gram.loc[i,'query'].split()
        for item in query_words:
            if item not in words:
                words[item]=1
            else:
                words[item]+=1
#to get count of word 'nutrition'
nut_ct=words['nutrition']


问:
How to select a partial of a table for exporting using SQL?
I have a dataset which has about 25 millions rows. I want to export it to ACCESS. However, I cannot export it as a whole. So I exported the top 10 millions rows. I have used the codes which is shown below.

```<code>SELECT TOP (10000000) [TRD_EVENT_DT]
  ,[TRD_EVENT_TM]
  ,[TRD_STCK_CD]
  ,[TRD_PR]
  ,[TRD_TUROVR]
FROM [trade92].[dbo].[trade]
</code>```

Now, I want to select second 10 millions rows and Then final 5 millions rows for export them to ACCESS.

How can I do that?

答:
You can use a CTE:

```<code>;WITH YourQuery AS (

    SELECT ROW_NUMBER() OVER (ORDER BY TRD_EVENT_TM DESC) as RowNumber, *
    FROM trade

    )
SELECT * FROM YourQuery
WHERE RowNumber BETWEEN 10000001 AND 20000000
</code>```

Assuming you are using SQL Server, and not one of the other currently tagged RDBMS. To get the final set of rows, change the WHERE clause to:

```<code>WHERE RowNumber > 20000000
</code>```

Body:
I have a dataset which has about 25 millions rows. I want to export it to ACCESS. However, I cannot export it as a whole. So I exported the top 10 millions rows. I have used the codes which is shown below.

SELECT TOP (10000000) [TRD_EVENT_DT]
  ,[TRD_EVENT_TM]
  ,[TRD_STCK_CD]
  ,[TRD_PR]
  ,[TRD_TUROVR]
FROM [trade92].[dbo].[trade]

Now, I want to select second 10 millions rows and Then final 5 millions rows for export them to ACCESS.

How can I do that?

Body:
You can use a CTE:

;WITH YourQuery AS (

    SELECT ROW_NUMBER() OVER (ORDER BY TRD_EVENT_TM DESC) as RowNumber, *
    FROM trade

    )
SELECT * FROM YourQuery
WHERE RowNumber BETWEEN 10000001 AND 20000000

Assuming you are using SQL Server, and not one of the other currently tagged RDBMS. To get the final set of rows, change the WHERE clause to:

WHERE RowNumber > 20000000


问:
Print stylish text on image in php
Is it possible to print html div tag with style on image in PHP?. if not, then what is the alternative way?</p>

答:
Some hosts have ImageMagick for PHP. To add text to your image, take a look at the syntax of the commands here. The example given on that page should help some - it's pretty easy to get text on an image.

The benefits of using ImageMagick over a fixed image is that you can vary the content of the text, which is what you might want (you didn't mention needing a static text; for this, I'd use an image with a transparent background). For more comprehensive font commands, take a look here.

To put a transparent image on top of your base image, take a look at this very nicely designed site.

I'll also give the code presented on that site here:

```
$photo = imagecreatefromjpeg("original.jpg");
$watermark = imagecreatefrompng("watermark.png");

// This is the key. Without ImageAlphaBlending on, the PNG won't render correctly.
imagealphablending($photo, true);

// Copy the watermark onto the master, $offset px from the bottom right corner.
$offset = 10;

imagecopy($photo, $watermark, imagesx($photo) - imagesx($watermark) - $offset, imagesy($photo) - imagesy($watermark) - $offset, 0, 0, imagesx($watermark), imagesy($watermark));

// Output to the browser
header("Content-Type: image/jpeg");
imagejpeg($photo);
```

To output the image to a file, please Google that and replace the last two lines of the example given above.

For ImageMagick stuff, take a look here

I hope this helps :-)

James

Title: Print stylish text on image in php

Body:
Some hosts have ImageMagick for PHP. To add text to your image, take a look at the syntax of the commands here. The example given on that page should help some - it's pretty easy to get text on an image.

The benefits of using ImageMagick over a fixed image is that you can vary the content of the text, which is what you might want (you didn't mention needing a static text; for this, I'd use an image with a transparent background). For more comprehensive font commands, take a look here.

To put a transparent image on top of your base image, take a look at this very nicely designed site.

I'll also give the code presented on that site here:

$photo = imagecreatefromjpeg("original.jpg");
$watermark = imagecreatefrompng("watermark.png");

// This is the key. Without ImageAlphaBlending on, the PNG won't render correctly.
imagealphablending($photo, true);

// Copy the watermark onto the master, $offset px from the bottom right corner.
$offset = 10;

imagecopy($photo, $watermark, imagesx($photo) - imagesx($watermark) - $offset, imagesy($photo) - imagesy($watermark) - $offset, 0, 0, imagesx($watermark), imagesy($watermark));

// Output to the browser
header("Content-Type: image/jpeg");
imagejpeg($photo);

To output the image to a file, please Google that and replace the last two lines of the example given above.

For ImageMagick stuff, take a look here

I hope this helps :-)

James


问:
How to check if a specific page is already open in Google Chrome?
Basically, I've got a packaged web application which I'd like to be able to check as it loads if there are any other instances of the web application open, and, if so, to switch to the open instance rather than create another one.

Also, for the options page, I'd like it to be able to check if the application is open, and, if so, refresh the application page if the options page has been changed.

I've been reading the documentation about the chrome.tabs JavaScript module, but I can't work out how to make the function look for a specific tab. I don't quite understand how to look for or set the tab ID for a specific tab. I think this is how to do what I want, but if I'm barking up the wrong tree please let me know.

If anyone here can explain it better for me I'd be most thankful.

答: Just in case anybody planning to use above examples, "selected" option has been deprecated since Chrome 33, use "highlighted" option instead.</p>


问:
Push notifications in PHP. How to use it?
i would like to send push notification in PHP, but i don't know how to do.

I successfully create the Service Worker.

I took a key from this page https://web-push-codelab.appspot.com/. But i don't understand why do they give a private key ?

Then i test my push notifiaction, and i send some notification from this page.
But I would like to send push notification from my PHP request.
More, i would this work on all the bowsers possible, this code works just with google chrome. Can we do this with firefox, safari, opéra ?

I already use the librairie web-push-php. (avaible here: https://github.com/web-push-libs/web-push-php)
I copy/pase the code from the documentation, and i remplace my key, and messages:`

```<code><?php
    error_reporting(E_ALL);
    ini_set('display_errors',1);
    use Minishlink\WebPush\WebPush;

    $notifications = array(
        array(
            'endpoint' => 'https://updates.push.services.mozilla.com/push/abc...', // Firefox 43+
            'payload' => 'hello !',
            'userPublicKey' => '*****', // base 64 encoded, should be 88 chars
            'userAuthToken' => '*****', // base 64 encoded, should be 24 chars
        ), array(
            'endpoint' => 'https://android.googleapis.com/gcm/send/abcdef...', // Chrome
            'payload' => '{msg:"je fais un test"}',
            'userPublicKey' => '*****',
            'userAuthToken' => null,
        )
    );

    $webPush = new WebPush();

    // send multiple notifications with payload
    foreach ($notifications as $notification) {
        $webPush->sendNotification(
            $notification['endpoint'],
            $notification['payload'], // optional (defaults null)
            $notification['userPublicKey'], // optional (defaults null)
            $notification['userAuthToken'] // optional (defaults null)
        );
    }
    $webPush->flush();
</code>```

But this code don't work, the page return this :{"multicast_id":6971447349404987967,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}`

I also create a firebase account, but i don't know how to usi it.

And i would like also target the notifications.
I would like to send the notification like "xxx commented to your post" or "xxx liked to your post" or "xxx send to you a friend request"

Hope, you can help me.

答:
I took a key from this page https://web-push-codelab.appspot.com/. But
  i don't understand why do they give a private key ?

The server is supposed to generate a public/private keypair. The public key is used by the browser to create a subscription. The private key remains on the server and is used to encrypt the push message.

And i would like also target the notifications. I would like to send
  the notification like "xxx commented to your post" or "xxx liked to
  your post" or "xxx send to you a friend request"

At some point you have the browser register a subscription by calling pushManager.subscribe (but this code is missing from your question). This returns a promise that resolves to a subscription. You should associate this subscription to the currently authenticated user. For example, you can use AJAX to send the subscription to your server and store it with the currently authenticated user. Whenever you want to notify this user you can use the subscription that is associated with this user.

You might want to take a look at https://web-push-book.gauntface.com/.

Body:
i would like to send push notification in PHP, but i don't know how to do.

I successfully create the Service Worker.

I took a key from this page https://web-push-codelab.appspot.com/. But i don't understand why do they give a private key ?

Then i test my push notifiaction, and i send some notification from this page.
But I would like to send push notification from my PHP request.
More, i would this work on all the bowsers possible, this code works just with google chrome. Can we do this with firefox, safari, opéra ?

I already use the librairie web-push-php. (avaible here: https://github.com/web-push-libs/web-push-php)
I copy/pase the code from the documentation, and i remplace my key, and messages:`

<?php
    error_reporting(E_ALL);
    ini_set('display_errors',1);
    use Minishlink\WebPush\WebPush;

    $notifications = array(
        array(
            'endpoint' => 'https://updates.push.services.mozilla.com/push/abc...', // Firefox 43+
            'payload' => 'hello !',
            'userPublicKey' => '*****', // base 64 encoded, should be 88 chars
            'userAuthToken' => '*****', // base 64 encoded, should be 24 chars
        ), array(
            'endpoint' => 'https://android.googleapis.com/gcm/send/abcdef...', // Chrome
            'payload' => '{msg:"je fais un test"}',
            'userPublicKey' => '*****',
            'userAuthToken' => null,
        )
    );

    $webPush = new WebPush();

    // send multiple notifications with payload
    foreach ($notifications as $notification) {
        $webPush->sendNotification(
            $notification['endpoint'],
            $notification['payload'], // optional (defaults null)
            $notification['userPublicKey'], // optional (defaults null)
            $notification['userAuthToken'] // optional (defaults null)
        );
    }
    $webPush->flush();

But this code don't work, the page return this :{"multicast_id":6971447349404987967,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}`

I also create a firebase account, but i don't know how to usi it.

And i would like also target the notifications.
I would like to send the notification like "xxx commented to your post" or "xxx liked to your post" or "xxx send to you a friend request"

Hope, you can help me.


问:
Get the current page node with a JSP
I'm doing a language picker, that permit to change between english and french, the application is on Jahia.

I would like to get the [j:fullpath] from the page  I'm on from the jsp of my component languagePicker, but I don't find a way to get it. I need the j:fullpath of the current page, current page is actually ..../home/html, but $(currentNode.path) answers me :

/modules/template/02.02.01.10-SNAPSHOT/templates/base/navbar2/navbarlinks-lang

But I would like something like : " /sites/services/home", it is my actual j:fullpath for my homepage. Under this node, there's a "VanityUrlMapping" and under again 2 nodes, one for each language.

There's  a vanityUrlmapping under each pages, so how to get the j:fullpath of these pages in a JSP ?

Thanks

答:
I think that ${renderContext.mainResouce.node.path} is what you are looking for.

I don't think that j:fullpath would take into account the vanity URLs.  I don't do much with those, though.

Title: Get the current page node with a JSP


问:
AWS CodeBuild with GitHub - only for specific directory
I am trying to set up automatic deployment for the Angular 2 app with AWS Pipeline, S3 and CodeBuild.

Following Andrés' tutorial I was able to connect CodeBuild the GitHub repo and the process works great.

However, our Angular app lives inside a subdirectory of the bigger repo.

Is there a way to specify a directory inside a repo, so that the build will only be triggered if the subdirectory changed?

Thanks a lot.

答:
It doesn't look like you can just pull down a certain folder but the artifact for the build spec you can specify the directories that are used for the build.

For GitHub, for the optional Source version value, type a commit ID, a pull request ID, a branch name, or a tag name that corresponds to the version of the source code you want to build. If a pull request ID is specified, it must use the format pr/pull-request-ID (for example, pr/25). If a branch name is specified, the branch's HEAD commit ID will be used. If Source version is blank, the default branch's HEAD commit ID will be used.

http://docs.aws.amazon.com/codebuild/latest/userguide/run-build.html

artifacts Optional sequence. Represents information about where AWS CodeBuild can find the build output and how AWS CodeBuild will prepare it for uploading to the Amazon S3 output bucket. This sequence is not required if, for example, you are building and pushing a Docker image to Amazon ECR, or you are running unit tests on your source code but not building it.
  files: Required sequence. Represents the locations containing the build output artifacts in the build environment. Contains a sequence of scalars, with each scalar representing a separate location where AWS CodeBuild can find build output artifacts, relative to the original build location. Locations can include the following:
  A single file (for example, my-file.jar).
  A single file in a subdirectory (for example, my-subdirectory/my-file.jar or my-parent-subdirectory/my-subdirectory/my-file.jar).
  '/' represents all files recursively.
  my-subdirectory/ represents all files in a subdirectory named my-subdirectory.
  my-subdirectory//* represents all files recursively starting from a subdirectory named my-subdirectory.

http://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html


问:
Python tkinter trace error
I'm trying to write a GUI for my code. My plan is to use tkinter's StringVar, DoubleVar, etc. to monitor my input in real time. So I found out the DoubleVar.trace('w', callback) function. However, every time I make the change I get an exception:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
TypeError: 'NoneType' object is not callable
</code>```

I have no idea what's going wrong. I'm using python 2.7
My code is as follows:

```<code>from Tkinter import *
class test(Frame):
    def __init__(self,master):
        Frame.__init__(self,master=None)
        self.main_frame = Frame(master);
        self.main_frame.pack()
        self.testvar = DoubleVar()
        self.slider_testvar = Scale(self.main_frame,variable = self.testvar,from_ = 0.2, to = 900, resolution = 0.1, orient=HORIZONTAL,length = 300)
        self.slider_testvar.grid(row = 0, column = 0, columnspan = 5)
        self.testvar.trace('w',self.testfun())
    def testfun(self):
        print(self.testvar.get())

root = Tk()
root.geometry("1024x768")
app = test(master = root)
root.mainloop()
</code>```

答:
Consider this line of code:

```<code>self.testvar.trace('w',self.testfun())
</code>```

This is exactly the same as this:

```<code>result = self.testfun()
self.testvar.trace('w', result)
</code>```

Since the function returns None, the trace is going to try to call None, and thus you get 'NoneType' object is not callable

The trace method requires a callable. That is, a reference to a function. You need to change that line to be the following (notice the missing () at the end):

```<code>self.testvar.trace('w',self.testfun)
</code>```

Also, you need to modify testfun to take arguments that are automatically passed by the tracing mechanism. For more information see What are the arguments to Tkinter variable trace method callbacks?

Title: Python tkinter trace error

Body:
I'm trying to write a GUI for my code. My plan is to use tkinter's StringVar, DoubleVar, etc. to monitor my input in real time. So I found out the DoubleVar.trace('w', callback) function. However, every time I make the change I get an exception:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
TypeError: 'NoneType' object is not callable

I have no idea what's going wrong. I'm using python 2.7
My code is as follows:

from Tkinter import *
class test(Frame):
    def __init__(self,master):
        Frame.__init__(self,master=None)
        self.main_frame = Frame(master);
        self.main_frame.pack()
        self.testvar = DoubleVar()
        self.slider_testvar = Scale(self.main_frame,variable = self.testvar,from_ = 0.2, to = 900, resolution = 0.1, orient=HORIZONTAL,length = 300)
        self.slider_testvar.grid(row = 0, column = 0, columnspan = 5)
        self.testvar.trace('w',self.testfun())
    def testfun(self):
        print(self.testvar.get())

root = Tk()
root.geometry("1024x768")
app = test(master = root)
root.mainloop()

Body:
Consider this line of code:

self.testvar.trace('w',self.testfun())

This is exactly the same as this:

result = self.testfun()
self.testvar.trace('w', result)

Since the function returns None, the trace is going to try to call None, and thus you get 'NoneType' object is not callable

The trace method requires a callable. That is, a reference to a function. You need to change that line to be the following (notice the missing () at the end):

self.testvar.trace('w',self.testfun)

Also, you need to modify testfun to take arguments that are automatically passed by the tracing mechanism. For more information see What are the arguments to Tkinter variable trace method callbacks?


问:
Web Services aspx Property of class doesn't keep default value
I'm Making a aspx web Services in vb.net. I receive an object array parameter letting the framework worry about cast validations as you can see

```<code>   <ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
       <WebMethod(True)> _
    Public Function insertarUnidad(ByVal unidades() As unidad) As String
</code>```

and I have a public class defined

```<code>Public Class unidad

Public Property id_unidad As String
Public Property nombre As String ="I'm Not Empty"
Public Property placas As String = "N"
END Class
</code>```

it turns out that when I'm debugging, the Object arrays doesn't have the default values of some propertys like placas, instead they have "0" value Which is the default value of String data type. but somehow the in the property nombre it does have the default value "I'm Not Empty".

how can I use the default value that I'm putting in the properties without losing it?

Thanks, sorry for my bad English.

UPDATE

The aspx was on .net4.5 and from web app it was working perfectly, but in a console app wasn't working because the console app was on net4.0
it get fixed changing the framework target from 4.5 to 4.0,
Even if the console app is in 4.5 framework the aspx works perfectly.

答:
Even a "" empty string will override those values.  But this is a good use case of a Get and a Set for the properties!</p>

```<code>Public Class unidad
    Private _nombre as string
    Private _placas as string
    Public Property id_unidad As String Public Property placas
        Get
            Return _placas
        End Get
        Set(ByVal value As String)
            If value = "0" then
               _placas = "N"
            else
               _placas = value
            end if
        End Set
    End Property
    Public Property nombre
            Get
                Return _nombre
            End Get
            Set(ByVal value As String)
                If value = "0" then
                   _nombre = "I'm Not Empty"
                else
                   _nombre = value
                end if
            End Set
    End Property
End Class
'Your if statements may need changed
</code>```

Body:
Even a "" empty string will override those values.  But this is a good use case of a Get and a Set for the properties!

Public Class unidad
    Private _nombre as string
    Private _placas as string
    Public Property id_unidad As String Public Property placas
        Get
            Return _placas
        End Get
        Set(ByVal value As String)
            If value = "0" then
               _placas = "N"
            else
               _placas = value
            end if
        End Set
    End Property
    Public Property nombre
            Get
                Return _nombre
            End Get
            Set(ByVal value As String)
                If value = "0" then
                   _nombre = "I'm Not Empty"
                else
                   _nombre = value
                end if
            End Set
    End Property
End Class
'Your if statements may need changed


问:
jQuery UI autocomplete - selectfirst extension
I am using the jQuery UI autocomplete 1.8.6 and need to include the selectfirst functionality into this. I downloaded the selectfirst extension js from
https://github.com/scottgonzalez/jquery-ui-extensions/blob/master/autocomplete/jquery.ui.autocomplete.selectFirst.js

Can someone tell me how to use this extension with the core autocomplete functionality? If I try to add the selectFirst option to the autocomplete widget, it gives error that it is not a valid property.

答:
I was able to get this working by simply

Adding the reference code to my page

Including selectFirst: true in the options for the autocomplete

There is a demo here:

http://dev.nemikor.com/jquery-ui-extensions/autocomplete/selectFirst.html

ContentLicense: CC BY-SA 4.0


问:
How can I know the character set of HTML content by HTTP headers?
I know the parameter charset= in the HTTP header:Content-Type can be used to determine the character set of the HTML  content. But if the parameter is missing in the Content-Type header, how can I know the character set of the HTML content?

I also know there is tag such as

```<code>"meta charset="utf-8""
</code>```

in HTML that is used to specify the character set. But we get that tag only after parsing the HTML and parsing HTML needs to know the character set first.

答:
In the absence of an explicit charset attribute in the Content-Type header, different media types sent over different transports have different default character sets.

For instance, just to show a few definitions:

RFC 2046, Section 4.1.2 of the MIME specification says:

Unlike some other parameter values, the values of the charset parameter are NOT case sensitive.  The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

RFC 2616, Section 3.7.1 of the HTTP protocol specification says:

The "charset" parameter is used with some media types to define the character set (section 3.4) of the data. When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value. See section 3.4.1 for compatibility problems.

Which was later reversed by RFC 7231, Appendix B:

The default charset of ISO-8859-1 for text media types has been removed; the default is now whatever the media type definition says. Likewise, special treatment of ISO-8859-1 has been removed from the Accept-Charset header field.  (Section 3.1.1.3 and Section 5.3.3).

RFC 3023, Sections 3.1, 3.3, 3.6, and 8.5 of the XML Media Types spec say:

Conformant with [RFC2046], if a text/xml entity is received with the charset parameter omitted, MIME processors and XML processors MUST use the default charset value of "us-ascii"[ASCII].  In cases where the XML MIME entity is transmitted via HTTP, the default charset value is still "us-ascii".  (Note: There is an inconsistency between this specification and HTTP/1.1, which uses ISO-8859-1[ISO8859] as the default for a historical reason.  Since XML is a new format, a new default should be chosen for better I18N.  US-ASCII was chosen, since it is the intersection of UTF-8 and ISO-8859-1 and since it is already used by MIME.)

The charset parameter of text/xml-external-parsed-entity is handled the same as that of text/xml as described in Section 3.1.

The following list applies to text/xml, text/xml-external-parsed-entity, and XML-based media types under the top-level type "text" that define the charset parameter according to this specification:

...

If the charset parameter is not specified, the default is "us-ascii".  The default of "iso-8859-1" in HTTP is explicitly overridden.

This example shows text/xml with the charset parameter omitted.  In this case, MIME and XML processors MUST assume the charset is "us-ascii", the default charset value for text media types specified in [RFC2046].  The default of "us-ascii" holds even if the text/xml entity is transported using HTTP.

Omitting the charset parameter is NOT RECOMMENDED for text/xml.  For example, even if the contents of the XML MIME entity are UTF-16 or UTF-8, or the XML MIME entity has an explicit encoding declaration, XML and MIME processors MUST assume the charset is "us-ascii".

RFC 7159, Sections 8.1 and 11, of the JSON specification says:

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.  The default encoding is UTF-8, and JSON texts that are encoded in UTF-8 are interoperable in the sense that they will be read successfully by the maximum number of implementations; there are many implementations that cannot successfully read texts in other encodings (such as UTF-16 and UTF-32).

Implementations MUST NOT add a byte order mark to the beginning of a JSON text.  In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

Note:  No "charset" parameter is defined for this registration. Adding one really has no effect on compliant recipients.

So, in general, if you want to know the charset used by a given resource, and that charset is not expressed through external means, like the charset attribute of a Content-Type header, then you have to determine what type of data you are dealing with, and then determine its charset based on how that data type's specification outlines.

In your case, you are dealing with HTML over HTTP, so the RFC 2616 rule applies to you.  The HTML 5 spec, Section 8.2.2.2 defines a very detailed algorithm for determining the HTML's charset when no charset attribute is specified in the Content-Type header.  That algorithm involves first checking for the presence of a UTF BOM, and if none is present then assume the HTML is 8-bit and parse it for any <meta> tags that contain character set or language declarations.

The XML 1.0 specification, Appendix F, also defines an algorithm that makes it easy to determine the character set used by the XML prolog, so you can read its Encoding attribute, if present, to determine the character set of the remaining XML.

Body:
I know the parameter charset= in the HTTP header:Content-Type can be used to determine the character set of the HTML  content. But if the parameter is missing in the Content-Type header, how can I know the character set of the HTML content?

I also know there is tag such as

"meta charset="utf-8""

in HTML that is used to specify the character set. But we get that tag only after parsing the HTML and parsing HTML needs to know the character set first.


问:
Chess: quiescence search dominating runtime
I have implemented an alpha-beta search with quiescence search for my chess engine. However, in most positions, the quiescence search is taking 80-90% of the total execution time, as indicated by my profiler. Do I have a bug with my pruning?

I have included both the alpha-beta routine and the quiescence routine.

My quiescence search is based directly on this pseudocode.

```<code>// Perform the alpha-beta search.
func ab(b *dragontoothmg.Board, alpha int16, beta int16, depth int8, halt chan bool, stop *bool) (int16, dragontoothmg.Move) {
    nodeCount++

    if *stop {
        return alpha, 0
    }

    found, tableMove, tableEval, tableDepth, tableNodeType := transtable.Get(b)
    if found && tableDepth >= depth {
        if tableNodeType == transtable.Exact {
            return tableEval, tableMove
        } else if tableNodeType == transtable.LowerBound {
            alpha = max(alpha, tableEval)
        } else { // upperbound
            beta = min(beta, tableEval)
        }
        if alpha >= beta {
            return tableEval, tableMove
        }
    }
    if depth == 0 {
        //return eval.Evaluate(b), 0
        return quiesce(b, alpha, beta, stop), 0
    }

    alpha0 := alpha
    bestVal := int16(negInf)
    moves := b.GenerateLegalMoves()
    var bestMove dragontoothmg.Move
    if len(moves) > 0 {
        bestMove = moves[0] // randomly pick some move
    }
    for _, move := range moves {
        unapply := b.Apply(move)
        var score int16
        score, _ = ab(b, -beta, -alpha, depth-1, halt, stop)
        score = -score
        unapply()
        if score > bestVal {
            bestMove = move
            bestVal = score
        }
        alpha = max(alpha, score)
        if alpha >= beta {
            break
        }
    }

    if *stop {
        return bestVal, bestMove
    }

    var nodeType uint8
    if bestVal <= alpha0 {
        nodeType = transtable.UpperBound
    } else if bestVal >= beta {
        nodeType = transtable.LowerBound
    } else {
        nodeType = transtable.Exact
    }
    transtable.Put(b, bestMove, bestVal, depth, nodeType)
    return bestVal, bestMove
}

func quiesce(b *dragontoothmg.Board, alpha int16, beta int16, stop *bool) int16 {
    nodeCount++
    if *stop {
        return alpha
    }
    var standPat int16
    found, _, evalresult, _, ntype := transtable.Get(b)
    if found && ntype == transtable.Exact {
        standPat = evalresult
    } else {
        standPat = eval.Evaluate(b)
        transtable.Put(b, 0, standPat, 0, transtable.Exact)
    }
    if standPat >= beta {
        return beta
    }
    if alpha < standPat {
        alpha = standPat
    }
    moves := b.GenerateLegalMoves()
    if len(moves) == 0 { // TODO(dylhunn): What about stalemate?
        return negInf
    }
    for _, move := range moves {
        if !isCapture(move, b) {
            continue
        }
        unapply := b.Apply(move)
        score := -quiesce(b, -beta, -alpha, stop)
        unapply()
        if score >= beta {
            return beta
        }
        if score > alpha {
            alpha = score
        }
    }
    return alpha
}

func isCapture(m dragontoothmg.Move, b *dragontoothmg.Board) bool {
    toBitboard := (uint64(1) << m.To())
    return (toBitboard&b.White.All != 0) || (toBitboard&b.Black.All != 0)
}
</code>```

答:
If I read your code correctly, you are searching all captures. What you can do to save work, is to prune the hopeless captures move. It turns out that it is quite common that moves are so bad that it is safe to skip them, so the technique is quite safe.

For example, take a look at this position:

FEN: rnbqkbnr/pppppppp/8/8/8/8/1PP1PPP1/RNBQKBNR w KQkq - 0 1

There are three captures:

Rxa7

Qxd7+

Rxh7

Let us assume the engine first tries the capture move with the queen. Black has four ways to capture back, but any of these moves will likely result in a cutoff.

For instance, black plays Bxd7. Now white has two captures in the resulting position, Rxa7 or Rxh7.

Here, most engines will recognize that white has already fallen back in material (in comparison to beta) that even capturing a pawn will not help. So, both of this rook captures are unlikely to result in a cutoff.

Here, your current search would still continue to search these moves. Detecting such cases and skipping these moves will save a lot of work.

There are further optimizations. For example, strong engines with static exchange evaluation will immediately see that Qxd7 will win one pawn but will loose the queen. As this is a bad trade, the engine can immediately skip this move. The same goes for the other two rook captures.

As always, there is a trade-off, though. If you prune too aggressively, you will eventually prune good moves, too. In general, I would recommend to spend more time in the normal search, not in the quiescence search, so aggressive pruning should be fine.

Body:
I have implemented an alpha-beta search with quiescence search for my chess engine. However, in most positions, the quiescence search is taking 80-90% of the total execution time, as indicated by my profiler. Do I have a bug with my pruning?

I have included both the alpha-beta routine and the quiescence routine.

My quiescence search is based directly on this pseudocode.

// Perform the alpha-beta search.
func ab(b *dragontoothmg.Board, alpha int16, beta int16, depth int8, halt chan bool, stop *bool) (int16, dragontoothmg.Move) {
    nodeCount++

    if *stop {
        return alpha, 0
    }

    found, tableMove, tableEval, tableDepth, tableNodeType := transtable.Get(b)
    if found && tableDepth >= depth {
        if tableNodeType == transtable.Exact {
            return tableEval, tableMove
        } else if tableNodeType == transtable.LowerBound {
            alpha = max(alpha, tableEval)
        } else { // upperbound
            beta = min(beta, tableEval)
        }
        if alpha >= beta {
            return tableEval, tableMove
        }
    }
    if depth == 0 {
        //return eval.Evaluate(b), 0
        return quiesce(b, alpha, beta, stop), 0
    }

    alpha0 := alpha
    bestVal := int16(negInf)
    moves := b.GenerateLegalMoves()
    var bestMove dragontoothmg.Move
    if len(moves) > 0 {
        bestMove = moves[0] // randomly pick some move
    }
    for _, move := range moves {
        unapply := b.Apply(move)
        var score int16
        score, _ = ab(b, -beta, -alpha, depth-1, halt, stop)
        score = -score
        unapply()
        if score > bestVal {
            bestMove = move
            bestVal = score
        }
        alpha = max(alpha, score)
        if alpha >= beta {
            break
        }
    }

    if *stop {
        return bestVal, bestMove
    }

    var nodeType uint8
    if bestVal <= alpha0 {
        nodeType = transtable.UpperBound
    } else if bestVal >= beta {
        nodeType = transtable.LowerBound
    } else {
        nodeType = transtable.Exact
    }
    transtable.Put(b, bestMove, bestVal, depth, nodeType)
    return bestVal, bestMove
}

func quiesce(b *dragontoothmg.Board, alpha int16, beta int16, stop *bool) int16 {
    nodeCount++
    if *stop {
        return alpha
    }
    var standPat int16
    found, _, evalresult, _, ntype := transtable.Get(b)
    if found && ntype == transtable.Exact {
        standPat = evalresult
    } else {
        standPat = eval.Evaluate(b)
        transtable.Put(b, 0, standPat, 0, transtable.Exact)
    }
    if standPat >= beta {
        return beta
    }
    if alpha < standPat {
        alpha = standPat
    }
    moves := b.GenerateLegalMoves()
    if len(moves) == 0 { // TODO(dylhunn): What about stalemate?
        return negInf
    }
    for _, move := range moves {
        if !isCapture(move, b) {
            continue
        }
        unapply := b.Apply(move)
        score := -quiesce(b, -beta, -alpha, stop)
        unapply()
        if score >= beta {
            return beta
        }
        if score > alpha {
            alpha = score
        }
    }
    return alpha
}

func isCapture(m dragontoothmg.Move, b *dragontoothmg.Board) bool {
    toBitboard := (uint64(1) << m.To())
    return (toBitboard&b.White.All != 0) || (toBitboard&b.Black.All != 0)
}


问:
How can reuse figure in Matlab?
I would like to reuse a figure I create in Matlab script.

```<code>fig1 = figure;
plot(...);
title(...);
% ...
% now I would like to plot fig1 again with a different title
% ...
% now I would like to plot fig1 again as a subplot in a 2x2 grid
</code>```

How can I do that without code duplication?

Can I use the figure object? Or perhaps save the plot object somehow?

答:
fig1 = figure;

p1=plot(...);

title('something');

% ...

% now I would like to plot fig1 again with a different title

title('something else'); % This will replace the old title with the new one 'something_else'.

% now I would like to plot fig1 again as a subplot in a 2x2 grid

delete(p1);

subplot(2,2,1);

p1=plot(...);

OR, you can just refresh your figure (without closing it and opening another one...) by typing:

clf reset

This will reset all figure properties, such as background color.  Then, you can re-plot whatever you like.

Title: How can reuse figure in Matlab?

Body:
I would like to reuse a figure I create in Matlab script.

fig1 = figure;
plot(...);
title(...);
% ...
% now I would like to plot fig1 again with a different title
% ...
% now I would like to plot fig1 again as a subplot in a 2x2 grid

How can I do that without code duplication?

Can I use the figure object? Or perhaps save the plot object somehow?


问:
SonarQube How to set analysis for C# Only in TFS and MSBuild
I am trying to get a TFS build work flow to analyse for only C# code.

According to the documentation https://docs.sonarqube.org/display/SONAR/Analysis+Parameters

I need to pass /d:sonar.language with the name of the language to prevent multi-language analysis.  The documentation then links to the plugins page for a selection of languages.

I have tried every permutation I can think of C#, csharp, sonar-csharp etc. but I constantly get an error such as this:

```<code>ERROR: Error during SonarQube Scanner execution
ERROR: You must install a plugin that supports the language 'sonar-csharp'
</code>```

I'm obviously missing a trick somewhere, can anyone point me in the right direction?

We are using:

SonarQube 6.4

SonarQube Scanner for MSbuild - Begin Analysis (new) v2.1.2

TFS 2015

答: If you are still wanting to go the route of using that parameter and not file exclusions (with which wildcards would do what you need), go ahead and just try "cs", I'm pretty sure that's the correct permutation.</p>

Body:
I am trying to get a TFS build work flow to analyse for only C# code.

According to the documentation https://docs.sonarqube.org/display/SONAR/Analysis+Parameters

I need to pass /d:sonar.language with the name of the language to prevent multi-language analysis.  The documentation then links to the plugins page for a selection of languages.

I have tried every permutation I can think of C#, csharp, sonar-csharp etc. but I constantly get an error such as this:

ERROR: Error during SonarQube Scanner execution
ERROR: You must install a plugin that supports the language 'sonar-csharp'

I'm obviously missing a trick somewhere, can anyone point me in the right direction?

We are using:

SonarQube 6.4

SonarQube Scanner for MSbuild - Begin Analysis (new) v2.1.2

TFS 2015


问:
Enable Infopath button
Ok so am fairly new to SharePoint and InfoPath but here is the thing. I have made this form in InfoPath. Section A gets data from a SharePoint library, Section B get data from another SharePoint library but that data is dependent on the data in Section A. Section C gets data from another different library but the data is also dependent on whats in Section A. So now I want the 'Show' button I have circled to be disable and enabled only when the queried record exists in the Library of Section C.
InfoPath Form image</p>

答: On the Button you want disabled, create a Formatting Rule to disable that control with a condition of one of your fields being empty or some value it wouldnt be until the other section is showing that data.</p>

Title: Enable Infopath button


问:
Windows bat: how to process files for each subdirectories
I need to use a bat named here.bat to process files in the same directories. Here is an example:

```<code>mydir
 |----mybat.bat
 |----here.bat
 |----subdir
        |-----subdir2
                 |-----subdir3
                          |-----subdir31
                          |        |-----a.jpg
                          |
                          |-----subdir32
                                   |-----b.jpg
</code>```

I need to use here.bat to process a.jpg and b.jpg. So I write a bat file named mybat.bat as below:

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (.\subdir\*) Do (
  Set "Files="
  For /F "delims=" %%B in ('dir /S /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
  If defined Files echo call here.bat !Files!
)

pause
</code>```

When I execute mybat.bat, I get the result as below:

```<code>call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\subdire31\a.jpg" "C:\Users\me\mydir\subdir\subdir2\subdir3\sudbir32\b.jpg"
</code>```

But this is not what I need. I need to process jpg files which are in the same directory with here.bat, if they are not in the same directory, they should be processed separately. Meaning that I need the result as below:

```<code>call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\subdire31\a.jpg"
call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\sudbir32\b.jpg"
</code>```

答:
Your changing requirements make it difficult to provide a solution in the first run. This version should do:</p>

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
for /R ".\subdir" %%A in (.) do (
  Set "Files="
  If Exist "%%~fA\*.jpg" For /F "delims=" %%B in (
      'dir /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
  If defined Files echo call here.bat !Files!
)
pause
</code>```

Body:
I need to use a bat named here.bat to process files in the same directories. Here is an example:

mydir
 |----mybat.bat
 |----here.bat
 |----subdir
        |-----subdir2
                 |-----subdir3
                          |-----subdir31
                          |        |-----a.jpg
                          |
                          |-----subdir32
                                   |-----b.jpg

I need to use here.bat to process a.jpg and b.jpg. So I write a bat file named mybat.bat as below:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (.\subdir\*) Do (
  Set "Files="
  For /F "delims=" %%B in ('dir /S /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
  If defined Files echo call here.bat !Files!
)

pause

When I execute mybat.bat, I get the result as below:

call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\subdire31\a.jpg" "C:\Users\me\mydir\subdir\subdir2\subdir3\sudbir32\b.jpg"

But this is not what I need. I need to process jpg files which are in the same directory with here.bat, if they are not in the same directory, they should be processed separately. Meaning that I need the result as below:

call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\subdire31\a.jpg"
call here.bat "C:\Users\me\mydir\subdir\subdir2\subdir3\sudbir32\b.jpg"

Body:
Your changing requirements make it difficult to provide a solution in the first run. This version should do:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
for /R ".\subdir" %%A in (.) do (
  Set "Files="
  If Exist "%%~fA\*.jpg" For /F "delims=" %%B in (
      'dir /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
  If defined Files echo call here.bat !Files!
)
pause


问:
Conditional fortran record variable selection
I have a structure defined:

```<code>STRUCTURE /IOA/
  INTEGER*2 ID
  .....
END STRUCTURE
</code>```

I need to create another structure, IOB. IOB contains all the same fields as IOA but with many more.

```<code>STRUCTURE /IOB/
  INTEGER*2 ID
  .....
END STRUCTURE
</code>```

My program currently has:

```<code>RECORD /IOA/ A
RECORD /IOB/ B
</code>```

The program will either use A or B depending on a user input.

Is there any way to have some sort of conditional in the code to use A or B depending on what's required? For example, is it possible to create a placeholder record (variable?) "IO" and define it based on the input?:

```<code>If user input = 1, IO = A
else IO = B
.....

IO.ID = 30
</code>```

Thank you.

答:
My recommendation is to make the type IO_TYPE in a module, and have it contain a POINTER to a type with the extra stuff you may or may not need:

```<code>MODULE IO_TYPES
  TYPE EXTRA_STUFF
     INTEGER :: AGE
     INTEGER :: HEIGHT
     INTEGER :: WIEGHT
  END type EXTRA_STUFF
  TYPE IO_TYPE
     INTEGER :: ID
     TYPE(EXTRA_STUFF), POINTER :: EXT
  END type IO_TYPE

END MODULE IO_TYPES
</code>```

Then, in your program, which will have USE IO_TYPES, of course, you can decide whether to allocate that pointer:

```<code>TYPE (IO_TYPE) :: IO
INTEGER        :: IERR_ALLOC

IF ( USER_INPUT .EQ. 1 ) ALLOCATE( IO%EXT, STAT=IERR_ALLOC )
IF ( IERR_ALLOC .NE. 0 ) STOP 1
</code>```

(Always check the results of ALLOCATE statements.)

Body:
I have a structure defined:

STRUCTURE /IOA/
  INTEGER*2 ID
  .....
END STRUCTURE

I need to create another structure, IOB. IOB contains all the same fields as IOA but with many more.

STRUCTURE /IOB/
  INTEGER*2 ID
  .....
END STRUCTURE

My program currently has:

RECORD /IOA/ A
RECORD /IOB/ B

The program will either use A or B depending on a user input.

Is there any way to have some sort of conditional in the code to use A or B depending on what's required? For example, is it possible to create a placeholder record (variable?) "IO" and define it based on the input?:

If user input = 1, IO = A
else IO = B
.....

IO.ID = 30

Thank you.

Body:
My recommendation is to make the type IO_TYPE in a module, and have it contain a POINTER to a type with the extra stuff you may or may not need:

MODULE IO_TYPES
  TYPE EXTRA_STUFF
     INTEGER :: AGE
     INTEGER :: HEIGHT
     INTEGER :: WIEGHT
  END type EXTRA_STUFF
  TYPE IO_TYPE
     INTEGER :: ID
     TYPE(EXTRA_STUFF), POINTER :: EXT
  END type IO_TYPE

END MODULE IO_TYPES

Then, in your program, which will have USE IO_TYPES, of course, you can decide whether to allocate that pointer:

TYPE (IO_TYPE) :: IO
INTEGER        :: IERR_ALLOC

IF ( USER_INPUT .EQ. 1 ) ALLOCATE( IO%EXT, STAT=IERR_ALLOC )
IF ( IERR_ALLOC .NE. 0 ) STOP 1

(Always check the results of ALLOCATE statements.)


问:
Can DPI scaling be enabled/disabled programmatically on a per-session basis?
My application happens to be written in Python using pygame, which wraps SDL, but I'm imagining that this is probably a more-general question to do with the Windows API.

In some of my Python applications, I want pixel-for-pixel control under Windows 10 even at high resolutions.  I want to be able to ensure, for example, that if my Surface Pro 3 has a native resolution of 2160x1440, then I can enter full-screen mode with those dimensions and present a full-screen image of exactly those dimensions.

The barrier to this is "DPI scaling".  By default, under Windows' Settings -> Display, the value of "Change the size of text, apps, and other items"  is "150% (Recommended)" and the result is that I only see 2/3 of my image.  I have discovered how to fix this behaviour...

systemwide, by moving that slider down to 100% (but that's undesirable for most other applications)

just for python.exe and pythonw.exe, by going to those executables' "Properties" dialogs, Compatibility tab, and clicking "Disable display scaling on high DPI settings".  I can do this for me alone, or for all users.  I can also automate this process by setting the appropriate keys in the registry programmatically. Or via .exe.manifest files (which also seems to require a global setting change, to prefer external manifests, with possible side-effects on other applications).

My question is: can I do this from inside my program on a per-launch basis, before I open my graphics window?  I, or anyone using my software, won't necessarily want this setting enabled for all Python applications ever—we might want it just when running particular Python programs.  I'm imagining there might be a winapi call (or failing that something inside SDL, wrapped by pygame) that could achieve this, but so far my research is drawing a blank.

答:
Here's the answer I was looking for, based on comments by IInspectable and andlabs (many thanks):

  import ctypes

  # Query DPI Awareness (Windows 10 and 8)
  awareness = ctypes.c_int()
  errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
  print(awareness.value)

  # Set DPI Awareness  (Windows 10 and 8)
  errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
  # the argument is the awareness level, which can be 0, 1 or 2:
  # for 1-to-1 pixel control I seem to need it to be non-zero (I'm using level 2)

  # Set DPI Awareness  (Windows 7 and Vista)
  success = ctypes.windll.user32.SetProcessDPIAware()
  # behaviour on later OSes is undefined, although when I run it on my Windows 10 machine, it seems to work with effects identical to SetProcessDpiAwareness(1)
```

<p>The awareness levels are defined as follows:</p>

<pre class="lang-c prettyprint-override"><code>typedef enum _PROCESS_DPI_AWARENESS {
    PROCESS_DPI_UNAWARE = 0,
    /*  DPI unaware. This app does not scale for DPI changes and is
        always assumed to have a scale factor of 100% (96 DPI). It
        will be automatically scaled by the system on any other DPI
        setting. */

    PROCESS_SYSTEM_DPI_AWARE = 1,
    /*  System DPI aware. This app does not scale for DPI changes.
        It will query for the DPI once and use that value for the
        lifetime of the app. If the DPI changes, the app will not
        adjust to the new DPI value. It will be automatically scaled
        up or down by the system when the DPI changes from the system
        value. */

    PROCESS_PER_MONITOR_DPI_AWARE = 2
    /*  Per monitor DPI aware. This app checks for the DPI when it is
        created and adjusts the scale factor whenever the DPI changes.
        These applications are not automatically scaled by the system. */
} PROCESS_DPI_AWARENESS;
</code>```

Level 2 sounds most appropriate for my goal although 1 will also work provided there's no change in system resolution / DPI scaling.

SetProcessDpiAwareness will fail with errorCode = -2147024891 = 0x80070005 = E_ACCESSDENIED if it has previously been called for the current process  (and that includes being called by the system when the process is launched, due to a registry key or .manifest file)

Body:
Here's the answer I was looking for, based on comments by IInspectable and andlabs (many thanks):

  import ctypes

  # Query DPI Awareness (Windows 10 and 8)
  awareness = ctypes.c_int()
  errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
  print(awareness.value)

  # Set DPI Awareness  (Windows 10 and 8)
  errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
  # the argument is the awareness level, which can be 0, 1 or 2:
  # for 1-to-1 pixel control I seem to need it to be non-zero (I'm using level 2)

  # Set DPI Awareness  (Windows 7 and Vista)
  success = ctypes.windll.user32.SetProcessDPIAware()
  # behaviour on later OSes is undefined, although when I run it on my Windows 10 machine, it seems to work with effects identical to SetProcessDpiAwareness(1)

The awareness levels are defined as follows:

typedef enum _PROCESS_DPI_AWARENESS {
    PROCESS_DPI_UNAWARE = 0,
    /*  DPI unaware. This app does not scale for DPI changes and is
        always assumed to have a scale factor of 100% (96 DPI). It
        will be automatically scaled by the system on any other DPI
        setting. */

    PROCESS_SYSTEM_DPI_AWARE = 1,
    /*  System DPI aware. This app does not scale for DPI changes.
        It will query for the DPI once and use that value for the
        lifetime of the app. If the DPI changes, the app will not
        adjust to the new DPI value. It will be automatically scaled
        up or down by the system when the DPI changes from the system
        value. */

    PROCESS_PER_MONITOR_DPI_AWARE = 2
    /*  Per monitor DPI aware. This app checks for the DPI when it is
        created and adjusts the scale factor whenever the DPI changes.
        These applications are not automatically scaled by the system. */
} PROCESS_DPI_AWARENESS;

Level 2 sounds most appropriate for my goal although 1 will also work provided there's no change in system resolution / DPI scaling.

SetProcessDpiAwareness will fail with errorCode = -2147024891 = 0x80070005 = E_ACCESSDENIED if it has previously been called for the current process  (and that includes being called by the system when the process is launched, due to a registry key or .manifest file)


问:
Displaying Data on Website from Node.js (Without Frameworks)
I have a Node.js webserver and I am fetching data from a mysql Server. The fetched Data needs to be displayed now in the frontend as HTML. I am not allowed to use any 3rd Party node.js/JavaScript framework's.

I'm new to Webserver development and i'm having a hard time figuring out how to "transport" the Backend Data to the Frontend.

I have 2 Ideas in my mind but dont know what's the right way to approach this problem...

Send Data via JSON to Client and process it with JavaScript. (Possible? and if yes how?)

Before sending the HTTP response, parse the HTML and insert the data. (Complicated without using Frameworks and too costly ?)

What would be the right way to solve this problem ?

Any Help would be appreciated. Thank's.

答:
Something like this?</p>

```<code>const http = require('http');
const util = require('util');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  mysql.query("select * from table").then(rows => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`<html><head></head><body>${util.inspect(rows)}</body></html>`);
  })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
</code>```

Body:
Something like this?

const http = require('http');
const util = require('util');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  mysql.query("select * from table").then(rows => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`<html><head></head><body>${util.inspect(rows)}</body></html>`);
  })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});


问:
How to make a bar chart, with x-labels and legend, directly from a table of listed data
I have a data table tb that looks something like this, which I want to turn into a bar chart.

```<code>N         X       P
________  ______  ______

0          5      15.314
0         10      36.288
0         13      7.1785
1          5      18.182
1         10      40.997
1         13      8.9741
2          5       17.65
2         10      40.095
2         13       9.276
</code>```

I want the bar chart to look something like this, but without needing to rearrange the table. What is the simplest way to do this?

Currently, my code to do it looks like this, but I expect there should be an easier way to manipulate it:

```<code>y = [tb.P(tb.X==5)' ; tb.P(tb.X==10)' ; tb.P(tb.X==13)'];
b = bar(y);
xlab = arrayfun(@num2str, Xlist, 'uniformoutput', false);
set(gca,'xticklabel',xlab);
leg = arrayfun(@num2str, Nlist, 'uniformoutput', false);;
legend(b,leg)
</code>```

What would be the proper method for doing this?

答:
You can do this a little easier with unique and accumarray:

```<code>[nValues, ~, nIndex] = unique(tb.N);
[xValues, ~, xIndex] = unique(tb.X);
bar(accumarray([xIndex nIndex], tb.P));
set(gca, 'XTickLabel', xValues);
legend(int2str(nValues));
</code>```

Body:
I have a data table tb that looks something like this, which I want to turn into a bar chart.

N         X       P
________  ______  ______

0          5      15.314
0         10      36.288
0         13      7.1785
1          5      18.182
1         10      40.997
1         13      8.9741
2          5       17.65
2         10      40.095
2         13       9.276

I want the bar chart to look something like this, but without needing to rearrange the table. What is the simplest way to do this?

Currently, my code to do it looks like this, but I expect there should be an easier way to manipulate it:

y = [tb.P(tb.X==5)' ; tb.P(tb.X==10)' ; tb.P(tb.X==13)'];
b = bar(y);
xlab = arrayfun(@num2str, Xlist, 'uniformoutput', false);
set(gca,'xticklabel',xlab);
leg = arrayfun(@num2str, Nlist, 'uniformoutput', false);;
legend(b,leg)

What would be the proper method for doing this?

Body:
You can do this a little easier with unique and accumarray:

[nValues, ~, nIndex] = unique(tb.N);
[xValues, ~, xIndex] = unique(tb.X);
bar(accumarray([xIndex nIndex], tb.P));
set(gca, 'XTickLabel', xValues);
legend(int2str(nValues));


问:
gsub regex not matching in R
I have a string that's formatted like:

```<code>x <- "\r\n\t\t\tExample\t\t\t"
</code>```

I want to extract the "Example" in the middle, and I thought to do this by using gsub to match every backslash followed by a lowercase letter and replacing them with an empty string using gsub. I've tried a variety of patterns, checking that they match correctly on regex101.com, but whenever I put them into R, the output is exactly the same as the beginning string.

Here's the gsub calls with the expressions I've tried that have all failed to return anything but the original string:

```<code>y <- gsub("\\W[:lower:]", "", x)
y <- gsub("(\\W[:lower:])*", "", x)
y <- gsub("(\\[a-z])*", "", x)
y <- gsub("\\[a-z]*", "", x)
y <- gsub("\\W[a-z]", "", x)
y <- gsub("\\[a-z]", "", x)
</code>```

I'm at my wit's end here. These patterns all seem to match what I need them to on the website, but they do nothing when plugged into gsub. My understanding of gsub is that it replaces every match in the string, not just the first, but this isn't even replacing the very first match. y always comes out identical to x.

答:
Use trimws to get rid of leading/trailing whitespace:

```<code>x <- "\r\n\t\t\tExample\t\t\t"
trimws(x)
</code>```

See online demo

\r - is a CR symbol

\n - is an LF symbol

\t - is a tab symbol.

Title: gsub regex not matching in R

Body:
I have a string that's formatted like:

x <- "\r\n\t\t\tExample\t\t\t"

I want to extract the "Example" in the middle, and I thought to do this by using gsub to match every backslash followed by a lowercase letter and replacing them with an empty string using gsub. I've tried a variety of patterns, checking that they match correctly on regex101.com, but whenever I put them into R, the output is exactly the same as the beginning string.

Here's the gsub calls with the expressions I've tried that have all failed to return anything but the original string:

y <- gsub("\\W[:lower:]", "", x)
y <- gsub("(\\W[:lower:])*", "", x)
y <- gsub("(\\[a-z])*", "", x)
y <- gsub("\\[a-z]*", "", x)
y <- gsub("\\W[a-z]", "", x)
y <- gsub("\\[a-z]", "", x)

I'm at my wit's end here. These patterns all seem to match what I need them to on the website, but they do nothing when plugged into gsub. My understanding of gsub is that it replaces every match in the string, not just the first, but this isn't even replacing the very first match. y always comes out identical to x.

Body:
Use trimws to get rid of leading/trailing whitespace:

x <- "\r\n\t\t\tExample\t\t\t"
trimws(x)

See online demo

\r - is a CR symbol

\n - is an LF symbol

\t - is a tab symbol.


问:
Xcode - Invalid character in source file (Replace " " with " ")
I have a question about Xcode (Swift). Sometimes when I write an if statement. Something like this:

```<code>if(a == 2){
//do Sth
} else {
//do Sth
}
</code>```

Xcode throws me an error: "Invalid character in source file"
I know it is no big deal and fixed by clicking on "Fix-it" but I want
to know what is the problem. That doesn't make sense to me...

My Xcode is on 7.2 and I am using Swift - I don't know if this is just a Swift problem.

答: I encountered this problem when I was using a non-Apple keyboard with my iMac. Probably your case too. They add unnecessary control characters! One way to fix it in Xcode ischoose from the menu Editor>Show Invisibles and see if there are any unwanted characters where the error is being thrown and remove them.</p>

Body:
I have a question about Xcode (Swift). Sometimes when I write an if statement. Something like this:

if(a == 2){
//do Sth
} else {
//do Sth
}

Xcode throws me an error: "Invalid character in source file"
I know it is no big deal and fixed by clicking on "Fix-it" but I want
to know what is the problem. That doesn't make sense to me...

My Xcode is on 7.2 and I am using Swift - I don't know if this is just a Swift problem.


问:
CSS - Make a div "clickable"
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

```<code><div class="teamSelector">Some</div>
</code>```

With this jQuery:

```<code>$('.teamSelector').click(function() {
    // some functions
});
</code>```

Cheers

答:
You've already made it clickable in your example. If you would like it to "look" clickable, you can add some CSS:

```<code>.teamSelector { cursor: pointer; }
</code>```

Or continuing with jQuery:

```<code>.click(function() { do something }).css("cursor", "pointer");
</code>```

Here is the W3 schools reference for the cursor property.

Title: CSS - Make a div "clickable"

Body:
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

Some

With this jQuery:

$('.teamSelector').click(function() {
    // some functions
});

Cheers

Body:
You've already made it clickable in your example. If you would like it to "look" clickable, you can add some CSS:

.teamSelector { cursor: pointer; }

Or continuing with jQuery:

.click(function() { do something }).css("cursor", "pointer");

Here is the W3 schools reference for the cursor property.


问:
$_POST is empty. Nginx OSx
I'm trying to access $_POST and it's empty.

If I try to access it on the root (ie. localhost), it WORKS.
If I try to access in a different folder (ie. localhost/foo), it DOESN'T WORK.

Here is my config file:

```<code> server {
        listen   80;

        root /var/www;
        index index.php index.html index.htm;

        server_name localhost;

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
        }

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php {
                try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

}
</code>```

Here is a sample RAW request:

```<code>POST /dev/post-test HTTP/1.1
Host: localhost
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="action"

store
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="id"

4315251
----WebKitFormBoundaryE19zNvXGzXaLvS5C
</code>```

What is the problem?

Thanks.

答:
The key on this differnet behavier is the trailing slash in the route.

For nginx the following are two different requests:

```<code>http://localhost/foo
http://localhost/foo/
</code>```

The first one result in an internal 301 redirect (to index.php into that folder), where the $_POST values are lost.

More about this behavior and solution to prevent it, read the answers below:
Nginx causes 301 redirect if there's no trailing slash

Title: $_POST is empty. Nginx OSx

Body:
I'm trying to access $_POST and it's empty.

If I try to access it on the root (ie. localhost), it WORKS.
If I try to access in a different folder (ie. localhost/foo), it DOESN'T WORK.

Here is my config file:

 server {
        listen   80;

        root /var/www;
        index index.php index.html index.htm;

        server_name localhost;

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
        }

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php {
                try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

}

Here is a sample RAW request:

POST /dev/post-test HTTP/1.1
Host: localhost
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="action"

store
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="id"

4315251
----WebKitFormBoundaryE19zNvXGzXaLvS5C

What is the problem?

Thanks.

Body:
The key on this differnet behavier is the trailing slash in the route.

For nginx the following are two different requests:

http://localhost/foo
http://localhost/foo/

The first one result in an internal 301 redirect (to index.php into that folder), where the $_POST values are lost.

More about this behavior and solution to prevent it, read the answers below:
Nginx causes 301 redirect if there's no trailing slash


问:
Invoke-Command return information to be used in conditional statement Powershell
```<code>for ($i = 0; $i -lt $arrayHold.length; $i++){
        $OSversion = invoke-command -computername $arrayHold[$i] -scriptblock {Get-WMIObject Win32_OperatingSystem} | select-object caption

    # create a nested for loop and throw the OSVERSION into it then nest the $i for loop.
    #if ($OSversion -match "7"){
        $invcmd = invoke-command -computerName  -scriptblock {Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" SMB1} | select-object PSComputerName, SMB1 | format-table -autosize

            #$printInfo = $OSversion + $invcmd
        $array += $invcmd

    #}
}
$array | out-file $save\"$file"
</code>```

Returns:

```<code>PSComputerName SMB1
-------------- ----
XXXXXXXX          0
</code>```

I want to do an IF statement that just looks to see if SMBv1 is equal to 1. How do I suppress the header information and write the statement?

答:
Try this</p>

```<code>$arrayHold = @("TEST_COMPUTER")
for ($i = 0; $i -lt $arrayHold.length; $i++){
    $OSversion = invoke-command -computername $arrayHold[$i] -scriptblock {Get-WMIObject Win32_OperatingSystem} | select-object caption
    $invcmd = invoke-command -computerName $arrayHold[$i]  -scriptblock {Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\" | select-object PSComputerName, SMB1}
    $invcmd

    if($invcmd.SMB1 -eq 1){
        "1"
    }elseif(!$invcmd.smb1){
        "2"
    }else{
        "3"
    }
}
</code>```

Body:
for ($i = 0; $i -lt $arrayHold.length; $i++){
        $OSversion = invoke-command -computername $arrayHold[$i] -scriptblock {Get-WMIObject Win32_OperatingSystem} | select-object caption

    # create a nested for loop and throw the OSVERSION into it then nest the $i for loop.
    #if ($OSversion -match "7"){
        $invcmd = invoke-command -computerName  -scriptblock {Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" SMB1} | select-object PSComputerName, SMB1 | format-table -autosize

            #$printInfo = $OSversion + $invcmd
        $array += $invcmd

    #}
}
$array | out-file $save\"$file"

Returns:

PSComputerName SMB1
-------------- ----
XXXXXXXX          0

I want to do an IF statement that just looks to see if SMBv1 is equal to 1. How do I suppress the header information and write the statement?

Body:
Try this

$arrayHold = @("TEST_COMPUTER")
for ($i = 0; $i -lt $arrayHold.length; $i++){
    $OSversion = invoke-command -computername $arrayHold[$i] -scriptblock {Get-WMIObject Win32_OperatingSystem} | select-object caption
    $invcmd = invoke-command -computerName $arrayHold[$i]  -scriptblock {Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\" | select-object PSComputerName, SMB1}
    $invcmd

    if($invcmd.SMB1 -eq 1){
        "1"
    }elseif(!$invcmd.smb1){
        "2"
    }else{
        "3"
    }
}


问:
In given a line from some file (or stdin) how can i reduce the extra spaces and convert the tabs to single space?
In given a line that exist in array. Like in this case:

```<code>char line[50];
while (fgets(line,50, input_file) != NULL) {
 // how can i do it here..
}
</code>```

How can i reduce all the extra spaces to single space , and to reduce all the tabs (between any two words) to a single space.

For example:

In give this line:

```<code>   a b   abb     ace    ab
</code>```

It's need to be:

```<code>a b abb ace ab
</code>```

答:
like this:</p>

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

char *reduce_and_trim(char *s);

int main(void) {
    FILE *input_file = stdin;
    char line[50];
    while (fgets(line,50, input_file) != NULL) {
        printf("'%s'\n", reduce_and_trim(line));
    }
    fclose(input_file);
}

#include <string.h>

char *reduce_and_trim(char *s){
    static const char *whitespaces = " \t\n";//\t:tab, \n:newline, omit \f\r\v
    size_t src = strspn(s, whitespaces);//Trim of the beginning
    size_t des = 0;//destination
    size_t spc = 0;//number of whitespaces

    while(s[src] != '\0'){
        if((spc = strspn(s+src, whitespaces)) != 0){
            src += spc;
            s[des++] = ' ';//reduce spaces
        } else {
            s[des++] = s[src++];
        }
    }
    if(des && s[des-1] == ' ')
        s[des-1] = 0;//Trim of end
    else
        s[des] = 0;

    return s;
}
</code>```

Body:
In given a line that exist in array. Like in this case:

char line[50];
while (fgets(line,50, input_file) != NULL) {
 // how can i do it here..
}

How can i reduce all the extra spaces to single space , and to reduce all the tabs (between any two words) to a single space.

For example:

In give this line:

   a b   abb     ace    ab

It's need to be:

a b abb ace ab

Body:
like this:

#include <stdio.h>

char *reduce_and_trim(char *s);

int main(void) {
    FILE *input_file = stdin;
    char line[50];
    while (fgets(line,50, input_file) != NULL) {
        printf("'%s'\n", reduce_and_trim(line));
    }
    fclose(input_file);
}

#include <string.h>

char *reduce_and_trim(char *s){
    static const char *whitespaces = " \t\n";//\t:tab, \n:newline, omit \f\r\v
    size_t src = strspn(s, whitespaces);//Trim of the beginning
    size_t des = 0;//destination
    size_t spc = 0;//number of whitespaces

    while(s[src] != '\0'){
        if((spc = strspn(s+src, whitespaces)) != 0){
            src += spc;
            s[des++] = ' ';//reduce spaces
        } else {
            s[des++] = s[src++];
        }
    }
    if(des && s[des-1] == ' ')
        s[des-1] = 0;//Trim of end
    else
        s[des] = 0;

    return s;
}


问:
How to create service for angular2 + apollo-client with graphql
I have no idea to create a service (like a api gateway) for send data that use apollo to my backend w/ graphql.

If i dont have a service. All of my components that want to send or get data from backend w/ graphql always import those 2

```<code>import { Angular2Apollo } from 'angular2-apollo';
import gql from 'graphql-tag';
</code>```

I try to create a service for that but query and mutation function in apollo have many property so my service can't warp all of many property.

Or it not be able to create service for that.

Thanks.

答:
Angular2 and Apollo Client are tools for creating a GraphQL client. You need to create a separate app that is a GraphQL server.

I suggest you create a new app and follow the instructions here: http://dev.apollodata.com/tools/graphql-server

Then you can work on making your Angular2 app make requests to the GraphQL server. For examples you can look here: http://dev.apollodata.com/angular2

Body:
I have no idea to create a service (like a api gateway) for send data that use apollo to my backend w/ graphql.

If i dont have a service. All of my components that want to send or get data from backend w/ graphql always import those 2

import { Angular2Apollo } from 'angular2-apollo';
import gql from 'graphql-tag';

I try to create a service for that but query and mutation function in apollo have many property so my service can't warp all of many property.

Or it not be able to create service for that.

Thanks.


问:
How to set current year and previous year in variables using php?

there is one scenario. assume that:

financial year =  01/04/2017 to 31/03/2018

I have one input field with datepicker and date column in database.
If any user will select    today's date e.g 08/06/2017

then there should display data for this    current year i.e from
01/04/2017 to 08/06/2017 with the help of date    table

and at the same it should display previous year's data i.e from
01/04/2016 to 31/03/2017

For the time I am using $currentdate = date('d/m/Y') to display
whole data from db till current date.

$A1 = mysqli_query($conn,'SELECT sum(netvalue) FROMfintranWHERE
 groupNo = 21 AND docDate <= "'.$currentdate.'" ');

We can create some formula but i am so poor to build logic so please help me

答:
You use Carbon.
<br/>
Documentation :- http://carbon.nesbot.com/docs/ </p>

```<code>$date = Carbon\Carbon::createFromFormat('d/m/Y', $date);
$date->subYear();
echo $date->format('d/m/Y'); // Previous year
</code>```

Body:
You use Carbon.

Documentation :- http://carbon.nesbot.com/docs/

$date = Carbon\Carbon::createFromFormat('d/m/Y', $date);
$date->subYear();
echo $date->format('d/m/Y'); // Previous year


问:
Slow performance with tabbed datatables
I have a web page with 5 data tables in separate tabs. The filter at the top of the page contains a test element which is populated with a code. For each character typed, 5 separate AJAX calls are made to update each tab.
This has resulted in extremely poor performance, for the remote users experiencing wait times of over 3 minutes, effectively making the page useless.

I'm having a hard time to determine which tab is selected and update only the selected tab at a time. I have some bad code I've been trying to get to work, commented in the second code block. Unable to get the tab, to perform the draw, and replace that block of code.  Any guidance appreciated.

These are the tabs:

```<code><ul class="nav nav-tabs" role="tablist" id="Status">
    <li role="presentation" class="active"><a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Tab1 Data</a></li>
    <li role="presentation"><a href="#Tab2" aria-controls="tab2" role="tab" data-toggle="tab">tab2 Data</a></li>
    <li role="presentation"><a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Tab3 Data</a></li>
    <li role="presentation"><a href="#tab4" aria-controls="tab4" role="tab" data-toggle="tab">Tab4 Data</a></li>
    <li role="presentation"><a href="#tab5" aria-controls="tab5" role="tab" data-toggle="tab">Tab5 Data (Legacy)</a></li>
</ul>
</code>```

My current code, has all 5 tabs as show, and walks through each tab

```<code>function filterShortCode () {
    // var tabIndex = &(this).find("a").attr("href");
    // $(tabIndex).DataTable().search(
    $('#gridTab1').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab2').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab3').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab4').DataTable().search(
      $('#global_sc').val()
       ).draw();
    $('#gridTab5').DataTable().search(
      $('#global_sc').val()
       ).draw();
    };
</code>```

答:
If I understood you correctly...</p>

```<code>var activeNavItem = $("#Status li.active");
var activeGrid = $("#Status li").index(activeNavItem)) + 1;

$('#gridTab' + activeGrid).DataTable().search(
    $('#global_sc').val()
        ).draw();
</code>```

Title: Slow performance with tabbed datatables

Body:
I have a web page with 5 data tables in separate tabs. The filter at the top of the page contains a test element which is populated with a code. For each character typed, 5 separate AJAX calls are made to update each tab.
This has resulted in extremely poor performance, for the remote users experiencing wait times of over 3 minutes, effectively making the page useless.

I'm having a hard time to determine which tab is selected and update only the selected tab at a time. I have some bad code I've been trying to get to work, commented in the second code block. Unable to get the tab, to perform the draw, and replace that block of code.  Any guidance appreciated.

These are the tabs:

Tab1 Data

tab2 Data

Tab3 Data

Tab4 Data

Tab5 Data (Legacy)

My current code, has all 5 tabs as show, and walks through each tab

function filterShortCode () {
    // var tabIndex = &(this).find("a").attr("href");
    // $(tabIndex).DataTable().search(
    $('#gridTab1').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab2').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab3').DataTable().search(
      $('#global_sc').val()
        ).draw();
    $('#gridTab4').DataTable().search(
      $('#global_sc').val()
       ).draw();
    $('#gridTab5').DataTable().search(
      $('#global_sc').val()
       ).draw();
    };

Body:
If I understood you correctly...

var activeNavItem = $("#Status li.active");
var activeGrid = $("#Status li").index(activeNavItem)) + 1;

$('#gridTab' + activeGrid).DataTable().search(
    $('#global_sc').val()
        ).draw();