问:
Header with three elements, one left, one center, one right
I'm just starting to develop in HTML and CSS, and despite reading about the box model I am still having trouble with some of the basics of positioning.

I want to create a header navigation bar with three elements - one to the left of the page, one to the right, and one in the center. I want these elements to be inline with each other.

At the moment, they are represented in HTML like so

```<code><body>
<div class="header">
    <ul class="child">
        <li id="lodestone"><a href="">The Lodestone</a></li>
        <li id="mogstation"><a href="">The Mog Station</a></li>
        <li id="user"><a href="">User Account</a></li>
    </ul>
</div>
</code>```

I have then attempted to align them using the 'text-align' property in CSS.

```<code>.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
}

.header > ul > li {
    display: inline-block;
}

#lodestone {
    text-align: left;
}

#user {
    text-align: right;
}

#mogstation {
    text-align: center;
}
</code>```

However, instead of the expected result it produces this.
The three items are aligned, next to each other, on the left.

Can anyone recommend what css property I should be using to solve this problem? My research has shown there are ways of using float, but other people recommend against it, and when I try I get issues with the text overflowing off the page.

答:
Why not make the li elements a third of the width?

First make the ul 100% width, you'll also need to ensure there's no padding on the right of the ul as it tends to be automatically added by browsers:

```<code>.header ul {
    display: inline-block;
    padding: 0;
    width: 100%;
}
</code>```

Then have each li 33%

```<code>.header > ul > li {
    display: inline-block;
    width: 33%;
}
</code>```

Style the rest as required

Body:
I'm just starting to develop in HTML and CSS, and despite reading about the box model I am still having trouble with some of the basics of positioning.

I want to create a header navigation bar with three elements - one to the left of the page, one to the right, and one in the center. I want these elements to be inline with each other.

At the moment, they are represented in HTML like so

The Lodestone

The Mog Station

User Account

I have then attempted to align them using the 'text-align' property in CSS.

.header {
    background-color: #ffd9e7;
    border: black;
    display: block;
    box-sizing: border-box;
}

.header ul {
    display: inline-block;
}

.header > ul > li {
    display: inline-block;
}

#lodestone {
    text-align: left;
}

#user {
    text-align: right;
}

#mogstation {
    text-align: center;
}

However, instead of the expected result it produces this.
The three items are aligned, next to each other, on the left.

Can anyone recommend what css property I should be using to solve this problem? My research has shown there are ways of using float, but other people recommend against it, and when I try I get issues with the text overflowing off the page.

Body:
Why not make the li elements a third of the width?

First make the ul 100% width, you'll also need to ensure there's no padding on the right of the ul as it tends to be automatically added by browsers:

.header ul {
    display: inline-block;
    padding: 0;
    width: 100%;
}

Then have each li 33%

.header > ul > li {
    display: inline-block;
    width: 33%;
}

Style the rest as required


来源: stackexchange

问:
Need help moving nUnit tests into separate project
Everything works fine when the unit tests class is part of the main project (TestAccount).

Every article I've read about unit testing recommends putting the tests in a separate project, so I...

added another project
(TestAccount.UnitTests) to the solution

moved the unit tests class (AccountTests.vb) to TestAccount.UnitTests

and added a reference in TestAccount.UnitTests to TestAccount (copy local = true)

The solution compiles without any warnings. However, nUnit can't access the main project and gives the following error for each test:

System.IO.FileNotFoundException : Could not load file or assembly 'TestAccount, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

What am I doing wrong?

(I was having similar trouble with nunit.framework.dll until I added it to the GAC)

screenshot of Solution Explorer http://img440.imageshack.us/img440/4862/nunitsolutionexploreree3.jpg

Visual Studio 2005

.NET 2.0

nUnit 2.4.8 (.NET 2.0 version)

[Edit] I only have this problem when running nUnit from Visual Studio (as external command). If I load the nUnit console independently, it works fine.

[Edit] Omar: yes, I have the reference to the other project. Here is a screenshot of my solution explorer

I think I might just have to run the nUnit console separately (instead of through VS's External Tools).

答: Also make sure your assembly output path corresponds to what is set up in your NUnit configuration. I have the same setup but I don't have to set 'copy local = true'</p>

OwnerDisplayName: David J

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David J

OwnerDisplayName: TT


问:
creating a dynamic field and getting the value
i posted another question about this, but i think this one will be more concise.

i've dynamically created a text field with javascript.  i've checked to see that it's in the DOM by getting its value, but when trying to access it from another function i get a value of null for the input object.  is it actually possible to get the current value from a dynamically created text field?

inside one function:

```
comment_field = 'comment-HE382U3-2';
document.getElementById(comment_field).value = 'Write a comment...';
```

inside the other:

```
comment_field = 'comment-HE382U3-2';
if (document.getElementById(comment_field).value == 'Write a comment...')
    { document.getElementById(comment_field).value = '';}
```

is not happening because there is no [HTMLInputObject] found in the DOM.  Please help.  Thanks!

答:
is it actually possible to get the current value from a dynamically created text field?

Yes. It is just like any other element. If it is in the DOM, it is accessed the same way.

Verify the value of the comment_field variable. You're making reference to different functions, so perhaps that variable is out of scope.

Body:
i posted another question about this, but i think this one will be more concise.

i've dynamically created a text field with javascript.  i've checked to see that it's in the DOM by getting its value, but when trying to access it from another function i get a value of null for the input object.  is it actually possible to get the current value from a dynamically created text field?

inside one function:

comment_field = 'comment-HE382U3-2';
document.getElementById(comment_field).value = 'Write a comment...';

inside the other:

comment_field = 'comment-HE382U3-2';
if (document.getElementById(comment_field).value == 'Write a comment...')
    { document.getElementById(comment_field).value = '';}

is not happening because there is no [HTMLInputObject] found in the DOM.  Please help.  Thanks!


答:
Take a look at CSS Flexbox for a different approach to layout your elements

header{
    display: flex;
    justify-content: space-around;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</header></code>```

ContentLicense: CC BY-SA 3.0

Title: Header with three elements, one left, one center, one right

Body:
Take a look at CSS Flexbox for a different approach to layout your elements

header{
    display: flex;
    justify-content: space-around;
}

<header>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</header>


问:
WebInvoke POST request only works if I write the url manually
```<code>public async Task<string> insert(string x, string y, string z)
{
    using (var client = new HttpClient())
    {
        var payload = new rootnode { username = x, userpassword = y, usermobile = z };
        var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
        var entry = new StringContent(stringPayload, Encoding.UTF8, "application/json");

        System.Diagnostics.Debug.WriteLine(entry);
        var result = await client.PostAsync("http://localhost:20968/Service1.svc/insert/", entry);
        return await result.Content.ReadAsStringAsync();
    }
}
</code>```

My function is working very well only if I write the url manually with entry=""

```<code>client.PostAsync("http://localhost:20968/Service1.svc/insert/x,y,z", "entry");
</code>```

Here is my webget method also

```<code>[WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json,UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]
</code>```

答:
Given the stated uri template in the OP you are constructing the request wrong. It was already indicated that it worked when the uri was manually constructed. repeat the same construction when sending the request.

Not enough details was provided about the target web method so the following example assumes that with something like...

```<code>[ServiceContract]
public interface IService {
    [OperationContract]
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]
    InsertResponse Insert(string username, string userpassword, string usermobile);
}
</code>```

Calling the service could look like this by constructing the request manually

```<code>public async Task<string> insert(string x, string y, string z) {
    using (var client = new HttpClient()) {
        client.BaseAddress = new Uri("http://localhost:20968/Service1.svc/");

        //UriTemplate = "insert/{username}/{userpassword}/{usermobile}"
        var url = string.Format("insert/{0}/{1}/{2}", x, y, z);
        System.Diagnostics.Debug.WriteLine(url);

        var request = new HttpRequestMessage(HttpMethod.Post, url);
        System.Diagnostics.Debug.WriteLine(request);

        var result = await client.SendAsync(request);
        return await result.Content.ReadAsStringAsync();
    }
}
</code>```

Body:
public async Task<string> insert(string x, string y, string z)
{
    using (var client = new HttpClient())
    {
        var payload = new rootnode { username = x, userpassword = y, usermobile = z };
        var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
        var entry = new StringContent(stringPayload, Encoding.UTF8, "application/json");

        System.Diagnostics.Debug.WriteLine(entry);
        var result = await client.PostAsync("http://localhost:20968/Service1.svc/insert/", entry);
        return await result.Content.ReadAsStringAsync();
    }
}

My function is working very well only if I write the url manually with entry=""

client.PostAsync("http://localhost:20968/Service1.svc/insert/x,y,z", "entry");

Here is my webget method also

[WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json,UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]

Body:
Given the stated uri template in the OP you are constructing the request wrong. It was already indicated that it worked when the uri was manually constructed. repeat the same construction when sending the request.

Not enough details was provided about the target web method so the following example assumes that with something like...

[ServiceContract]
public interface IService {
    [OperationContract]
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]
    InsertResponse Insert(string username, string userpassword, string usermobile);
}

Calling the service could look like this by constructing the request manually

public async Task<string> insert(string x, string y, string z) {
    using (var client = new HttpClient()) {
        client.BaseAddress = new Uri("http://localhost:20968/Service1.svc/");

        //UriTemplate = "insert/{username}/{userpassword}/{usermobile}"
        var url = string.Format("insert/{0}/{1}/{2}", x, y, z);
        System.Diagnostics.Debug.WriteLine(url);

        var request = new HttpRequestMessage(HttpMethod.Post, url);
        System.Diagnostics.Debug.WriteLine(request);

        var result = await client.SendAsync(request);
        return await result.Content.ReadAsStringAsync();
    }
}


问:
How to use gulp in laravel on ubuntu 16.04
I have problem with gulp in my project. I installed node, npm, gulp and I created file gulpfile.js.

If I use command gulp never nothing happens.

I don't know what is incorrect.

Please help me.

My code for example:

```<code>var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  '/bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            '/bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            '/bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            '/bower_components/AdminLTE/plugins/morris/morris.css',
            '/bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css']
};

gulp.task('css', function() {
   return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/'));
});

gulp.task('default', ['css']);
</code>```

答:
Try this:</p>

```<code>var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  'bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            'bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            'bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            'bower_components/AdminLTE/plugins/morris/morris.css',
            'bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css'] };

gulp.task('css', function() {    return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/')); });

gulp.task('default', ['css']);
</code>```

Body:
I have problem with gulp in my project. I installed node, npm, gulp and I created file gulpfile.js.

If I use command gulp never nothing happens.

I don't know what is incorrect.

Please help me.

My code for example:

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  '/bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            '/bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            '/bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            '/bower_components/AdminLTE/plugins/morris/morris.css',
            '/bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css']
};

gulp.task('css', function() {
   return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/'));
});

gulp.task('default', ['css']);

Body:
Try this:

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  'bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            'bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            'bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            'bower_components/AdminLTE/plugins/morris/morris.css',
            'bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css'] };

gulp.task('css', function() {    return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/')); });

gulp.task('default', ['css']);


问:
Strategy for reading and writing to threaded data structure
I have a class that contains an NSDictionary and periodically, I have a thread writing data into this NSDictionary. Then at other times, I have another view controller reading data out of the class's NSDictionary.

What's the best objective-c way to make the data in this class thread-safe so that if you were to ask data for 'read', you're getting the correct version aka, the last written version and not the one that maybe getting written to currently?

答:
As Carl mentioned, @synchronized is one option.

If you are targeting iOS 4.0+, another one is using a Grand Central Dispatch queue to regulate access to a shared data structure from multiple threads/queues. The WWDC 2010 Session 211 video has a good explanation of this technique.

In a nutshell: you create a custom GCD queue (dispatch_queue_create()) whose single responsibility is to regulate access to the shared data structure. All code that accesses the shared structure then must do so from inside this queue. Because queues only execute one block of code at a time, no two threads can access the data structure at the same time.


问:
Static method that returns the current class' name regardless of inheritance
My problem is that MethodBase.GetCurrentMethod().DeclaringType.Name only works if called on an instance of a class. If called from a static function, it returns the topmost parent class' name regardless of how many times it has been sub-classed.

For example

```<code>public class ReflectionObject {

    public static string Name() {
        return MethodBase.GetCurrentMethod().DeclaringType.Name;
    }
}
public class DerivedObject : ReflectionObject {
}
</code>```

Calling DerivedObject.Name() returns ReflectionObject and not DerivedObject like I need it to. Any ideas?

答:
It's not possible as the static method is bound to the class you're declaring it in. You can't mark it virtual or override it either.

If you want the name, you could treat the base static method as a helper function and pass in the name from the deriving class.

Body:
My problem is that MethodBase.GetCurrentMethod().DeclaringType.Name only works if called on an instance of a class. If called from a static function, it returns the topmost parent class' name regardless of how many times it has been sub-classed.

For example

public class ReflectionObject {

    public static string Name() {
        return MethodBase.GetCurrentMethod().DeclaringType.Name;
    }
}
public class DerivedObject : ReflectionObject {
}

Calling DerivedObject.Name() returns ReflectionObject and not DerivedObject like I need it to. Any ideas?


问:
Java for loop not incrementing
```<code>BufferedReader inputStream = null;
    String fileLine;
    int employeeCount = 1;
    String[] years = new String[2];
    //Employee[] employees = new Employee[employeeCount + 1];
    List<Employee> employees = new ArrayList<>();
    File myFile = new File("src/project1/data.txt");
    //System.out.println("Attempting to read from file in: "+ myFile.getCanonicalPath());
    try {
        FileInputStream fstream = new FileInputStream(myFile);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null)   {
            String[] data = strLine.split(" ");
            //while ( int i < employees.length ) {
            for (int i=1; i < employees.size(); i++ ) {
                if (data[1].equals("Executive")) {
                    employees.add( new Executive(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
                } else if (data[1].equals("Salesman")) {
                    employees.add( new Salesman(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
                } else {
                    employees.add( new Employee(data[0],data[1],data[2], Integer.parseInt(data[3])) );
                }
                //System.out.println(employees[i].toString());
                System.out.println(i +" " + employeeCount);
                employeeCount++;
            }
        }
        for (int y=1; y < employees.size(); y++ ) {
            System.out.println(employees.get(y).getName());
        }
        //System.out.println(employees.toString());
    } catch (IOException io) {
        System.out.println("File IO exception" + io.getMessage());
    }
</code>```

EmployeeCount is incrementing as expected, but i is always 1 - what am I missing here? textfile is read in line by line using a while loop - for loop checks if second piece of data matches a string and creates object base on match. Am I making sense here?

答:
The for loop is not incrementing because the condition is false after the first iteration at:

```<code>for (int i=1; i < employees.length; i++ ) {
</code>```

that is, employees.length is 2 since employeeCount was one at this line (I must assume that since the code is incomplete):

```<code>Employee[] employees = new Employee[employeeCount + 1];
</code>```

This line creates an array with two positions since employeeCount + 1 was 2. The size is not automatically adjusted as employeeCount is incremented...

I suggest using a List instead of an array, since the List is expanded as needed:

```<code>List<Employee> employees = new ArrayList<>();
...
employees.add(new Employee(...));
</code>```

Title: Java for loop not incrementing

Body:
BufferedReader inputStream = null;
    String fileLine;
    int employeeCount = 1;
    String[] years = new String[2];
    //Employee[] employees = new Employee[employeeCount + 1];
    List<Employee> employees = new ArrayList<>();
    File myFile = new File("src/project1/data.txt");
    //System.out.println("Attempting to read from file in: "+ myFile.getCanonicalPath());
    try {
        FileInputStream fstream = new FileInputStream(myFile);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null)   {
            String[] data = strLine.split(" ");
            //while ( int i < employees.length ) {
            for (int i=1; i < employees.size(); i++ ) {
                if (data[1].equals("Executive")) {
                    employees.add( new Executive(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
                } else if (data[1].equals("Salesman")) {
                    employees.add( new Salesman(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
                } else {
                    employees.add( new Employee(data[0],data[1],data[2], Integer.parseInt(data[3])) );
                }
                //System.out.println(employees[i].toString());
                System.out.println(i +" " + employeeCount);
                employeeCount++;
            }
        }
        for (int y=1; y < employees.size(); y++ ) {
            System.out.println(employees.get(y).getName());
        }
        //System.out.println(employees.toString());
    } catch (IOException io) {
        System.out.println("File IO exception" + io.getMessage());
    }

EmployeeCount is incrementing as expected, but i is always 1 - what am I missing here? textfile is read in line by line using a while loop - for loop checks if second piece of data matches a string and creates object base on match. Am I making sense here?

Body:
The for loop is not incrementing because the condition is false after the first iteration at:

for (int i=1; i < employees.length; i++ ) {

that is, employees.length is 2 since employeeCount was one at this line (I must assume that since the code is incomplete):

Employee[] employees = new Employee[employeeCount + 1];

This line creates an array with two positions since employeeCount + 1 was 2. The size is not automatically adjusted as employeeCount is incremented...

I suggest using a List instead of an array, since the List is expanded as needed:

List<Employee> employees = new ArrayList<>();
...
employees.add(new Employee(...));


问:
In SQL I want to display the names of all those cities which end with an vowel
I wrote the following query

```<code>SELECT UNIQUE
    CITY
FROM
    STATION
WHERE
    (CITY LIKE '%A' OR
     CITY LIKE '%E' OR
     CITY LIKE '%I' OR
     CITY LIKE '%O' OR
     CITY LIKE '%U')
ORDER BY
    CITY;
</code>```

What is wrong with this?

答:
In MySql</p>

```<code>    select distinct city
    from Station
    where ( city regexp '.[aeiou]$' );
</code>```

Body:
I wrote the following query

SELECT UNIQUE
    CITY
FROM
    STATION
WHERE
    (CITY LIKE '%A' OR
     CITY LIKE '%E' OR
     CITY LIKE '%I' OR
     CITY LIKE '%O' OR
     CITY LIKE '%U')
ORDER BY
    CITY;

What is wrong with this?

Body:
In MySql

    select distinct city
    from Station
    where ( city regexp '.[aeiou]$' );


Title: Finding number of clicks per unit of time

Body:
  Ad-Slot Id   Click Time                    Click IP
0   208878    2017-03-23 18:30:00.059   2405:204:c:3868:f27d:db2c:e2a9:c90c
1   195915  2017-03-23 18:30:00.107   2405:204:4183:6939:d3c2:bf40:ed47:3a6d
2   129192  2017-03-23 18:30:00.309   2405:204:900a:5700:cd84:2eec:449e:6af6
3   195987  2017-03-23 18:30:00.311   27.62.33.203
4   209078  2017-03-23 18:30:00.523   182.65.23.82
5   206706  2017-03-23 18:30:00.637   2405:205:1308:f499:b1d1:931a:2266:a738
6   210917  2017-03-23 18:30:01.136   42.106.17.94
7   236944  2017-03-23 18:30:01.226   171.61.19.146
8   195980  2017-03-23 18:30:01.331   2405:204:4088:1b4d::17ac:38ac

I have above data snippet and need to find out number of clicks per unit of time (1 minute, 5 minute, 1 hr) for each publisher (Ad-Slot Id).

Body:
Note: I modified your data snippet to have some multiple Ad-slot Id's per second, just for testing. So my output will be different from yours.

data snippet:

 Ad-Slot_Id   Click Time                    Click_IP
0   208878    2017-03-23 18:30:00.059   2405:204:c:3868:f27d:db2c:e2a9:c90c
1   236944  2017-03-23 18:30:00.107   2405:204:4183:6939:d3c2:bf40:ed47:3a6d
2   129192  2017-03-23 18:30:00.309   2405:204:900a:5700:cd84:2eec:449e:6af6
3   129192  2017-03-23 18:30:00.311   27.62.33.203
4   236944  2017-03-23 18:30:00.523   182.65.23.82
5   206706  2017-03-23 18:30:00.637   2405:205:1308:f499:b1d1:931a:2266:a738
6   129192  2017-03-23 18:30:01.136   42.106.17.94
7   236944  2017-03-23 18:30:01.226   171.61.19.146
8   129192  2017-03-23 18:30:01.331   2405:204:4088:1b4d::17ac:38ac

I am grouping the DataFrame by Ad-Slot Id, then resampling per second/minute/whatever you want, and counting the number of objects:

df = pd.read_clipboard()
df.index = pd.to_datetime(df['Click'] + ' ' + df['Time'])
resampletime = 's'
for theid, thedf in df.groupby(by=['Ad-Slot_Id'], axis=0):
    print theid
    print thedf.resample(resampletime, how='count')['Ad-Slot_Id']

This should help you get on your way.


问:
Thymeleaf + Spring Boot: placing html in subfolders
By default, Thymeleaf needs all the html files to be present in scr/main/java/resources/templates. In order not to create a mess in templates folder I need to create different subloders there. The problem is that html files placed there never get resolved. Example is below.

Structure:

IndexController:

```<code>@Controller
public class IndexController {
    @GetMapping(value = "/")
    public String index() {
        return "index";
    }
}
</code>```

default template:

```<code><!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8"/>
    <title>Default template</title>
</head>
<body>

<section id="site-content" layout:fragment="content"></section>

</body>
</html>
</code>```

index:

```<code><!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="default">
<head>
    <meta charset="UTF-8"/>
    <title>Index</title>
</head>
<body>

<div layout:fragment="content">
    <div>
        This is index page
    </div>

    <a href="subfolder/page.html">Page</a>
</div>

</body>
</html>
</code>```

page in the subfolder:

```<code><!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="default">
<head>
    <meta charset="UTF-8">
    <title>Page</title>
</head>
<body>

<div layout:fragment="content">
    This is a page in the subfolder
</div>

</body>
</html>
</code>```

When I open index page and click the link to the page.html, I get this:

What I did wrong?

答:
You have no controller mapping for /subfolder/page.html, this is not how Thymeleaf and Spring work.

You can't easily reference plain HTML files, as they aren't technically stored there. You have to reference an endpoint defined within Spring which will then select the HTML file to be rendered, like so:

```<code>@Controller
public class IndexController {
    @GetMapping(value = "/subfolder/page")
    public String index() {
        return "subfolder/page";
    }
}
</code>```

and create your link like this:

```<code><a href="subfolder/page">Page</a>
</code>```

Body:
By default, Thymeleaf needs all the html files to be present in scr/main/java/resources/templates. In order not to create a mess in templates folder I need to create different subloders there. The problem is that html files placed there never get resolved. Example is below.

Structure:

IndexController:

@Controller
public class IndexController {
    @GetMapping(value = "/")
    public String index() {
        return "index";
    }
}

default template:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Default template</title>

index:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Index</title>

        This is index page

    Page

page in the subfolder:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Page</title>

    This is a page in the subfolder

When I open index page and click the link to the page.html, I get this:

What I did wrong?

Body:
You have no controller mapping for /subfolder/page.html, this is not how Thymeleaf and Spring work.

You can't easily reference plain HTML files, as they aren't technically stored there. You have to reference an endpoint defined within Spring which will then select the HTML file to be rendered, like so:

@Controller
public class IndexController {
    @GetMapping(value = "/subfolder/page")
    public String index() {
        return "subfolder/page";
    }
}

and create your link like this:

<a href="subfolder/page">Page</a>


问:
I wanted to add an element to my array after sorting the array
Here is my code</p>

```<code>import java.util.*;

public class ArrayExample {
    public static void main(String[] args) {
        Integer arr[] = {5,4,3,2,15,8,9};
        List<Integer> list = Arrays.asList(arr);
        Collections.sort(list);
        System.out.println(list);
        list.add(6);// here I am adding 6 to my array.
        System.out.println(list);
        // Here I should get output as [2,3,4,5,6,8,9,15]
    }
}
</code>```

答:
No you cannot add, as you are using Arrays.asList(arr);

```<code> List<Integer> list = Arrays.asList(arr);
</code>```

asList returning a fixed-size list, you cannot add any element in that, once the list is formed.
You may get java.lang.UnsupportedOperationException

```<code>[2, 3, 4, 5, 8, 9, 15]
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at Test.main(Test.java:14)
</code>```

Body:
Here is my code

import java.util.*;

public class ArrayExample {
    public static void main(String[] args) {
        Integer arr[] = {5,4,3,2,15,8,9};
        List<Integer> list = Arrays.asList(arr);
        Collections.sort(list);
        System.out.println(list);
        list.add(6);// here I am adding 6 to my array.
        System.out.println(list);
        // Here I should get output as [2,3,4,5,6,8,9,15]
    }
}

Body:
No you cannot add, as you are using Arrays.asList(arr);

 List<Integer> list = Arrays.asList(arr);

asList returning a fixed-size list, you cannot add any element in that, once the list is formed.
You may get java.lang.UnsupportedOperationException

[2, 3, 4, 5, 8, 9, 15]
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at Test.main(Test.java:14)


问:
JQuery datepicker- 2 inputs From and To
I am using the Jquery datepicker plugin  with this timepicker addon in two input boxes, one for the "From" date and the second with the "To" date.

When I set the first one, I want the second one to be one day after the date selected in the first,disabling all the dates earlier than the date selected in the "From" date

If the "To" date is selected first, then the "From" date is set to the day before the "To" date.

I have found some examples, but I don't know how to get the date with time.So,If I  ,for example, select 13/12/2010 15:50 in the "From" date, the date in the "To" date is set to 14/12/2010 15:50 or at least to 14/12/2010 00:00.

 EDITED***

I've just found this piece of code that works as I want , but without the timepicker addon.

```<code> $(function(){

  $('#dateFrom').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateTo').datepicker('option','minDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
          }
  });
  $('#dateTo').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateFrom').datepicker('option','maxDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
    }
  });

});
</code>```

Based on the above code, would it be possible to adapt it ,so that I can use it with the timepicker addon?

Thanks beforehand

答: Try to use onSelect or onClose event to change minDate and maxDate options.</p>

Title: JQuery datepicker- 2 inputs From and To

Body:
I am using the Jquery datepicker plugin  with this timepicker addon in two input boxes, one for the "From" date and the second with the "To" date.

When I set the first one, I want the second one to be one day after the date selected in the first,disabling all the dates earlier than the date selected in the "From" date

If the "To" date is selected first, then the "From" date is set to the day before the "To" date.

I have found some examples, but I don't know how to get the date with time.So,If I  ,for example, select 13/12/2010 15:50 in the "From" date, the date in the "To" date is set to 14/12/2010 15:50 or at least to 14/12/2010 00:00.

 EDITED***

I've just found this piece of code that works as I want , but without the timepicker addon.

 $(function(){

  $('#dateFrom').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateTo').datepicker('option','minDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
          }
  });
  $('#dateTo').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateFrom').datepicker('option','maxDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
    }
  });

});

Based on the above code, would it be possible to adapt it ,so that I can use it with the timepicker addon?

Thanks beforehand


问:
Setting file permissions in batch
I'm outputting the following error that's generated when executing a batch of file permission changes to a file. I'm not sure what to make of this, since it's only a problem for some of the files, and the issue doesn't trigger when trying to run in debug mode:

```<code>500 >> Internal Error. User message: "An internal error has occurred which prevented the sharing of these item(s): Example File.DOCX"
</code>```

I'm using the following code:

```<code>var batch = new Google.Apis.Requests.BatchRequest(service);

Google.Apis.Requests.BatchRequest.OnResponse<Permission> callback = delegate (
            Permission permission,
            Google.Apis.Requests.RequestError error,
            int index,
            System.Net.Http.HttpResponseMessage message) {
                if (error != null) {
                    // Handle error
                    Console.WriteLine("File PERMISSION Error: " + error.Code + " >> " + error.Message);
                } else {
                    Console.WriteLine("File Permission ID: " + permission.Id);
                }
            };

Permission filePermission = new Permission()
{
    EmailAddress = "test-email@gmail.com"
    , Type = GoogleDriveRoleType
    , Role = GoogleDriveRole
};

var permExec = service.Permissions.Create(filePermission, googleDriveObjectId);
permExec.SendNotificationEmail = false;
permExec.Fields = "id";
batch.Queue(permExec, callback);

await batch.ExecuteAsync();
</code>```

This code is within a method that's public static async Task MyMethod(...).

答: You may want to make your batch request smaller. You might be experiencing 500 internal error because you are flooding the server with too many request per second. As stated in this related SO post, as the server handles your batch request, it is not smart enough to slow down to avoid the error 500. You can also use exponential backoff and then retry the batch request. As stated in this forum, currently there is no way to know in a batch request what part fail or succeed. You have to create your own implementation regarding this. Hope this helps.</p>

Title: Setting file permissions in batch

Body:
I'm outputting the following error that's generated when executing a batch of file permission changes to a file. I'm not sure what to make of this, since it's only a problem for some of the files, and the issue doesn't trigger when trying to run in debug mode:

500 >> Internal Error. User message: "An internal error has occurred which prevented the sharing of these item(s): Example File.DOCX"

I'm using the following code:

var batch = new Google.Apis.Requests.BatchRequest(service);

Google.Apis.Requests.BatchRequest.OnResponse<Permission> callback = delegate (
            Permission permission,
            Google.Apis.Requests.RequestError error,
            int index,
            System.Net.Http.HttpResponseMessage message) {
                if (error != null) {
                    // Handle error
                    Console.WriteLine("File PERMISSION Error: " + error.Code + " >> " + error.Message);
                } else {
                    Console.WriteLine("File Permission ID: " + permission.Id);
                }
            };

Permission filePermission = new Permission()
{
    EmailAddress = "test-email@gmail.com"
    , Type = GoogleDriveRoleType
    , Role = GoogleDriveRole
};

var permExec = service.Permissions.Create(filePermission, googleDriveObjectId);
permExec.SendNotificationEmail = false;
permExec.Fields = "id";
batch.Queue(permExec, callback);

await batch.ExecuteAsync();

This code is within a method that's public static async Task MyMethod(...).


问:
Custom keyboard shortcuts for Google Docs (change color - background color)
I would like to change the ForegroundColor of a selected text in a Google Docs with a keyboard shortcut.

I could make the "change the ForegroundColor" part (with a menu item bound to the function setColor() ), but not the "keyboard shortcut part".

I found this code but I have trouble implementing it:

```<code>$(document).keydown(function(e){
  //CTRL + Q keydown combo
  if(e.ctrlKey && e.keyCode == 81){
    $( '#output' ).html("I've been pressed!");
  }
})
</code>```

My difficulties :

1) I am not sure where to place this code in my script editor (I tried to place it in the onOpen() function as below, but also above it without success).

2) I am not sure what the $(document) should refer to.

3) I am not sure what they mean by "having to click on / activate the sidebar first for that to happen".

```<code>function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Color', 'setColor')
      .addToUi();

  var document = DocumentApp.getActiveDocument() // should it be here?
  $(document).keydown(function(e){
    //CTRL + Q keydown combo
    if(e.ctrlKey && e.keyCode == 81){
      SpreadsheetApp.getUi().alert('Hello, world!');
    }
  })
}

function setColor1() {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        // Only modify elements that can be edited as text; skip images and other non-text elements.
        if (element.getElement().editAsText) {
            var text = element.getElement().editAsText();

            // Edit the selected part of the element, or the full element if it's completely selected.
            if (element.isPartial()) {
                text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#00FFFF");
            } else {
                text.setForegroundColor("#00FFFF");
            }
        }
    }
    }
}
</code>```

答:
In this line, the variable 'document' is an instance of the 'Document' object as defined in Google Apps Script documentation.

```<code>var document = DocumentApp.getActiveDocument()
</code>```

It's an abstraction over the Google Document sitting in your Drive that allows you to modify your Drive files using a set of methods described here https://developers.google.com/apps-script/reference/document/document

The line below is jQuery syntax.

```<code>$(document).keydown(function(e){}
</code>```

jQuery is a JavaScript library for client-side development. It is used for navigating the HTML DOM tree of a webpage. $(document) is jQuery's representation of the DOM. More on jQuery http://jquery.com/

Because Google Apps Script runs on Google servers, not locally on your machine, there's no DOM tree for you to navigate. You are limited to GAS functions that are mapped to bits of code on Google servers. These two lines of code have nothing to do with each other and are not referring to the same document.

Same applies to events that you can listen to. While GAS does have some event handling capabilities, the list of events is quite short (see 'Simple Triggers' and Installable Triggers') https://developers.google.com/apps-script/guides/triggers/

UPDATE

You can achieve this by building your own custom UI using HtmlService. The caveat is that there seems to be no way to hand over control from Google Document to the UI element, so you'll have to manually set focus on the sidebar after each action.

Here's the example of how the .gs file in your project may look like. Treat this as your server app.

```<code>//creates html output from the template
function onOpen(){

var ui = DocumentApp.getUi();
var htmlOutput = HtmlService.createTemplateFromFile('sidebar').evaluate();
ui.showSidebar(htmlOutput);

}

function setColor1(){

  //your code

}
</code>```

Below is my client-side code for the sidebar template. You create the template in your Script Editor by clicking on File -> New -> Html file.
Call it sidebar or whatever you choose for the var htmlOutput in the .gsfile above. If you press 'Ctrl + Q', the sidebar will display a confirmation and call the setColor1() function in your .gs file.

More on calling server-side GAS functions from the client https://developers.google.com/apps-script/guides/html/reference/run

More on HtmlService
https://developers.google.com/apps-script/guides/html/

The obvious downside is that the sidebar must acquire focus first, so you always need to click on it after making a selection.

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

    <p> Press Ctrl + Q to change the color of selected text </p>
    <p id="log"> </p>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>

    $(document).ready(function(){

      $(document).keydown(function(e){

      if(e.ctrlKey && e.keyCode == 81){

           $('#log').html('you pressed Ctrl + Q');

           google.script.run.setColor1();

      }

      });

    });

    </script>

  </body>
</html>
</code>```

Hope this helps!

Body:
I would like to change the ForegroundColor of a selected text in a Google Docs with a keyboard shortcut.

I could make the "change the ForegroundColor" part (with a menu item bound to the function setColor() ), but not the "keyboard shortcut part".

I found this code but I have trouble implementing it:

$(document).keydown(function(e){
  //CTRL + Q keydown combo
  if(e.ctrlKey && e.keyCode == 81){
    $( '#output' ).html("I've been pressed!");
  }
})

My difficulties :

1) I am not sure where to place this code in my script editor (I tried to place it in the onOpen() function as below, but also above it without success).

2) I am not sure what the $(document) should refer to.

3) I am not sure what they mean by "having to click on / activate the sidebar first for that to happen".

function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Color', 'setColor')
      .addToUi();

  var document = DocumentApp.getActiveDocument() // should it be here?
  $(document).keydown(function(e){
    //CTRL + Q keydown combo
    if(e.ctrlKey && e.keyCode == 81){
      SpreadsheetApp.getUi().alert('Hello, world!');
    }
  })
}

function setColor1() {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        // Only modify elements that can be edited as text; skip images and other non-text elements.
        if (element.getElement().editAsText) {
            var text = element.getElement().editAsText();

            // Edit the selected part of the element, or the full element if it's completely selected.
            if (element.isPartial()) {
                text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#00FFFF");
            } else {
                text.setForegroundColor("#00FFFF");
            }
        }
    }
    }
}

Body:
In this line, the variable 'document' is an instance of the 'Document' object as defined in Google Apps Script documentation.

var document = DocumentApp.getActiveDocument()

It's an abstraction over the Google Document sitting in your Drive that allows you to modify your Drive files using a set of methods described here https://developers.google.com/apps-script/reference/document/document

The line below is jQuery syntax.

$(document).keydown(function(e){}

jQuery is a JavaScript library for client-side development. It is used for navigating the HTML DOM tree of a webpage. $(document) is jQuery's representation of the DOM. More on jQuery http://jquery.com/

Because Google Apps Script runs on Google servers, not locally on your machine, there's no DOM tree for you to navigate. You are limited to GAS functions that are mapped to bits of code on Google servers. These two lines of code have nothing to do with each other and are not referring to the same document.

Same applies to events that you can listen to. While GAS does have some event handling capabilities, the list of events is quite short (see 'Simple Triggers' and Installable Triggers') https://developers.google.com/apps-script/guides/triggers/

UPDATE

You can achieve this by building your own custom UI using HtmlService. The caveat is that there seems to be no way to hand over control from Google Document to the UI element, so you'll have to manually set focus on the sidebar after each action.

Here's the example of how the .gs file in your project may look like. Treat this as your server app.

//creates html output from the template
function onOpen(){

var ui = DocumentApp.getUi();
var htmlOutput = HtmlService.createTemplateFromFile('sidebar').evaluate();
ui.showSidebar(htmlOutput);

}

function setColor1(){

  //your code

}

Below is my client-side code for the sidebar template. You create the template in your Script Editor by clicking on File -> New -> Html file.
Call it sidebar or whatever you choose for the var htmlOutput in the .gsfile above. If you press 'Ctrl + Q', the sidebar will display a confirmation and call the setColor1() function in your .gs file.

More on calling server-side GAS functions from the client https://developers.google.com/apps-script/guides/html/reference/run

More on HtmlService
https://developers.google.com/apps-script/guides/html/

The obvious downside is that the sidebar must acquire focus first, so you always need to click on it after making a selection.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

    <p> Press Ctrl + Q to change the color of selected text </p>
    <p id="log"> </p>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>

    $(document).ready(function(){

      $(document).keydown(function(e){

      if(e.ctrlKey && e.keyCode == 81){

           $('#log').html('you pressed Ctrl + Q');

           google.script.run.setColor1();

      }

      });

    });

    </script>

  </body>
</html>

Hope this helps!


问:
Sorting list array of strings in C
```<code>#include <stdio.h>
#include <string.h>

void ascending_sort(char *name, char **pName, unsigned int size);

int main(){
   char * names[] = {"Ellin","Alexa","Eliza","Celiza", NULL};
ascending_sort(names[0],names,( sizeof(names)/sizeof(char *)) - 1);
return 0;
}

void ascending_sort(char *name, char **pName, unsigned int size){
    unsigned int i;
    unsigned int z;
    int keep;
    char temp;
    /// print out the array
    for (i = 0; i < size; i++)
    {
        printf("str: %s\n", pName[i]);
    }

    ///start sorting...
    for (i = 0; i < size; i++){
        keep = i;
        for(z = i; z < size; z++){
            if(pName[keep]>pName[z]){
               keep = z;
            }
        }
        temp = pName[i];
        pName[i] = pName[keep];
        pName[keep] = temp;

    }
    for (i = 0; i < size; i++){
        printf("str: %s\n", pName[i]);
    }
}
</code>```

I'm confused with double pointer(char**).
How can I print out each element of array in function with 'for' loop (so I can easily understand) and sorting it (using 'for' loop)?

help fix my sorting algorithm, it didnt work

答:
fixed 99.99%... !! </p>

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

    void sort_name(char **pName, char order[], unsigned int size);

int main()
{
    char *names[] = {"Ellin","Alexa","Eliza","4-C", NULL};

    printf("[1] ");
    sort_name(names, "asc", (sizeof(names)/sizeof(char *))-1);

    return 0;
}

void sort_name(char **pName, char order[], unsigned int size){

     unsigned int i;
     unsigned int z;

     ///print out
     printf("Original list:\n\t");
     for (i = 0; i < size; i++)
     {
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
     }

     ///start sorting...
     if (!strcmp(order,"asc")){
            printf("    Ascending sorted list:\n\t");
     for (i=0; i <size; i++){
         for(z=i+1; z<size; z++){
             if(strcmp(*(pName+i),*(pName+z))>0){
                char *temp = *(pName+i);
                *(pName+i) = *(pName+z);
                *(pName+z) = temp;
             }
         }
     }
     for (i = 0; i < size; i++){
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
         }
     }

     else if (!strcmp(order,"desc")){
            printf("    Descending sorted list:\n\t");
     for (i=0; i <size; i++){
         for(z=i+1; z<size; z++){
             if(strcmp(*(pName+i),*(pName+z))<0){
                char *temp = *(pName+i);
                *(pName+i) = *(pName+z);
                *(pName+z) = temp;
             }
         }

     }
     for (i = 0; i < size; i++){
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
         }
     }

     else{
        printf(" That doesnt even make sense!");
     }
}
</code>```

Title: Sorting list array of strings in C

Body:
#include <stdio.h>
#include <string.h>

void ascending_sort(char *name, char **pName, unsigned int size);

int main(){
   char * names[] = {"Ellin","Alexa","Eliza","Celiza", NULL};
ascending_sort(names[0],names,( sizeof(names)/sizeof(char *)) - 1);
return 0;
}

void ascending_sort(char *name, char **pName, unsigned int size){
    unsigned int i;
    unsigned int z;
    int keep;
    char temp;
    /// print out the array
    for (i = 0; i < size; i++)
    {
        printf("str: %s\n", pName[i]);
    }

    ///start sorting...
    for (i = 0; i < size; i++){
        keep = i;
        for(z = i; z < size; z++){
            if(pName[keep]>pName[z]){
               keep = z;
            }
        }
        temp = pName[i];
        pName[i] = pName[keep];
        pName[keep] = temp;

    }
    for (i = 0; i < size; i++){
        printf("str: %s\n", pName[i]);
    }
}

I'm confused with double pointer(char**).
How can I print out each element of array in function with 'for' loop (so I can easily understand) and sorting it (using 'for' loop)?

help fix my sorting algorithm, it didnt work

Body:
fixed 99.99%... !!

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

    void sort_name(char **pName, char order[], unsigned int size);

int main()
{
    char *names[] = {"Ellin","Alexa","Eliza","4-C", NULL};

    printf("[1] ");
    sort_name(names, "asc", (sizeof(names)/sizeof(char *))-1);

    return 0;
}

void sort_name(char **pName, char order[], unsigned int size){

     unsigned int i;
     unsigned int z;

     ///print out
     printf("Original list:\n\t");
     for (i = 0; i < size; i++)
     {
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
     }

     ///start sorting...
     if (!strcmp(order,"asc")){
            printf("    Ascending sorted list:\n\t");
     for (i=0; i <size; i++){
         for(z=i+1; z<size; z++){
             if(strcmp(*(pName+i),*(pName+z))>0){
                char *temp = *(pName+i);
                *(pName+i) = *(pName+z);
                *(pName+z) = temp;
             }
         }
     }
     for (i = 0; i < size; i++){
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
         }
     }

     else if (!strcmp(order,"desc")){
            printf("    Descending sorted list:\n\t");
     for (i=0; i <size; i++){
         for(z=i+1; z<size; z++){
             if(strcmp(*(pName+i),*(pName+z))<0){
                char *temp = *(pName+i);
                *(pName+i) = *(pName+z);
                *(pName+z) = temp;
             }
         }

     }
     for (i = 0; i < size; i++){
         (i<size-1) ? printf(" %s,", *(pName+i)) : printf(" %s\n", *(pName+i));
         }
     }

     else{
        printf(" That doesnt even make sense!");
     }
}


问:
How to change h1 tittle when clicked/make the section centered
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

```<code><Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
</code>```

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

答:
As others have mentioned, you should be able to find everything on Google. But to help you out, this is what the answer should be:

var heading = document.getElementsByTagName("h1")[0];
var section = document.getElementById("first");

heading.addEventListener("click", function() {
    section.innerText = "First section: modified version";
});

section.addEventListener("click", function() {
    heading.setAttribute("style", "text-align: center");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 title="When this is clicked, the section changes">Title</h1>
<p id="first" title="When this is clicked, the title is centered">First section: Original version.</p></code>```

Body:
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

 Title

 First section: Original version.

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

Body:
As others have mentioned, you should be able to find everything on Google. But to help you out, this is what the answer should be:

var heading = document.getElementsByTagName("h1")[0];
var section = document.getElementById("first");

heading.addEventListener("click", function() {
    section.innerText = "First section: modified version";
});

section.addEventListener("click", function() {
    heading.setAttribute("style", "text-align: center");
});

<h1 title="When this is clicked, the section changes">Title</h1>
<p id="first" title="When this is clicked, the title is centered">First section: Original version.</p>


问:
Override ResourceHttpRequestHandler Spring MVC
I am trying to override ResourceHttpRequestHandler in my Spring MVC application.

I have the following class so far:

```<code>@Controller
public class ResourceHttpRequestHandlerReplacer extends ResourceHttpRequestHandler implements BeanFactoryPostProcessor {

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.handleRequest(request, response);
}

public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
        throws BeansException {
    String[] names = factory.getBeanNamesForType(ResourceHttpRequestHandler.class);

    for (String name : names) {
        BeanDefinition bd = factory.getBeanDefinition(name);
        bd.setBeanClassName("com.project.controllers.ResourceHttpRequestHandlerReplacer");
    }
}

}
</code>```

Right now its supposed to just call the super handleRequest so nothing should have changed but I am getting this message:

Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@16943e88]]] does not run within a ServletContext. Make sure the object is fully configured!

I am trying to override so that I can implement some custom logic around trying to find resources that aren't static but aren't mapped by a controller either as the user will be able to define URLs for the pages in their CMS.

Can anyone advise where ive gone wrong?

Thanks

答:
looks like your ResourceHttpRequestHandlerReplacer is not aware of the servletContext, which is rare since you are extending it from ResourceHttpRequestHandler. Try adding this to your class

```<code>@Autowired
ServletContext servletContext;
</code>```

Body:
I am trying to override ResourceHttpRequestHandler in my Spring MVC application.

I have the following class so far:

@Controller
public class ResourceHttpRequestHandlerReplacer extends ResourceHttpRequestHandler implements BeanFactoryPostProcessor {

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.handleRequest(request, response);
}

public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
        throws BeansException {
    String[] names = factory.getBeanNamesForType(ResourceHttpRequestHandler.class);

    for (String name : names) {
        BeanDefinition bd = factory.getBeanDefinition(name);
        bd.setBeanClassName("com.project.controllers.ResourceHttpRequestHandlerReplacer");
    }
}

}

Right now its supposed to just call the super handleRequest so nothing should have changed but I am getting this message:

Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@16943e88]]] does not run within a ServletContext. Make sure the object is fully configured!

I am trying to override so that I can implement some custom logic around trying to find resources that aren't static but aren't mapped by a controller either as the user will be able to define URLs for the pages in their CMS.

Can anyone advise where ive gone wrong?

Thanks

Body:
looks like your ResourceHttpRequestHandlerReplacer is not aware of the servletContext, which is rare since you are extending it from ResourceHttpRequestHandler. Try adding this to your class

@Autowired
ServletContext servletContext;


问:
Does anyone know how to emulate the search box on www.foodnetwork.com?
Does anyone know how to create a search field, similar to what is on the www.foodnetwork.com website? It contains a definition list to help the user select what area to search. If anyone knows of a demo site where someone might be building this, I would appreciate it. It's a very cool feature.</p>

答: It's just an autocomplete textboox. There are lots of tutorials around the Web if you Google it. (Random pick from the Google results: Auto-complete Control.) jQuery UI 1.8 also includes an autocomplete feature that pretty much handles it for you.</p>


问:
Error while display json from sql database - PHP
I made a script to display data from online SQL database into JSON format.
The problem is, I don't have the format i was looking for, I get 2 [ more while i wanted only one:

A part of my script:

```<code>$sql = "select pseudo, dixsec from user;";

$result = mysqli_query($conn,$sql);

$rows = array();
while($r = mysqli_fetch_assoc($result)) {

$rows[] = $r;

}
$arrray = array("server_response" => array($rows));
print json_encode($arrray);
</code>```

What i get (You can see here that i have 2 "["):
Json i get

How can i solve it and get only one "[" ?

答:
$rows is already an array.

Try with: $arrray = array("server_response" => $rows);

Body:
I made a script to display data from online SQL database into JSON format.
The problem is, I don't have the format i was looking for, I get 2 [ more while i wanted only one:

A part of my script:

$sql = "select pseudo, dixsec from user;";

$result = mysqli_query($conn,$sql);

$rows = array();
while($r = mysqli_fetch_assoc($result)) {

$rows[] = $r;

}
$arrray = array("server_response" => array($rows));
print json_encode($arrray);

What i get (You can see here that i have 2 "["):
Json i get

How can i solve it and get only one "[" ?


问:
In Ruby on Rails ActiveRecord, looking for case-insensitive sorting that actually works
ActiveRecord model: How to sort and be case insensitive?

After searching Google and trying a bunch of SO solutions, nothing seems to work and many other solutions are not as elegant as I would expect (they require invoking other methods explicitly rather than just work as a built-in-default, etc.).

This statement is what I like in its simplicity. The problem is that it is case sensitive:

```<code>default_scope -> { order(alias: :asc) }
</code>```

Here are some solutions that I got from Google and SO:

```<code>1. default_scope -> { |alias| where(alias: alias.downcase) }
2. scope lambda { |email| where(email: alias.downcase) }
3. default_scope order: 'lower(alias)'
4. default_scope -> { order(lower(alias: :asc)) }
5. default_scope -> { order(lower(:alias) :asc) }
</code>```

None of these solutions work: most generate errors. Perhaps this is because I am on Rails 5.0.2 and these are designed for old versions? I don't know.

In Ruby, at my stage of development, it is the simple things that trip me up. Thanks for your help.

答:
This solution here does work. After getting to this point, this is rather obvious but what throws me off is the strange answers that were recalled in the original question that were found by researching this problem that absolutely don't work.</p>

```<code>default_scope -> { order('lower(alias) asc') }
</code>```

Body:
ActiveRecord model: How to sort and be case insensitive?

After searching Google and trying a bunch of SO solutions, nothing seems to work and many other solutions are not as elegant as I would expect (they require invoking other methods explicitly rather than just work as a built-in-default, etc.).

This statement is what I like in its simplicity. The problem is that it is case sensitive:

default_scope -> { order(alias: :asc) }

Here are some solutions that I got from Google and SO:

1. default_scope -> { |alias| where(alias: alias.downcase) }
2. scope lambda { |email| where(email: alias.downcase) }
3. default_scope order: 'lower(alias)'
4. default_scope -> { order(lower(alias: :asc)) }
5. default_scope -> { order(lower(:alias) :asc) }

None of these solutions work: most generate errors. Perhaps this is because I am on Rails 5.0.2 and these are designed for old versions? I don't know.

In Ruby, at my stage of development, it is the simple things that trip me up. Thanks for your help.

Body:
This solution here does work. After getting to this point, this is rather obvious but what throws me off is the strange answers that were recalled in the original question that were found by researching this problem that absolutely don't work.

default_scope -> { order('lower(alias) asc') }


问:
Uploading a file from a bootstrap modal using ajax
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.

The modal html is

```<code><div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
</code>```

The Javascript

```<code>$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
   url: "attachment.php",
   type: "POST",
   data: data,
   processData: false,  // tell jQuery not to process the data
   contentType: false
   }).done(function(msg) {
   console.log(msg);
    $('#myAttachModal').modal('hide');
            });
    });
});
</code>```

The PHP server code

```<code>print_r($_POST);
print_r($_FILES);
</code>```

I am not seeing anything in the $_FILES array when I run this.

Any suggestions?

答:
Change the data value in your Ajax post to postData. postData contains the form data.

Change this section

data: data,

To

data: postData,//this contains the form data

Body:
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.

The modal html is

<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>

The Javascript

$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
   url: "attachment.php",
   type: "POST",
   data: data,
   processData: false,  // tell jQuery not to process the data
   contentType: false
   }).done(function(msg) {
   console.log(msg);
    $('#myAttachModal').modal('hide');
            });
    });
});

The PHP server code

print_r($_POST);
print_r($_FILES);

I am not seeing anything in the $_FILES array when I run this.

Any suggestions?


问:
String-literals without escaping null-character
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

```<code>const char digits[] = "0123456789abcdef";
</code>```

I know that you can write it in form of an array:

```<code>const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
</code>```

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

答:
In C, you could write

```<code>const char digits[16] = "0123456789abcdef";
</code>```

This is actually supported in C as defined in array initialization:

If the size of the array is known, it may be one less than the size of
  the string literal, in which case the terminating null character is
  ignored: char str[3] = "abc"; // str has type char[3] and holds 'a',
  'b', 'c'

For C++, I see no direct way; but one could come around this as follows:

```<code>char digits_t[16] = "0123456789abcde";
digits_t[15]='f';
const char* digits = digits_t;
</code>```

Body:
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

const char digits[] = "0123456789abcdef";

I know that you can write it in form of an array:

const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

Body:
In C, you could write

const char digits[16] = "0123456789abcdef";

This is actually supported in C as defined in array initialization:

If the size of the array is known, it may be one less than the size of
  the string literal, in which case the terminating null character is
  ignored: char str[3] = "abc"; // str has type char[3] and holds 'a',
  'b', 'c'

For C++, I see no direct way; but one could come around this as follows:

char digits_t[16] = "0123456789abcde";
digits_t[15]='f';
const char* digits = digits_t;


问:
Reading a remote file with java on linux
I need to read a remote file using a java app, but the file is in apache server on linux.
I tried with "\\" but doesn't work like windows.
How can i do that?</p>

答:
You'll need to use the URL class:
http://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.html

This is the standard way of reading files from a URL.


问:
ORACLE 12C - ORA-02287: sequence number not allowed here
I have created sequnce prac_seq:

```<code>CREATE SEQUENCE prac_seq
   START WITH 300
   INCREMENT BY 10;
</code>```

And I want to use it the following:

```<code>UPDATE pracownicy
   SET placa_dod = prac_seq.CURRVAL
   WHERE id_prac = prac_seq.CURRVAL;
</code>```

And then I get an error called:

Error report - SQL Error: ORA-02287: sequence number not allowed here
  02287. 00000 -  "sequence number not allowed here"
  *Cause:    The specified sequence number (CURRVAL or NEXTVAL) is inappropriate
             here in the statement.
  *Action:   Remove the sequence number.

Why I cannot use sequence like above?

答:
First, the documentation is quite clear on this point:

Restrictions on Sequence Values

You cannot use CURRVAL and NEXTVAL in the following constructs:

The WHERE clause of a SELECT statement

I do understand why NEXTVAL can't be used.  You think the WHERE clause is being executed once, but it is (conceptually) executed for each row.  Having a side-effecting operation in the WHERE introduces a host of problems.  The results of the query using an index, for instance, would be different from the results not using an index.

My guess is that the reason is because both values could change while the query is running, and in some cases, the result of the query is not deterministic.

Body:
I have created sequnce prac_seq:

CREATE SEQUENCE prac_seq
   START WITH 300
   INCREMENT BY 10;

And I want to use it the following:

UPDATE pracownicy
   SET placa_dod = prac_seq.CURRVAL
   WHERE id_prac = prac_seq.CURRVAL;

And then I get an error called:

Error report - SQL Error: ORA-02287: sequence number not allowed here
  02287. 00000 -  "sequence number not allowed here"
  *Cause:    The specified sequence number (CURRVAL or NEXTVAL) is inappropriate
             here in the statement.
  *Action:   Remove the sequence number.

Why I cannot use sequence like above?


问:
Can we say this is an IIFE ?!?- In Javascript
As you know in Javascript, it's very common to use the following expression as an IIFE (Immediately Invoked Function Expression) :

```<code>(function(){
  //code ...
})();
</code>```

I'm wondering if we can say that the following expression is an IIFE (when no return value needed):

```<code>new function(){
 //code ...
}
</code>```

Or

```<code>new function(global){
  //code..
}(this);
</code>```

Even though it's an object . Thanks .

Answer :

[ Thanks to @le_m , @vol7ron and @Bergi , here is the short answer ]
Can we say that he following expression is an IIFE (Immediately Invoked Function Expression) ?

```<code>new function(){
 //code ...
}
</code>```

Or

```<code>new function(global){
  //code..
}(this);
</code>```

The answer is NO.
And what's that ?
It's just an unnamed object with an anonymous constructor, so we're not talking about functions here (plain and simple).

答:
Is new function(){ ... } an IIFE?

Now, IIFE stands for Immediately Invoked Function Expression. And a FunctionExpression is defined as follows:

function BindingIdentifierₒₚₜ ( FormalParameters
  ) { FunctionBody }

So, are we dealing with a function expression? Let's analyze your syntax:

```<code>"type": "ExpressionStatement",
"expression": {
    "type": "NewExpression",
    "callee": {
        "type": "FunctionExpression",
        "params": [],
        "body": {
           ...
    },
    "arguments": []
}
</code>```

This shows us that your code is not a function expression, but it includes a function expression as a part of the NewExpression.

Is this expression immediately invoked? In a way, yes - see [[Construct]] invocation. The constructor function is immediately invoked.

Still, I wouldn't call the whole thing an IIFE as the outer expression is not a function expression. Some call this expression Immeditately Invoked Constructor or IIC instead (thanks to @vol7ron, @Bergi for pointing this out).

Body:
As you know in Javascript, it's very common to use the following expression as an IIFE (Immediately Invoked Function Expression) :

(function(){
  //code ...
})();

I'm wondering if we can say that the following expression is an IIFE (when no return value needed):

new function(){
 //code ...
}

Or

new function(global){
  //code..
}(this);

Even though it's an object . Thanks .

Answer :

[ Thanks to @le_m , @vol7ron and @Bergi , here is the short answer ]
Can we say that he following expression is an IIFE (Immediately Invoked Function Expression) ?

new function(){
 //code ...
}

Or

new function(global){
  //code..
}(this);

The answer is NO.
And what's that ?
It's just an unnamed object with an anonymous constructor, so we're not talking about functions here (plain and simple).

Body:
Is new function(){ ... } an IIFE?

Now, IIFE stands for Immediately Invoked Function Expression. And a FunctionExpression is defined as follows:

function BindingIdentifierₒₚₜ ( FormalParameters
  ) { FunctionBody }

So, are we dealing with a function expression? Let's analyze your syntax:

"type": "ExpressionStatement",
"expression": {
    "type": "NewExpression",
    "callee": {
        "type": "FunctionExpression",
        "params": [],
        "body": {
           ...
    },
    "arguments": []
}

This shows us that your code is not a function expression, but it includes a function expression as a part of the NewExpression.

Is this expression immediately invoked? In a way, yes - see [[Construct]] invocation. The constructor function is immediately invoked.

Still, I wouldn't call the whole thing an IIFE as the outer expression is not a function expression. Some call this expression Immeditately Invoked Constructor or IIC instead (thanks to @vol7ron, @Bergi for pointing this out).


问:
set number of comments per page
I'm using get_comments() in one of my page to retrive a list of comments.
However, I want only four comment to be in one page, so if there are 12 comment, they will be divide to three pages, and load the next page with ajax.
I couldn't find any comments_per_page or something similar in the function get_comments()

Any idea how to achive this?

Thanks in advance!

答: Using wp_list_comments with the parameter per_page did the job.

Title: set number of comments per page


问:
Cannot enqueue Query after invoking quit
According to the Node MySQL documentation (https://github.com/mysqljs/mysql#introduction):

Every method you invoke on a connection is queued and executed in sequence.

and

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Nevertheless, the code below doesn't work, because the connection.end() method is called before the SQL queries can run.  If I comment out the connection.end() line, it works, but the script hangs (doesn't close/end) when it completes, requiring me to hit ctrl-c to end it.

If I move the MySQL connection object and the connection.end() call into the lineReader.createInterface().on() block, it works - the script correctly terminates at the end...but it's creating a new connection for every INSERT statement.

It doesn't seem right to close and reconnect each time like that.  Am I misunderstanding the Node MySQL documentation?  Is there a better way?

```<code>let lineReader  = require('readline');
let file        = require('fs');
let mysql       = require('mysql');

let connection  = mysql.createConnection({
    host: '127.0.0.1',
    port: 33060,
    user: 'homestead',
    password: 'secret',
    database: 'sentinel',
});

lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
        let ary = line.split(/[:, ]/);
        let insert_sql;

        if (typeof ary[2] !== 'undefined' && typeof  ary[3] !== 'undefined') {
            insert_sql =
                'INSERT INTO proxies (host, port, username, password) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '", "' + ary[2] + '", "' + ary[3] + '")';
        } else {
            insert_sql =
                'INSERT INTO proxies (host, port) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '")';
        }

        connection.query(insert_sql, function (error, results, fields) {
            if (error) {
                console.log('error: ' + error);
            } else {
                console.log('success: ' + insert_sql);
            }
        });

    });

connection.end();
</code>```

答:
You can call connection.end() in a close event listener:

```<code>lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
      ...
    }).on('close', function() {
      connection.end();
    });
</code>```

Body:
According to the Node MySQL documentation (https://github.com/mysqljs/mysql#introduction):

Every method you invoke on a connection is queued and executed in sequence.

and

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Nevertheless, the code below doesn't work, because the connection.end() method is called before the SQL queries can run.  If I comment out the connection.end() line, it works, but the script hangs (doesn't close/end) when it completes, requiring me to hit ctrl-c to end it.

If I move the MySQL connection object and the connection.end() call into the lineReader.createInterface().on() block, it works - the script correctly terminates at the end...but it's creating a new connection for every INSERT statement.

It doesn't seem right to close and reconnect each time like that.  Am I misunderstanding the Node MySQL documentation?  Is there a better way?

let lineReader  = require('readline');
let file        = require('fs');
let mysql       = require('mysql');

let connection  = mysql.createConnection({
    host: '127.0.0.1',
    port: 33060,
    user: 'homestead',
    password: 'secret',
    database: 'sentinel',
});

lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
        let ary = line.split(/[:, ]/);
        let insert_sql;

        if (typeof ary[2] !== 'undefined' && typeof  ary[3] !== 'undefined') {
            insert_sql =
                'INSERT INTO proxies (host, port, username, password) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '", "' + ary[2] + '", "' + ary[3] + '")';
        } else {
            insert_sql =
                'INSERT INTO proxies (host, port) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '")';
        }

        connection.query(insert_sql, function (error, results, fields) {
            if (error) {
                console.log('error: ' + error);
            } else {
                console.log('success: ' + insert_sql);
            }
        });

    });

connection.end();

Body:
You can call connection.end() in a close event listener:

lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
      ...
    }).on('close', function() {
      connection.end();
    });


问:
Google calendar event respond on behalf of guest
I scheduled an event on my Google Calendar and one of the guests called me asking me to mark them as a "maybe."

Is there a way for me to mark the RSVP on behalf of the guest on my event?

The only thing I found online that can do this is iGoogle and that was phased out in 2015.

Thanks in advance.

答:
You might want to test the Events: insert - attendees[].responseStatus:

The attendee's response status. Possible values are:

"needsAction" - The attendee has not responded to the invitation.

"declined" - The attendee has declined the invitation.

"tentative" - The attendee has tentatively accepted the invitation.

"accepted" - The attendee has accepted the invitation.

I've tested the this and it let my guess have a pre-valued response (accepted) on his behalf. I've used "Try this API" on the same page of the document and checked my calendar if it works.

Hope this helps.


问:
How to specify jetty-env.xml file for Maven Cargo plugin for Jetty?
I am migrating from Maven's jetty plugin to the Cargo plugin (cargo-maven2-plugin) because Cargo will happily run WARs from dependent Maven modules.  Within out web-app we have taken great pains to externalize all configuration through JNDI.  These JNDI definitions are web-app specific and therefore are placed in a jetty-env.xml file that is outside the WAR.  Using the Jetty plugin, we specified this file as follows:

```<code>        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <configuration>
                <jettyEnvXml>${basedir}/target/config/jetty-env.xml</jettyEnvXml>
            </configuration>
        </plugin>
</code>```

How does one go about specifying this within the Cargo Plugin?  Here's the configuration I have so far.  It is, of course, failing because of the absent JNDI configuration:

```<code>        <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <configuration>
                    <container>
                        <containerId>jetty6x</containerId>
                        <type>embedded</type>
                    </container>
                    <configuration>
                        <deployables>
                            <deployable>
                                <groupId>com.mycompany</groupId>
                                <artifactId>my-war-module</artifactId>
                                <type>war</type>
                                <properties>
                                   <context>/</context>
                                </properties>
                            </deployable>
                        </deployables>
                    </configuration>
                    <wait>false</wait>
                </configuration>
                <executions>
                           ......
                </executions>
        </plugin>
</code>```

答:
Something else I want to do is to filter properties.  So far I have this:

```<code>    <profile>
        <id>deploy-properties</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <deployable.classifier>properties</deployable.classifier>
            <deployable.type>zip</deployable.type>
            <ys.imq.user>UserFromDeploymentPom</ys.imq.user>
            <ys.imq.password>PasswordFromDeploymentPom</ys.imq.password>
        </properties>
        <dependencies>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>${deployable.artifactId}</artifactId>
                <classifier>${deployable.classifier}</classifier>
                <type>${deployable.type}</type>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>process-resources</phase>
                            <goals>
                                <goal>unpack</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${deployable.artifactId}</artifactId>
                                <classifier>${deployable.classifier}</classifier>
                                <version>${project.version}</version>
                                <type>${deployable.type}</type>
                                <overWrite>true</overWrite>
                                <outputDirectory>/tmp/${deployable.artifactId}</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${deploy.jettyHome}</outputDirectory>
                                <overwrite>true</overwrite>
                                <resources>
                                    <resource>
                                        <directory>/tmp/${deployable.artifactId}</directory>
                                        <filtering>true</filtering>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>```

Its a bit more complicated than I like but allows me to filter properties whilst adding them to Jetty.  This enables passwords and other confidential data to be overriden using system properties.  We are using Bamboo (I guess Hudson is similar) and one can adjust plans per environment.  Plans can be subject to access control.  This allows us to have one place to set all deployment properties, so no more admins hacking on the Unix boxes.

Body:
I am migrating from Maven's jetty plugin to the Cargo plugin (cargo-maven2-plugin) because Cargo will happily run WARs from dependent Maven modules.  Within out web-app we have taken great pains to externalize all configuration through JNDI.  These JNDI definitions are web-app specific and therefore are placed in a jetty-env.xml file that is outside the WAR.  Using the Jetty plugin, we specified this file as follows:

        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <configuration>
                <jettyEnvXml>${basedir}/target/config/jetty-env.xml</jettyEnvXml>
            </configuration>
        </plugin>

How does one go about specifying this within the Cargo Plugin?  Here's the configuration I have so far.  It is, of course, failing because of the absent JNDI configuration:

        <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <configuration>
                    <container>
                        <containerId>jetty6x</containerId>
                        <type>embedded</type>
                    </container>
                    <configuration>
                        <deployables>
                            <deployable>
                                <groupId>com.mycompany</groupId>
                                <artifactId>my-war-module</artifactId>
                                <type>war</type>
                                <properties>
                                   <context>/</context>
                                </properties>
                            </deployable>
                        </deployables>
                    </configuration>
                    <wait>false</wait>
                </configuration>
                <executions>
                           ......
                </executions>
        </plugin>

Body:
Something else I want to do is to filter properties.  So far I have this:

    <profile>
        <id>deploy-properties</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <deployable.classifier>properties</deployable.classifier>
            <deployable.type>zip</deployable.type>
            <ys.imq.user>UserFromDeploymentPom</ys.imq.user>
            <ys.imq.password>PasswordFromDeploymentPom</ys.imq.password>
        </properties>
        <dependencies>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>${deployable.artifactId}</artifactId>
                <classifier>${deployable.classifier}</classifier>
                <type>${deployable.type}</type>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>process-resources</phase>
                            <goals>
                                <goal>unpack</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${deployable.artifactId}</artifactId>
                                <classifier>${deployable.classifier}</classifier>
                                <version>${project.version}</version>
                                <type>${deployable.type}</type>
                                <overWrite>true</overWrite>
                                <outputDirectory>/tmp/${deployable.artifactId}</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${deploy.jettyHome}</outputDirectory>
                                <overwrite>true</overwrite>
                                <resources>
                                    <resource>
                                        <directory>/tmp/${deployable.artifactId}</directory>
                                        <filtering>true</filtering>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>

Its a bit more complicated than I like but allows me to filter properties whilst adding them to Jetty.  This enables passwords and other confidential data to be overriden using system properties.  We are using Bamboo (I guess Hudson is similar) and one can adjust plans per environment.  Plans can be subject to access control.  This allows us to have one place to set all deployment properties, so no more admins hacking on the Unix boxes.


问:
Removing a Turtle from a List
I have a list in which each element is a turtle and was trying to make a turtle get removed from the list and get hidden. So far I have tried :

```<code>lis[lis.index(food)].ht()
lis[lis.index(food)].clear()
lis.remove(lis.index(food))
</code>```

However, when I run this, I get an error saying that the element is not found.

答:
If lis is a list of turtles and food is a turtle then use lis.remove(food). The error message that you are getting is because lis.index(food) is an int (not a turtle) and that int isn't in your list.

If you are going to be doing a lot of removing, a dictionary of turtles might be more natural than a list. Removing from a dictionary is O(1) but removing from a list is O(n). As a general rule of thumb, if you find yourself repeatedly removing (and/or inserting) items from the middle of a list you should ask yourself if there is a better way of achieving your goal.

Title: Removing a Turtle from a List

Body:
I have a list in which each element is a turtle and was trying to make a turtle get removed from the list and get hidden. So far I have tried :

lis[lis.index(food)].ht()
lis[lis.index(food)].clear()
lis.remove(lis.index(food))

However, when I run this, I get an error saying that the element is not found.