问:
protractor in typescript setup issue
Tried running protractor with typescript, but got following error

```<code>C:\MyFiles\NewTechonologies\Protractor\TypeScript\Test>npm install
npm ERR! not a package C:\Users\skp\AppData\Roaming\npm\node_modules\protractor\bin\protractor
npm ERR! addLocal Could not install C:\Users\skp\AppData\Roaming\npm\node_modules\protractor\bin\protractor
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "
install"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! path C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpack-b2acb3b1\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpac
k-b2acb3b1\package.json'
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpac
k-b2acb3b1\package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     C:\MyFiles\NewTechonologies\Protractor\TypeScript\Test\npm-debug.log
</code>```

My setup is like

package.json

```<code>{
  "name": "example-typescript",
  "version": "1.0.0",
  "description": "a typescript example",
  "author": "",
  "license": "MIT",
  "scripts": {
    "tsc": "tsc",
    "pretest": "npm run tsc",
    "test": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor tmp/conf.js",
   "debug": "node --inspect --debug-brk C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor asyncAwait/conf.js"
  },
  "dependencies": {
    "@types/jasmine": "2.5.41",
    "@types/jasminewd2": "^2.0.0",
    "jasmine": "^2.4.1",
    "protractor": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor",
    "typescript": "~2.0.0"
  },
  "devDependencies": {
    "@types/jasminewd2": "^2.0.0",
    "ts-node": "^3.0.2"
  }
}
</code>```

spec.ts

```<code>import {browser, element, by, By, $, $$, ExpectedConditions} from 'protractor';

describe('protractor with typescript typings', () => {
  beforeEach(() => {
    browser.get('http://www.angularjs.org');
  });

  it('should greet the named user', () => {
    element(by.model('yourName')).sendKeys('Julie');
    let greeting = element(by.binding('yourName'));
    expect(greeting.getText()).toEqual('Hello Julie!');
  });

  it('should list todos', function() {
    let todoList = element.all(by.repeater('todo in todoList.todos'));
    expect(todoList.count()).toEqual(2);
    expect(todoList.get(1).getText()).toEqual('build an angular app');
  });
});
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "inlineSourceMap": true,
    "declaration": false,
    "noImplicitAny": false,
    "outDir": "tmp"
  },
  "exclude": [
    "node_modules",
    "asyncAwait",
    "plugins.ts"
  ]
}
</code>```

I have installed protractor, jasmine, typescript globally.
still getting error as above and conf.ts also throws error on protractor text as shown in picture
Please guide where exactly the setup went wrong.

答:
Since you have installed the above said modules globally, they should work without the npm install.

Nevertheless, you should have these modules as dependencies in your package.json. It clearly is a path issue, npm is not able to find the protractor module during npm install.

You have 2 options -

correct the local protractor path in your package.json

```<code>"dependencies": {
"@types/jasmine": "2.5.41",
"@types/jasminewd2": "^2.0.0",
"jasmine": "^2.4.1",
"protractor": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor",
"typescript": "~2.0.0"
},
</code>```

mention the protractor version in package.json as you have done with rest of your modules

```<code>"dependencies": {
"@types/jasmine": "2.5.41",
"@types/jasminewd2": "^2.0.0",
"jasmine": "^2.4.1",
"protractor": "^5.1.1",
"typescript": "~2.0.0"
},
</code>```

Now if you run ``npm install` it should install the dependencies successfully.

Title: protractor in typescript setup issue

Body:
Tried running protractor with typescript, but got following error

C:\MyFiles\NewTechonologies\Protractor\TypeScript\Test>npm install
npm ERR! not a package C:\Users\skp\AppData\Roaming\npm\node_modules\protractor\bin\protractor
npm ERR! addLocal Could not install C:\Users\skp\AppData\Roaming\npm\node_modules\protractor\bin\protractor
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "
install"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! path C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpack-b2acb3b1\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpac
k-b2acb3b1\package.json'
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\skp\AppData\Local\Temp\npm-8952-eac08724\unpac
k-b2acb3b1\package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     C:\MyFiles\NewTechonologies\Protractor\TypeScript\Test\npm-debug.log

My setup is like

package.json

{
  "name": "example-typescript",
  "version": "1.0.0",
  "description": "a typescript example",
  "author": "",
  "license": "MIT",
  "scripts": {
    "tsc": "tsc",
    "pretest": "npm run tsc",
    "test": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor tmp/conf.js",
   "debug": "node --inspect --debug-brk C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor asyncAwait/conf.js"
  },
  "dependencies": {
    "@types/jasmine": "2.5.41",
    "@types/jasminewd2": "^2.0.0",
    "jasmine": "^2.4.1",
    "protractor": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor/bin/protractor",
    "typescript": "~2.0.0"
  },
  "devDependencies": {
    "@types/jasminewd2": "^2.0.0",
    "ts-node": "^3.0.2"
  }
}

spec.ts

import {browser, element, by, By, $, $$, ExpectedConditions} from 'protractor';

describe('protractor with typescript typings', () => {
  beforeEach(() => {
    browser.get('http://www.angularjs.org');
  });

  it('should greet the named user', () => {
    element(by.model('yourName')).sendKeys('Julie');
    let greeting = element(by.binding('yourName'));
    expect(greeting.getText()).toEqual('Hello Julie!');
  });

  it('should list todos', function() {
    let todoList = element.all(by.repeater('todo in todoList.todos'));
    expect(todoList.count()).toEqual(2);
    expect(todoList.get(1).getText()).toEqual('build an angular app');
  });
});

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "inlineSourceMap": true,
    "declaration": false,
    "noImplicitAny": false,
    "outDir": "tmp"
  },
  "exclude": [
    "node_modules",
    "asyncAwait",
    "plugins.ts"
  ]
}

I have installed protractor, jasmine, typescript globally.
still getting error as above and conf.ts also throws error on protractor text as shown in picture
Please guide where exactly the setup went wrong.

Body:
Since you have installed the above said modules globally, they should work without the npm install.

Nevertheless, you should have these modules as dependencies in your package.json. It clearly is a path issue, npm is not able to find the protractor module during npm install.

You have 2 options -

correct the local protractor path in your package.json

"dependencies": {
"@types/jasmine": "2.5.41",
"@types/jasminewd2": "^2.0.0",
"jasmine": "^2.4.1",
"protractor": "C:/Users/skp/AppData/Roaming/npm/node_modules/protractor",
"typescript": "~2.0.0"
},

mention the protractor version in package.json as you have done with rest of your modules

"dependencies": {
"@types/jasmine": "2.5.41",
"@types/jasminewd2": "^2.0.0",
"jasmine": "^2.4.1",
"protractor": "^5.1.1",
"typescript": "~2.0.0"
},

Now if you run ``npm install` it should install the dependencies successfully.


来源: stackexchange

问:
drain array values in the url
Array

```<code>var array = [
    {
        item: "abcd1234",
        data: "something"
    },
    {
        item: "4321dcba",
        data: "something"
    },
];
</code>```

Array length can be randomly from 1 to 10

I'm making http request for all these items.

```<code>array.forEach(function(item) {

    var url = "www.something.com?id=" + item.item;

    //making request

});
</code>```

Now I need 1 - 10 requests per array depends on a array length.

Lets say I have 10 arrays with 10 elements in it. Its 100 requests.

I could do this with only 1 request per array if I use url like this

www.something.com?id=abcd1234&id2=4321dcba

How do I loop all array values to the url if I don't know how many elements there is?

答:
Use array-style URL parameter names. Most server-side libraries and frameworks will collect these into an array (e.g. $_GET['id'] will be an array in PHP).

You can use .map() to return an array of all the parameters, and .join() to connect them with &.

var array = [{
    item: "abcd1234",
    data: "something"
  },
  {
    item: "4321dcba",
    data: "something"
  },
];

var url = 'www.something.com?' +
  array.map(function(item) {
    return 'id[]=' + encodeURIComponent(item.item);
  }).join('&');

console.log(url);```

ContentLicense: CC BY-SA 3.0

Title: drain array values in the url

Body:
Array

var array = [
    {
        item: "abcd1234",
        data: "something"
    },
    {
        item: "4321dcba",
        data: "something"
    },
];

Array length can be randomly from 1 to 10

I'm making http request for all these items.

array.forEach(function(item) {

    var url = "www.something.com?id=" + item.item;

    //making request

});

Now I need 1 - 10 requests per array depends on a array length.

Lets say I have 10 arrays with 10 elements in it. Its 100 requests.

I could do this with only 1 request per array if I use url like this

www.something.com?id=abcd1234&id2=4321dcba

How do I loop all array values to the url if I don't know how many elements there is?


问:
Select second min() or second smallest from mysql table
I'm wondering how to select the second smallest value from a mysql table, grouped on a non-numeric column. If I have a table that looks like this:

```<code>    +----+----------+------------+--------+------------+
    | id | customer | order_type | amount | created_dt |
    +----+----------+------------+--------+------------+
    |  1 |        1 | web        |      5 | 2017-01-01 |
    |  2 |        1 | web        |      7 | 2017-01-05 |
    |  3 |        2 | web        |      2 | 2017-01-07 |
    |  4 |        3 | web        |      2 | 2017-02-01 |
    |  5 |        3 | web        |      3 | 2017-02-01 |
    |  6 |        2 | web        |      5 | 2017-03-15 |
    |  7 |        1 | in_person  |      7 | 2017-02-01 |
    |  8 |        3 | web        |      8 | 2017-01-01 |
    |  9 |        2 | web        |      1 | 2017-04-01 |
    +----+----------+------------+--------+------------+
</code>```

I want to count the number of second orders in each month/year. I also have a customer table (which is where the customer ids come from). I can find the number of customers with more than at least 2 orders by the customer's created date by querying

```<code>select date(c.created_dt) as create_date, count(c.id)
from customer c
where c.id in
  (select or.identity_id
  from orders or
  where
    (select count(o.created_dt)
    from orders o
    where or.customer = o.customer and o.order_tpe in ('web')
    ) > 1
  )
group by 1;
</code>```

However, that result gives customer by their created date, and I can't seem to figure out how to find the the number of second orders by date.
The desired output i'd like to see, based on the data above, is:

```<code>    +-------+------+---------------+
    | month | year | second_orders |
    +-------+------+---------------+
    |  1    | 2017 | 1             |
    |  2    | 2017 | 1             |
    |  3    | 2017 | 1             |
    +-------+------+---------------+
</code>```

答:
One way to approach this

SELECT YEAR(created_dt) year, MONTH(created_dt) month, COUNT(*) second_orders
  FROM (
    SELECT created_dt,
           @rn := IF(@c = customer, @rn + 1, 1) rn,
           @c := customer
      FROM orders CROSS  JOIN (
        SELECT @c := NULL, @rn := 1
      ) i
     WHERE order_type = 'web'
     ORDER BY customer, id
  ) q
 WHERE rn = 2
 GROUP BY YEAR(created_dt), MONTH(created_dt)
 ORDER BY year, month
```

<p>Here is a dbfiddle demo</p>

<p>Output:</p>

```
+------+-------+---------------+
| year | month | second_orders |
+------+-------+---------------+
| 2017 |     1 |             1 |
| 2017 |     2 |             1 |
| 2017 |     3 |             1 |
+------+-------+---------------+
```

Body:
I'm wondering how to select the second smallest value from a mysql table, grouped on a non-numeric column. If I have a table that looks like this:

    +----+----------+------------+--------+------------+
    | id | customer | order_type | amount | created_dt |
    +----+----------+------------+--------+------------+
    |  1 |        1 | web        |      5 | 2017-01-01 |
    |  2 |        1 | web        |      7 | 2017-01-05 |
    |  3 |        2 | web        |      2 | 2017-01-07 |
    |  4 |        3 | web        |      2 | 2017-02-01 |
    |  5 |        3 | web        |      3 | 2017-02-01 |
    |  6 |        2 | web        |      5 | 2017-03-15 |
    |  7 |        1 | in_person  |      7 | 2017-02-01 |
    |  8 |        3 | web        |      8 | 2017-01-01 |
    |  9 |        2 | web        |      1 | 2017-04-01 |
    +----+----------+------------+--------+------------+

I want to count the number of second orders in each month/year. I also have a customer table (which is where the customer ids come from). I can find the number of customers with more than at least 2 orders by the customer's created date by querying

select date(c.created_dt) as create_date, count(c.id)
from customer c
where c.id in
  (select or.identity_id
  from orders or
  where
    (select count(o.created_dt)
    from orders o
    where or.customer = o.customer and o.order_tpe in ('web')
    ) > 1
  )
group by 1;

However, that result gives customer by their created date, and I can't seem to figure out how to find the the number of second orders by date.
The desired output i'd like to see, based on the data above, is:

    +-------+------+---------------+
    | month | year | second_orders |
    +-------+------+---------------+
    |  1    | 2017 | 1             |
    |  2    | 2017 | 1             |
    |  3    | 2017 | 1             |
    +-------+------+---------------+

Body:
One way to approach this

SELECT YEAR(created_dt) year, MONTH(created_dt) month, COUNT(*) second_orders
  FROM (
    SELECT created_dt,
           @rn := IF(@c = customer, @rn + 1, 1) rn,
           @c := customer
      FROM orders CROSS  JOIN (
        SELECT @c := NULL, @rn := 1
      ) i
     WHERE order_type = 'web'
     ORDER BY customer, id
  ) q
 WHERE rn = 2
 GROUP BY YEAR(created_dt), MONTH(created_dt)
 ORDER BY year, month

Here is a dbfiddle demo

Output:

+------+-------+---------------+
| year | month | second_orders |
+------+-------+---------------+
| 2017 |     1 |             1 |
| 2017 |     2 |             1 |
| 2017 |     3 |             1 |
+------+-------+---------------+


问:
how to convert odata json to concrete DTO
I am attempting to take some ugly json, that looks like this:

And deserialize it to my DTO:

```<code>public class Account
{
    [JsonProperty("@odata.etag")]
    public string etag { get; set; }
    public Guid accountid { get; }
    public DateTime CreatedOn { get; }
    public Guid OwnerId { get; }
    public string Name { get; set; }
    public DateTime ModifiedOn { get; }
    public Guid CreatedBy { get; }

}

public class RootObject
{
    [JsonProperty("@odata.context")]
    public string context { get; set; }
    public List<Account> value { get; set; }
}
</code>```

This is how I attempt to do it:

```<code>    public async Task<Account> GetAccount(string query)
    {
        var task = await Client.HTTPCLIENT.GetAsync(Client.HTTPCLIENT.BaseAddress + query);
        var jsonString = await task.Content.ReadAsStringAsync();
        var value = JsonConvert.DeserializeObject<RootObject>(jsonString);
        return value.value.First();
    }
</code>```

And my response partially works:

```<code>{"@odata.etag":"W/\"608578\"","accountid":"00000000-0000-0000-0000-000000000000","CreatedOn":"0001-01-01T00:00:00","OwnerId":"00000000-0000-0000-0000-000000000000","Name":"Smith","ModifiedOn":"0001-01-01T00:00:00","CreatedBy":"00000000-0000-0000-0000-000000000000"}
</code>```

What am I doing wrong? How do I convert this odata json response to a c# object?

答:
I'm making some assumptions that you don't specify:

I assume you're using Json.net

For the date properties, you want to add the attribute [IsoDateTimeConverter], which comes with Json.net

So...

```<code>[IsoDateTimeConverter]
public DateTime CreatedOn { get; }
</code>```

DateTime properties won't parse ISO 8601 strings by default, you have to use the converter.

And basically, that's your answer for the Guid's and such as well, except you also have to implement those converters for yourself.  You have to create a converter class, and read the input string, and parse it into the Guid object.  Then decorate each Guid property with a [YourCustomGuidConverter] attribute.

Body:
I am attempting to take some ugly json, that looks like this:

And deserialize it to my DTO:

public class Account
{
    [JsonProperty("@odata.etag")]
    public string etag { get; set; }
    public Guid accountid { get; }
    public DateTime CreatedOn { get; }
    public Guid OwnerId { get; }
    public string Name { get; set; }
    public DateTime ModifiedOn { get; }
    public Guid CreatedBy { get; }

}

public class RootObject
{
    [JsonProperty("@odata.context")]
    public string context { get; set; }
    public List<Account> value { get; set; }
}

This is how I attempt to do it:

    public async Task<Account> GetAccount(string query)
    {
        var task = await Client.HTTPCLIENT.GetAsync(Client.HTTPCLIENT.BaseAddress + query);
        var jsonString = await task.Content.ReadAsStringAsync();
        var value = JsonConvert.DeserializeObject<RootObject>(jsonString);
        return value.value.First();
    }

And my response partially works:

{"@odata.etag":"W/\"608578\"","accountid":"00000000-0000-0000-0000-000000000000","CreatedOn":"0001-01-01T00:00:00","OwnerId":"00000000-0000-0000-0000-000000000000","Name":"Smith","ModifiedOn":"0001-01-01T00:00:00","CreatedBy":"00000000-0000-0000-0000-000000000000"}

What am I doing wrong? How do I convert this odata json response to a c# object?

Body:
I'm making some assumptions that you don't specify:

I assume you're using Json.net

For the date properties, you want to add the attribute [IsoDateTimeConverter], which comes with Json.net

So...

[IsoDateTimeConverter]
public DateTime CreatedOn { get; }

DateTime properties won't parse ISO 8601 strings by default, you have to use the converter.

And basically, that's your answer for the Guid's and such as well, except you also have to implement those converters for yourself.  You have to create a converter class, and read the input string, and parse it into the Guid object.  Then decorate each Guid property with a [YourCustomGuidConverter] attribute.


问:
How to make UITextField move up when keyboard is present?
How do I prevent a UITextField from being hidden by the keyboard?

答:
Swift 3 code for Geiger answer

```<code>func textFieldDidBeginEditing(_ textField: UITextField) { // became first responder

    //move textfields up
    let myScreenRect: CGRect = UIScreen.main.bounds
    let keyboardHeight : CGFloat = 216

    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var needToMove: CGFloat = 0

    var frame : CGRect = self.view.frame
    if (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight - 30)) {
        needToMove = (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight - 30);
    }

    frame.origin.y = -needToMove
    self.view.frame = frame
    UIView.commitAnimations()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    //move textfields back down
    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var frame : CGRect = self.view.frame
    frame.origin.y = 0
    self.view.frame = frame
    UIView.commitAnimations()
}
</code>```

Body:
Swift 3 code for Geiger answer

func textFieldDidBeginEditing(_ textField: UITextField) { // became first responder

    //move textfields up
    let myScreenRect: CGRect = UIScreen.main.bounds
    let keyboardHeight : CGFloat = 216

    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var needToMove: CGFloat = 0

    var frame : CGRect = self.view.frame
    if (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight - 30)) {
        needToMove = (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight - 30);
    }

    frame.origin.y = -needToMove
    self.view.frame = frame
    UIView.commitAnimations()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    //move textfields back down
    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var frame : CGRect = self.view.frame
    frame.origin.y = 0
    self.view.frame = frame
    UIView.commitAnimations()
}


问:
What is the proper way to handle several automatic redirects?
I have a website that basically allows customers to build a cart with an item that can be configured. A user will pick an item, and they'll be prompted to pick the first option they want, they get sent to the second step where they pick their second option, etc.

The number of steps and the number of options are variable, as they are defined by the client. Usually the item only has 2-3 steps with 5-10 options. However, in order to make it faster for the customer, if there is only one option available for the given step, it will automatically be chosen and the user will be sent to the next step.

A client decided to set up an item with 10+ steps with only one option for each step. This results in the entire process automatically choosing everything. FireFox doesn't like this, as it gives the error

Firefox has detected that the server
  is redirecting the request for this
  address in a way that will never
  complete.

(I haven't checked IE or Chrome, although it probably gives similar errors).

What's the best way to fix this?

Right now the process is basically

User picks item

User picks option if there is more than one option available. Otherwise the website does step 3 itself.

POST to add the option to the cart

Redirect to Page.aspx?step=#

Repeat step 2-4 as many times as necessary

Is there any change I can make to the code or page so that FireFox doesn't think I'm in an endless loop?

答:
I'm guessing something like this would work:

Read Step # from query string into local variable

Load data from database passing in the local step variable

If data only contains one option then:

(3.1) Store option

(3.2) increment local step variable

(3.3) goto 2

Load page with data from step 2

How does your code handling someone skipping options and entering Page.aspx?step=10 into the address bar when they are on Page.aspx?step=1?

ContentLicense: CC BY-SA 2.5


问:
How to access the class name of a React object in this.props.children
In a react component render method that has some children components in this.props.children. How can I get the component (class) name of each child to differentiate between them?</p>

```<code>React.Children.map(this.props.children, function(child){
    // how can I get the class name of a child or some other identifier
})
</code>```

答:
The same as @Vaclav, but if you are using redux connect you will get "Connect" as name which may cause problems. Here is my improved version:</p>

```<code>let{ name, displayName=name } = child.type;
React.cloneElement(child, {
  ...
  key:displayName,
});
</code>```

Body:
In a react component render method that has some children components in this.props.children. How can I get the component (class) name of each child to differentiate between them?

React.Children.map(this.props.children, function(child){
    // how can I get the class name of a child or some other identifier
})

Body:
The same as @Vaclav, but if you are using redux connect you will get "Connect" as name which may cause problems. Here is my improved version:

let{ name, displayName=name } = child.type;
React.cloneElement(child, {
  ...
  key:displayName,
});


问:
How to pass a variable from laravel 5.4 to vuejs
Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this

var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js

example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK

Controller

```<code>class SearchCompanyName extends Controller
{
    public function getcompanyname($name)
    {
      return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
    }

    public function index()
    {
       $url = $this->getcompanyname(Input::get("company_name_by_user"));
       return view('searchcompany', ['url' => $url]);

    }
}
</code>```

vue app.js

```<code>Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
    el: '#search',
    data: {
    },
    method: {
        getMessages: function(){
            console.log('I am here')
        }()
    }
});
</code>```

blade template

```<code>@section('content')
<div class="container">
{!! $url !!}
 <search></search>
</div>

@endsection
</code>```

答:
You can use this package : https://github.com/laracasts/PHP-Vars-To-Js-Transformer</p>

```<code>public function index()
{
    JavaScript::put([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29
    ]);

    return View::make('hello');
}
</code>```

Body:
Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this

var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js

example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK

Controller

class SearchCompanyName extends Controller
{
    public function getcompanyname($name)
    {
      return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
    }

    public function index()
    {
       $url = $this->getcompanyname(Input::get("company_name_by_user"));
       return view('searchcompany', ['url' => $url]);

    }
}

vue app.js

Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
    el: '#search',
    data: {
    },
    method: {
        getMessages: function(){
            console.log('I am here')
        }()
    }
});

blade template

@section('content')

{!! $url !!}
 <search></search>

@endsection

Body:
You can use this package : https://github.com/laracasts/PHP-Vars-To-Js-Transformer

public function index()
{
    JavaScript::put([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29
    ]);

    return View::make('hello');
}


问:
Spark NegativeArraySizeException
In a spark job I join two RDDs,

```<code>val data: RDD[(Long, (String, String))] = sc.objectFile[(Long, scala.collection.mutable.HashMap[String, Object])](outputFile)
  .leftOuterJoin(attributionData)
</code>```

Here outputFile is output of another spark job which process data from hive. One of the tables in hive has 40 million records and when I limit to read table to fetch only 10 million records code works fine. However with full data (if I remove limit()) following error occurs,

```<code>10:43:27 WARN TaskSetManager: Lost task 0.0 in stage 1.0 (TID 2, buysub.com): java.lang.NegativeArraySizeException
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.resize(IdentityObjectIntMap.java:409)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.putStash(IdentityObjectIntMap.java:227)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.push(IdentityObjectIntMap.java:221)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.put(IdentityObjectIntMap.java:117)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.putStash(IdentityObjectIntMap.java:228)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.push(IdentityObjectIntMap.java:221)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.put(IdentityObjectIntMap.java:117)
at com.esotericsoftware.kryo.util.MapReferenceResolver.addWrittenObject(MapReferenceResolver.java:23)
at com.esotericsoftware.kryo.Kryo.writeReferenceOrNull(Kryo.java:598)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:566)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:224)
at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:403)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.immutable.List.foreach(List.scala:318)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.Tuple2Serializer.write(TupleSerializers.scala:37)
at com.twitter.chill.Tuple2Serializer.write(TupleSerializers.scala:33)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.mutable.HashMap$$anonfun$foreach$1.apply(HashMap.scala:98)
at scala.collection.mutable.HashMap$$anonfun$foreach$1.apply(HashMap.scala:98)
at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:226)
at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:39)
at scala.collection.mutable.HashMap.foreach(HashMap.scala:98)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
</code>```

I am using Spark 1.6. Following is the spark configuration,

```<code>conf.set("spark.driver.memory", "4G")
conf.set("spark.executor.memory", "30G")
conf.set("spark.rdd.compress", "true")
conf.set("spark.storage.memoryFraction", "0.3")
conf.set("spark.shuffle.consolidateFiles", "true")
conf.set("spark.shuffle.memoryFraction", "0.5")
conf.set("spark.akka.frameSize", "384")
conf.set("spark.io.compression.codec", "lz4")
conf.set("spark.serializer","org.apache.spark.serializer.KryoSerializer")
</code>```

答:
I found some info pointing to this being a bug in Kryo serialization:

https://github.com/EsotericSoftware/kryo/issues/382

It's fixed in Kryo 4, but spark is not yet using that version:

https://issues.apache.org/jira/browse/SPARK-20389

As a temporary work-around, sounds like this might help:

```<code>spark.executor.extraJavaOptions –XX:hashCode=0
spark.driver.extraJavaOptions –XX:hashCode=0
</code>```

(From https://github.com/broadinstitute/gatk/issues/1524#issuecomment-189368808)

Or you could simply use a different serializer, though that might slow things down.

Title: Spark NegativeArraySizeException

Body:
In a spark job I join two RDDs,

val data: RDD[(Long, (String, String))] = sc.objectFile[(Long, scala.collection.mutable.HashMap[String, Object])](outputFile)
  .leftOuterJoin(attributionData)

Here outputFile is output of another spark job which process data from hive. One of the tables in hive has 40 million records and when I limit to read table to fetch only 10 million records code works fine. However with full data (if I remove limit()) following error occurs,

10:43:27 WARN TaskSetManager: Lost task 0.0 in stage 1.0 (TID 2, buysub.com): java.lang.NegativeArraySizeException
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.resize(IdentityObjectIntMap.java:409)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.putStash(IdentityObjectIntMap.java:227)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.push(IdentityObjectIntMap.java:221)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.put(IdentityObjectIntMap.java:117)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.putStash(IdentityObjectIntMap.java:228)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.push(IdentityObjectIntMap.java:221)
at com.esotericsoftware.kryo.util.IdentityObjectIntMap.put(IdentityObjectIntMap.java:117)
at com.esotericsoftware.kryo.util.MapReferenceResolver.addWrittenObject(MapReferenceResolver.java:23)
at com.esotericsoftware.kryo.Kryo.writeReferenceOrNull(Kryo.java:598)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:566)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:224)
at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:403)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.immutable.List.foreach(List.scala:318)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.Tuple2Serializer.write(TupleSerializers.scala:37)
at com.twitter.chill.Tuple2Serializer.write(TupleSerializers.scala:33)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:29)
at com.twitter.chill.TraversableSerializer$$anonfun$write$1.apply(Traversable.scala:27)
at scala.collection.mutable.HashMap$$anonfun$foreach$1.apply(HashMap.scala:98)
at scala.collection.mutable.HashMap$$anonfun$foreach$1.apply(HashMap.scala:98)
at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:226)
at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:39)
at scala.collection.mutable.HashMap.foreach(HashMap.scala:98)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:27)
at com.twitter.chill.TraversableSerializer.write(Traversable.scala:21)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:568)

I am using Spark 1.6. Following is the spark configuration,

conf.set("spark.driver.memory", "4G")
conf.set("spark.executor.memory", "30G")
conf.set("spark.rdd.compress", "true")
conf.set("spark.storage.memoryFraction", "0.3")
conf.set("spark.shuffle.consolidateFiles", "true")
conf.set("spark.shuffle.memoryFraction", "0.5")
conf.set("spark.akka.frameSize", "384")
conf.set("spark.io.compression.codec", "lz4")
conf.set("spark.serializer","org.apache.spark.serializer.KryoSerializer")

Body:
I found some info pointing to this being a bug in Kryo serialization:

https://github.com/EsotericSoftware/kryo/issues/382

It's fixed in Kryo 4, but spark is not yet using that version:

https://issues.apache.org/jira/browse/SPARK-20389

As a temporary work-around, sounds like this might help:

spark.executor.extraJavaOptions –XX:hashCode=0
spark.driver.extraJavaOptions –XX:hashCode=0

(From https://github.com/broadinstitute/gatk/issues/1524#issuecomment-189368808)

Or you could simply use a different serializer, though that might slow things down.


问:
Regular expression to split a string but consider multi-digit escape sequences
I could need some help on the following problem with regular expressions and would appreciate any help, thanks in advance.

I have to split a string by another string, let me call it separator. However, if an escape sequence preceeds separatorString, the string should not be split at this point. The escape sequence is also a string, let me call it escapeSequence.

Maybe it is better to start with some examples

```<code>separatorString = "§§";

escapeSequence = "###";

inputString = "Part1§§Part2" ==> Desired output: "Part1", "Part2"
inputString = "Part1§§Part2§§ThisIs###§§AllPart3" ==> Desired output: "Part1", "Part2", "ThisIs###§§AllPart3"
</code>```

Searching stackoverflow, I found Splitting a string that has escape sequence using regular expression in Java and came up with the regular expression

"(?<!(###))§§".

This is basically saying, match if you find "§§", unless it is preceeded by "###".

This works fine with Regex.Split for the examples above, however, if inputString is "Part1###§§§§Part2" I receive "Part1###§", "§Part2" instead of "Part1###§§", "Part2".

I understand why, as the second "§" gives a match, because the proceeding chars are "##§" and not "###". I tried several hours to modify the regex, but the result got only worse. Does someone have an idea?

答:
Let's call the things that appear between the separators, tokens.  Your regex needs to stipulate what the beginning and end of a token looks like.

In the absence of any stipulation, in other words, using the regex you have now, the regex engine is happy to say that the first token is Part1###§ and the second is §Part2.

The syntax you used, (?<!foo) , is called a zero-width negative look-behind assertion. In other words, it looks behind the current match, and makes an assertion that it must match foo. Zero-width just indicates that the assertion does not advance the pointer or cursor in the subject string when the assertion is evaluated.

If you require that a new token start with something specific (say, an alphanumeric character), you can specify that with a zero-width positive lookahead assertion. It's similar to your lookbehind, but it says "the next bit has to match the following pattern", again without advancing the cursor or pointer.

To use it, put (?=[A-Z]) following the §§.  The entire regex for the separator is then

(?<!###)§§(?=[A-z]).

This would  assert that the character following a separator sequence needs to be an uppercase alpha, while the characters preceding the separator sequence must not be ###. In your  example, it would force the match on the §§ separator to be the pair of chars before Part2.  Then you would get Part1###§§ and Part2 as the tokens, or group captures.

If you want to stipulate what a token is in the negative - in other words to stipulate the a token begins with anything except a certain pattern, you can use a negative lookahead assertion.  The syntax for this is (?!foo).  It works just as you would expect - like your negative lookbehind, only looking forward.

The regular-expressions.info website has good explanations for all things regex, including for the lookahead and lookbehind constructs.

ps: it's "Hello All", not "Hello Together".

Body:
I could need some help on the following problem with regular expressions and would appreciate any help, thanks in advance.

I have to split a string by another string, let me call it separator. However, if an escape sequence preceeds separatorString, the string should not be split at this point. The escape sequence is also a string, let me call it escapeSequence.

Maybe it is better to start with some examples

separatorString = "§§";

escapeSequence = "###";

inputString = "Part1§§Part2" ==> Desired output: "Part1", "Part2"
inputString = "Part1§§Part2§§ThisIs###§§AllPart3" ==> Desired output: "Part1", "Part2", "ThisIs###§§AllPart3"

Searching stackoverflow, I found Splitting a string that has escape sequence using regular expression in Java and came up with the regular expression

"(?<!(###))§§".

This is basically saying, match if you find "§§", unless it is preceeded by "###".

This works fine with Regex.Split for the examples above, however, if inputString is "Part1###§§§§Part2" I receive "Part1###§", "§Part2" instead of "Part1###§§", "Part2".

I understand why, as the second "§" gives a match, because the proceeding chars are "##§" and not "###". I tried several hours to modify the regex, but the result got only worse. Does someone have an idea?


问:
how to change default language of SQL server management studio?
how to change default language of SQL server management studio?

I tried to change default language to french by using the below query.

```<code>USE ssidps;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
</code>```

but SELECT @@language gives "us_english" always.

答: Follow the images below to change the Management Studio default language:

Body:
how to change default language of SQL server management studio?

I tried to change default language to french by using the below query.

USE ssidps;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

but SELECT @@language gives "us_english" always.


问:
Access For Loop Hide Objects
I'm trying to hide/unhide around 30 objects on my form when the user selects certain values from a dropdown menu. I tried the loop below, however I receive the following error: 'Object doesn't support this property or method.' I have this code running on the 'AfterUpdate' of the dropdown menu object. </p>

```<code>Dim VisibleVisitFields() As String
Dim VisibleVisitFieldlist As String
Dim varVisibleVisit As Variant
VisibleVisitFieldlist = "VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event"
VisibleVisitFields = Split(VisibleVisitFieldlist, ",")

If (EventType = 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = True
    Exit For
Next
Else
If (EventType <> 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = False
    Exit For
Next
End If
End If
</code>```

答:
You are trying to iterate over an array of strings.

```<code>Dim VisibleVisitFields() As String
</code>```

You need to declare the array to contain variants (which can still contain strings)

```<code>Dim VisibleVisitFields() As Variant
</code>```

Title: Access For Loop Hide Objects

Body:
I'm trying to hide/unhide around 30 objects on my form when the user selects certain values from a dropdown menu. I tried the loop below, however I receive the following error: 'Object doesn't support this property or method.' I have this code running on the 'AfterUpdate' of the dropdown menu object.

Dim VisibleVisitFields() As String
Dim VisibleVisitFieldlist As String
Dim varVisibleVisit As Variant
VisibleVisitFieldlist = "VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event"
VisibleVisitFields = Split(VisibleVisitFieldlist, ",")

If (EventType = 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = True
    Exit For
Next
Else
If (EventType <> 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = False
    Exit For
Next
End If
End If

Body:
You are trying to iterate over an array of strings.

Dim VisibleVisitFields() As String

You need to declare the array to contain variants (which can still contain strings)

Dim VisibleVisitFields() As Variant


Title: Format date string using gawk?

Body:
I have an issue that when running this code:

gawk 'BEGIN{FS=";";RS="\r\n"}
        {
            for (i = 1; i <= NF; i++) {
                if(match($i, /([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/, m)){
                    $i =  m[1]"-"m[2]"-"m[3]" " m[4]":"m[5]":"m[6]
                    printf $0 "\n"
                }

            }
        }' contact20.txt > cleaned.txt

with input:

3;0952;2001-03-22-11.56.13.514119;2;2014-09-21-10.25.58.918626;J;2015-12-27-14.17.45.593190;N;0;0001-01-01-00.00.00.000000;N;2014-09-21-10.25.58.918626;2012-11-03-21.52.55.270989;N;0001-01-01-00.00.00.000000

I get:

3 0952 2001-03-22 11:56:13 2 2014-09-21-10.25.58.918626 J 2015-12-27-14.17.45.593190 N 0 0001-01-01-00.00.00.000000 N 2014-09-21-10.25.58.918626 2012-11-03-21.52.55.270989 N 0001-01-01-00.00.00.000000

But the result should look like this:

3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

I can't figure out why is removing the ; from the string and also is ignoring date strings like 0001-01-01-00.00.00.000000 and the match is only matching the first one?

What do I need to change to make work property?

Body:
You don't need a loop for that, all you need is:

$ gawk '{print gensub(/([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/,"\\1-\\2-\\3 \\4:\\5:\\6","g")}' file
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

which of course could just as easily be done with sed:

$ sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/\1-\2-\3 \4:\5:\6/g' file
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

The above uses GNU awk for gensub() and GNU or OSX sed for -E.


问:
Add select dropdown to table column with JS
I have created a table in HTML (4 rows and 3 columns). But I want to add a select dropdown in the second column. I am unable to add that in the column.

My code is:

```<code><!DOCTYPE html>
<html>
<body>

<table border="1" style="width:100%">
  <tr>
    <th>Criteria</th>
    <th>Yes/No</th>
    <th>Comments</th>
  </tr>
<script>

var array1 = [1,2,3,4];
for(var i=0; i<array1.length; i++)
{

document.write("<tr>");

document.write("<td>"+array1[i]+"</td>");
document.write("<td>  </td>");
document.write("<td>  </td>");

document.write("</tr>");

}
</script>
</table>
</body>
</html>
</code>```

And the select dropdown HTML is:

```<code><select name="mydropdown">
    <option value="Milk">Fresh Milk</option>
    <option value="Cheese">Old Cheese</option>
    <option value="Bread">Hot Bread</option>
</select>
</code>```

答:
This may help

<!DOCTYPE html>

      Criteria
      Yes/No
      Comments

```

Body:
I have created a table in HTML (4 rows and 3 columns). But I want to add a select dropdown in the second column. I am unable to add that in the column.

My code is:

<!DOCTYPE html>

    Criteria
    Yes/No
    Comments

And the select dropdown HTML is:

<select name="mydropdown">
    <option value="Milk">Fresh Milk</option>
    <option value="Cheese">Old Cheese</option>
    <option value="Bread">Hot Bread</option>
</select>

Body:
This may help

<!DOCTYPE html>
<html>

<body>

  <table border="1" style="width:100%">
    <tr>
      <th>Criteria</th>
      <th>Yes/No</th>
      <th>Comments</th>
    </tr>
    <script>
      var array1 = [1, 2, 3, 4];
      for (var i = 0; i < array1.length; i++) {

        var dropdown = "<select name='mydropdown'>" +
          "<option value='Milk'>Yes</option>" +
          "<option value='Cheese'>No</option>" +
          "</select>";

        document.write("<tr>");

        document.write("<td>" + array1[i] + "</td>");
        document.write("<td>" + dropdown + "</td>");
        document.write("<td>  </td>");

        document.write("</tr>");

      }
    </script>
  </table>
</body>

</html>


问:
Commander.js display help when called with no commands
I'm using commander.js to write a simple node.js program that interacts with an API. All calls require the use of subcommands. For example:

```<code>apicommand get
</code>```

Is called as follows:

```<code>program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount);
</code>```

What I want to do now is display a default message when apicommand is called without any subcommands. Just like when you call git without a subcommand:

```<code>MacBook-Air:Desktop username$ git
usage: git [--version] [--help] [-C <path>] [-c name=value]
       [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
       [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
       [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
       <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one
...
</code>```

答:
You can do something like this by checking what arguments were received and if nothing other than node and <app>.js then display the help text.

```<code>program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount)
  .parse(process.argv)

if (process.argv.length < 3) {
  program.help()
}
</code>```

Body:
I'm using commander.js to write a simple node.js program that interacts with an API. All calls require the use of subcommands. For example:

apicommand get

Is called as follows:

program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount);

What I want to do now is display a default message when apicommand is called without any subcommands. Just like when you call git without a subcommand:

MacBook-Air:Desktop username$ git
usage: git [--version] [--help] [-C <path>] [-c name=value]
       [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
       [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
       [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
       <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one
...

Body:
You can do something like this by checking what arguments were received and if nothing other than node and <app>.js then display the help text.

program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount)
  .parse(process.argv)

if (process.argv.length < 3) {
  program.help()
}


问:
Spring Resttemplate: Parsing using @JsonIgnore causes values to be null
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

```<code>{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}
</code>```

My class is set up like this, because for a start I only want to get the account id and name:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}
</code>```

and here's the way I try to call it:

```<code>        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);
</code>```

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.

答:
So, Christian Zieglers Comments and Answer is partially right.

You need to make sure your Class Structure can be mapped from the retrieved Json.

So, to make it work, the imho easiest way woud be, instead of creating a wrapper object:

Remove your @JsonIgnoreProperties Annotation. We'll do this with the object mapper.

Then, Add Jacksons @JsonRootName Property to your class PortalAccount and set the value to d. Your class now should only have this one annotation:

@JsonRootName(value = "d") like this:

```<code>@JsonRootName(value = "d")
public class PortalAccount implements Serializable{
    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    ...
}
</code>```

Now, when you call it, you have to set your Objectmapper (assuming jackson 2) to Unwrap your rootElement (and to ignore unknown properties) like this:

```<code>objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
</code>```

So your whole call would look like this:

```<code>RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);
</code>```

Important thing here is, as stated above, the @JsonRootName Property, because without it, the UNWRAP_ROOT_VALUE feature would not work.

Hope this helps!

Body:
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}

My class is set up like this, because for a start I only want to get the account id and name:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}

and here's the way I try to call it:

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.

Body:
So, Christian Zieglers Comments and Answer is partially right.

You need to make sure your Class Structure can be mapped from the retrieved Json.

So, to make it work, the imho easiest way woud be, instead of creating a wrapper object:

Remove your @JsonIgnoreProperties Annotation. We'll do this with the object mapper.

Then, Add Jacksons @JsonRootName Property to your class PortalAccount and set the value to d. Your class now should only have this one annotation:

@JsonRootName(value = "d") like this:

@JsonRootName(value = "d")
public class PortalAccount implements Serializable{
    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    ...
}

Now, when you call it, you have to set your Objectmapper (assuming jackson 2) to Unwrap your rootElement (and to ignore unknown properties) like this:

objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

So your whole call would look like this:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);

Important thing here is, as stated above, the @JsonRootName Property, because without it, the UNWRAP_ROOT_VALUE feature would not work.

Hope this helps!


问:
How to Align Bootstrap thumbnails horizontally
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

```<code><div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>
</code>```

And here's s screenshot how it is placed.

答:
Remove the
 divs and their corresponding end tags. Right now you are forcing them to a seperate "row" by using them, hence the vertical arrangement.

Body:
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

Software Name

...

Read More

Software Name

...

Read More

And here's s screenshot how it is placed.

Body: Remove the <div class="row"> divs and their corresponding end tags. Right now you are forcing them to a seperate "row" by using them, hence the vertical arrangement.


问:
How to Make a "Pixelated" Line in Java
I would like to draw a "pixelated" line in Java. Here is an example of what I mean by "pixelated" line:

This is my what my code is trying to do. Assume that the line is going from (x1, y1) to (x2, y2) and that I want a line of 10 "blocks" length between them (I would call them pixels but they will be displayed using many pixels):

Make a rectangle with (x1, y1) as (0, 0) and with width x2 - x1 and height y2 - y1.

Calculate the hypotenuse of the triangle formed by that rectangle. Call that cOriginal.

Rescale the rectangle so that the hypotenuse length is 10 long.

Create a 2D boolean array of the size of the rescaled rectangle. Call that grid.

Run the Bresenham Line Algorithm on that grid from top right corner, which is (0, 0) to the bottom left corner, marking grid spaces that are part of the line as true. I have assured that my Bresenham algorithm works in all quadrants and in all cases.

This is the part I'm a bit fuzzy on. Currently, I first define 2 variables that "scale up" the grid. These are defined as follows:

float widthScalingFactor = (float) widthOriginal / (float) newWidth;
float heightScalingFactor = (float) heightOriginal / (float) newHeight;

(I have no idea why thats not formatting...) Next I loop through grid and if grid[i][j] (is true), I draw a rectangle of width and height of 10 at (x1 + (i * widthScalingFactor), yOffset + (j * heightScalingFactor)).

Here is the current method:

```<code>public static void drawPixelatedLine(Graphics g, int x1, int y1, int x2, int y2) {

    int widthOriginal = x2 - x1;
    int heightOriginal = y2 - y1;

    if(widthOriginal <= 0 && heightOriginal <= 0){

        int temp = x2;
        x2 = x1;
        x1 = temp;

        temp = y2;
        y2 = y1;
        y1 = temp;

    }

    double cOriginal = Math.sqrt(widthOriginal * widthOriginal + heightOriginal * heightOriginal);

    double shrinkingFactor = 10d / cOriginal;

    int newWidth = (int) Math.round(shrinkingFactor * widthOriginal);
    int newHeight = (int) Math.round(shrinkingFactor * heightOriginal);

    newWidth = (newWidth <= 0 ? 1 : newWidth);
    newHeight = (newHeight <= 0 ? 1 : newHeight);

    boolean[][] grid = new boolean[newWidth][newHeight];

    int rescaledX1 = 0;
    int rescaledY1 = 0;

    int rescaledX2 = newWidth - 1;
    int rescaledY2 = newHeight - 1;

    int x = rescaledX1;
    int y = rescaledY1;

    int dx = Math.abs(rescaledX2 - rescaledX1);
    int dy = Math.abs(rescaledY2 - rescaledY1);

    int s1 = Utils.sign(rescaledX2 - rescaledX1);
    int s2 = Utils.sign(rescaledY2 - rescaledY1);

    boolean swap = false;

    if (dy > dx) {

        int temp = dx;
        dx = dy;
        dy = temp;

        swap = true;

    }

    int D = 2 * dy - dx;

    for (int i = 0; i < dx; i += 1) {

        grid[x][y] = true;

        while (D >= 0) {

            D = D - 2 * dx;

            if (swap) {

                x += s1;

            }

            else {

                y += s2;

            }

        }

        D = D + 2 * dy;

        if (swap) {

            y += s2;

        }

        else {

            x += s1;

        }

    }

    int xOffset = x1;
    int yOffset = y1;

    float widthScalingFactor = (float) widthOriginal / (float) newWidth;
    float heightScalingFactor = (float) heightOriginal / (float) newHeight;

    for(int i = 0; i < grid.length; i++){

        for(int j = 0; j < grid[0].length; j++){

            if(grid[i][j]){

                g.fillRect((int) (xOffset + (i * widthScalingFactor)), (int) (yOffset + (j * heightScalingFactor)), 10, 10);

            }

        }

    }
</code>```

Right now this code partially works when drawing in any cardinal direction and northwest and southeast, although the size of the rectangles I am drawing seem to be wrong (this is likely because I am trying to draw 10 squares of size 10 across a distance that is likely more than ~140 pixels. However, when I try to draw a line northeast or southwest, it just draws a horizontal line. Here are some examples.

This is a line going northwest and working properly (I can fix the whole stretching/gaps issue).

Here is a line that is going northeast and as you can see it is simply just a straight line going east from the origin to the x position of the destination. A similar thing happens when drawing lines southwest except it goes south and stops at the destination's y position.

Currently as you can see if the line is going northwest I just flip the 2 points around so it is going southeast. However, I feel that my current approach isn't quite right and would require a lot of modification just to accommodate the last 2 cases.

How could I modify my current algorithm or make a new one to draw a "pixelated" line?

答:
This code demonstrates an approach where all coordinates are scaled to a lower resoultion, then the line is drawn in the lower resolution while scaling up again in the plot(x, y) function.

The obvious side effect is that the lines endpoints are subject to rounding (actually truncating) to the lower resolution.

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BresenhamBlocky {

    static class TestPanel extends JPanel {
        public TestPanel() {
            setPreferredSize(new Dimension(800, 800));
        }

        @Override
        protected void paintComponent(final Graphics g) {
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            g.setColor(Color.GRAY);
            g.fillRect(0, 0, w, h);
            g.setColor(Color.BLUE);
            drawLine(g, w >> 1, h >> 1, targetX, targetY, 10);
        }
    }

    public static void main(String[] argv) {
        SwingUtilities.invokeLater(() -> { showTest(); });
    }

    static int targetX, targetY;

    static void showTest() {
        JFrame frame = new JFrame("Test");
        JComponent test = new TestPanel();
        test.setFocusable(true);
        test.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                targetX = e.getX();
                targetY = e.getY();
                e.getComponent().repaint();
            }
        });
        frame.setLayout(new BorderLayout());
        frame.add(test, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void drawLine(Graphics g, int x0, int y0, int x1, int y1, int blockSize) {
        int scaledX0 = x0 / blockSize;
        int scaledY0 = y0 / blockSize;
        int scaledX1 = x1 / blockSize;
        int scaledY1 = y1 / blockSize;
        int dx = scaledX1 - scaledX0;
        int dy = scaledY1 - scaledY0;
        int stepX = Integer.signum(dx);
        int stepY = Integer.signum(dy);
        dx = Math.abs(dx);
        dy = Math.abs(dy);
        int dx2 = dx << 1;
        int dy2 = dy << 1;
        int x = scaledX0;
        int y = scaledY0;
        int error;
        if (dx >= dy) {
            error = dy2 - dx;
            do {
                plot(g, x, y, blockSize);
                if (error > 0) {
                    y += stepY;
                    error -= dx2;
                }
                error += dy2;
                x += stepX;
            } while (x != scaledX1);
        } else {
            error = dx2 - dy;
            do {
                plot(g, x, y, blockSize);
                if (error > 0) {
                    x += stepX;
                    error -= dy2;
                }
                error += dx2;
                y += stepY;
            } while (y != scaledY1);
        }
    }

    static void plot(Graphics g, int x, int y, int blockSize) {
        int x0 = x * blockSize;
        int y0 = y * blockSize;
        int w = blockSize;
        int h = blockSize;
        g.fillRect(x0, y0, w, h);
    }

}
</code>```

(Use mouse click to move one endpoint of the line)

Title: How to Make a "Pixelated" Line in Java

Body:
I would like to draw a "pixelated" line in Java. Here is an example of what I mean by "pixelated" line:

This is my what my code is trying to do. Assume that the line is going from (x1, y1) to (x2, y2) and that I want a line of 10 "blocks" length between them (I would call them pixels but they will be displayed using many pixels):

Make a rectangle with (x1, y1) as (0, 0) and with width x2 - x1 and height y2 - y1.

Calculate the hypotenuse of the triangle formed by that rectangle. Call that cOriginal.

Rescale the rectangle so that the hypotenuse length is 10 long.

Create a 2D boolean array of the size of the rescaled rectangle. Call that grid.

Run the Bresenham Line Algorithm on that grid from top right corner, which is (0, 0) to the bottom left corner, marking grid spaces that are part of the line as true. I have assured that my Bresenham algorithm works in all quadrants and in all cases.

This is the part I'm a bit fuzzy on. Currently, I first define 2 variables that "scale up" the grid. These are defined as follows:

float widthScalingFactor = (float) widthOriginal / (float) newWidth;
float heightScalingFactor = (float) heightOriginal / (float) newHeight;

(I have no idea why thats not formatting...) Next I loop through grid and if grid[i][j] (is true), I draw a rectangle of width and height of 10 at (x1 + (i * widthScalingFactor), yOffset + (j * heightScalingFactor)).

Here is the current method:

public static void drawPixelatedLine(Graphics g, int x1, int y1, int x2, int y2) {

    int widthOriginal = x2 - x1;
    int heightOriginal = y2 - y1;

    if(widthOriginal <= 0 && heightOriginal <= 0){

        int temp = x2;
        x2 = x1;
        x1 = temp;

        temp = y2;
        y2 = y1;
        y1 = temp;

    }

    double cOriginal = Math.sqrt(widthOriginal * widthOriginal + heightOriginal * heightOriginal);

    double shrinkingFactor = 10d / cOriginal;

    int newWidth = (int) Math.round(shrinkingFactor * widthOriginal);
    int newHeight = (int) Math.round(shrinkingFactor * heightOriginal);

    newWidth = (newWidth <= 0 ? 1 : newWidth);
    newHeight = (newHeight <= 0 ? 1 : newHeight);

    boolean[][] grid = new boolean[newWidth][newHeight];

    int rescaledX1 = 0;
    int rescaledY1 = 0;

    int rescaledX2 = newWidth - 1;
    int rescaledY2 = newHeight - 1;

    int x = rescaledX1;
    int y = rescaledY1;

    int dx = Math.abs(rescaledX2 - rescaledX1);
    int dy = Math.abs(rescaledY2 - rescaledY1);

    int s1 = Utils.sign(rescaledX2 - rescaledX1);
    int s2 = Utils.sign(rescaledY2 - rescaledY1);

    boolean swap = false;

    if (dy > dx) {

        int temp = dx;
        dx = dy;
        dy = temp;

        swap = true;

    }

    int D = 2 * dy - dx;

    for (int i = 0; i < dx; i += 1) {

        grid[x][y] = true;

        while (D >= 0) {

            D = D - 2 * dx;

            if (swap) {

                x += s1;

            }

            else {

                y += s2;

            }

        }

        D = D + 2 * dy;

        if (swap) {

            y += s2;

        }

        else {

            x += s1;

        }

    }

    int xOffset = x1;
    int yOffset = y1;

    float widthScalingFactor = (float) widthOriginal / (float) newWidth;
    float heightScalingFactor = (float) heightOriginal / (float) newHeight;

    for(int i = 0; i < grid.length; i++){

        for(int j = 0; j < grid[0].length; j++){

            if(grid[i][j]){

                g.fillRect((int) (xOffset + (i * widthScalingFactor)), (int) (yOffset + (j * heightScalingFactor)), 10, 10);

            }

        }

    }

Right now this code partially works when drawing in any cardinal direction and northwest and southeast, although the size of the rectangles I am drawing seem to be wrong (this is likely because I am trying to draw 10 squares of size 10 across a distance that is likely more than ~140 pixels. However, when I try to draw a line northeast or southwest, it just draws a horizontal line. Here are some examples.

This is a line going northwest and working properly (I can fix the whole stretching/gaps issue).

Here is a line that is going northeast and as you can see it is simply just a straight line going east from the origin to the x position of the destination. A similar thing happens when drawing lines southwest except it goes south and stops at the destination's y position.

Currently as you can see if the line is going northwest I just flip the 2 points around so it is going southeast. However, I feel that my current approach isn't quite right and would require a lot of modification just to accommodate the last 2 cases.

How could I modify my current algorithm or make a new one to draw a "pixelated" line?

Body:
This code demonstrates an approach where all coordinates are scaled to a lower resoultion, then the line is drawn in the lower resolution while scaling up again in the plot(x, y) function.

The obvious side effect is that the lines endpoints are subject to rounding (actually truncating) to the lower resolution.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BresenhamBlocky {

    static class TestPanel extends JPanel {
        public TestPanel() {
            setPreferredSize(new Dimension(800, 800));
        }

        @Override
        protected void paintComponent(final Graphics g) {
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            g.setColor(Color.GRAY);
            g.fillRect(0, 0, w, h);
            g.setColor(Color.BLUE);
            drawLine(g, w >> 1, h >> 1, targetX, targetY, 10);
        }
    }

    public static void main(String[] argv) {
        SwingUtilities.invokeLater(() -> { showTest(); });
    }

    static int targetX, targetY;

    static void showTest() {
        JFrame frame = new JFrame("Test");
        JComponent test = new TestPanel();
        test.setFocusable(true);
        test.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                targetX = e.getX();
                targetY = e.getY();
                e.getComponent().repaint();
            }
        });
        frame.setLayout(new BorderLayout());
        frame.add(test, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void drawLine(Graphics g, int x0, int y0, int x1, int y1, int blockSize) {
        int scaledX0 = x0 / blockSize;
        int scaledY0 = y0 / blockSize;
        int scaledX1 = x1 / blockSize;
        int scaledY1 = y1 / blockSize;
        int dx = scaledX1 - scaledX0;
        int dy = scaledY1 - scaledY0;
        int stepX = Integer.signum(dx);
        int stepY = Integer.signum(dy);
        dx = Math.abs(dx);
        dy = Math.abs(dy);
        int dx2 = dx << 1;
        int dy2 = dy << 1;
        int x = scaledX0;
        int y = scaledY0;
        int error;
        if (dx >= dy) {
            error = dy2 - dx;
            do {
                plot(g, x, y, blockSize);
                if (error > 0) {
                    y += stepY;
                    error -= dx2;
                }
                error += dy2;
                x += stepX;
            } while (x != scaledX1);
        } else {
            error = dx2 - dy;
            do {
                plot(g, x, y, blockSize);
                if (error > 0) {
                    x += stepX;
                    error -= dy2;
                }
                error += dx2;
                y += stepY;
            } while (y != scaledY1);
        }
    }

    static void plot(Graphics g, int x, int y, int blockSize) {
        int x0 = x * blockSize;
        int y0 = y * blockSize;
        int w = blockSize;
        int h = blockSize;
        g.fillRect(x0, y0, w, h);
    }

}

(Use mouse click to move one endpoint of the line)


问:
Returning unique_ptr which is function parameter
I have the following method:

```<code>std::unique_ptr<Req> RequestConverter::SetReg(
    const std::unique_ptr<Req> pb_req, ...) {
</code>```

I want to return parameter pb_req from the above method.
I get this error (with or without std::move):

```<code>error: call to deleted constructor of 'std::unique_ptr<Req>'
</code>```

What's recommended approach ?

Thanks

答:
The unique_ptr copy constructor is marked as deleted, i.e. the following

```<code>unique_ptr(const unique_ptr&) = delete;
</code>```

And when you return a const unique_ptr<Req> from your function, the return value is treated as an rvalue, and therefore the exact match for a constructor if available would be

```<code>unique_ptr(const unique_ptr&&);
</code>```

The move constructor does not match const unique_ptr<Req>&& because it requires a non const rvalue reference.  And so the closest match is the copy constructor which is deleted, therefore this does not work.

But the question you should be asking yourself is, why do you want to mark the unique_ptr to be const in the first place?  A const unique_ptr means that the pointer is const, and not the pointed to thing.  If you want a unique_ptr to const, you should do unique_ptr<const Req> instead.

Body:
I have the following method:

std::unique_ptr<Req> RequestConverter::SetReg(
    const std::unique_ptr<Req> pb_req, ...) {

I want to return parameter pb_req from the above method.
I get this error (with or without std::move):

error: call to deleted constructor of 'std::unique_ptr<Req>'

What's recommended approach ?

Thanks

Body:
The unique_ptr copy constructor is marked as deleted, i.e. the following

unique_ptr(const unique_ptr&) = delete;

And when you return a const unique_ptr<Req> from your function, the return value is treated as an rvalue, and therefore the exact match for a constructor if available would be

unique_ptr(const unique_ptr&&);

The move constructor does not match const unique_ptr<Req>&& because it requires a non const rvalue reference.  And so the closest match is the copy constructor which is deleted, therefore this does not work.

But the question you should be asking yourself is, why do you want to mark the unique_ptr to be const in the first place?  A const unique_ptr means that the pointer is const, and not the pointed to thing.  If you want a unique_ptr to const, you should do unique_ptr<const Req> instead.


问:
SVN post commit hook not working?
Navigate to TortoiseSVN on mine local box, open settings and 'Hook Scripts'. Click 'Add...' and entered below values

Hook Type
post_commit_hook

Working Copy Path
https:\svn.internal.net\svn\Release_Customer

Command Line to Execute
C:\postCommitHook.bat

postCommitHook.bat file content is

```<code>"C:\Program Files\TortoiseSVN\bin\svnlook.exe" log -t %2 %1 | FindStr [a-zA-Z0-9]
IF %ERRORLEVEL% EQU 0 GOTO OK
echo "Commit Comments are Required" >&2
exit 1
:OK
exit 0
</code>```

But when I commit from my local box code(pointing To https:\svn.internal.net\svn\Release_Customer) without any comment, i am still able to commit. Why my
postCommitHook.bat is restricting it ?

Basically i an trying add the restriction to svn repo(https:\\svn.internal.net\svn\Release_Customer) where as batch script is lying on local box. Is it fine ?

答:
You have two issues:

If you want to block a commit from happening, it must happen in the pre-commit hook script. The post-commit hook executes after a successful commit, which is not helpful for your use case.

The hook you've configured is local only to your computer, and for commits performed via TortoiseSVN. To install a hook script in the repository, you need an appropriate level of access to the filesystem on your SVN server itself, to place it in the hooks directory of the repository database itself. More info in the manual

Title: SVN post commit hook not working?

Body:
Navigate to TortoiseSVN on mine local box, open settings and 'Hook Scripts'. Click 'Add...' and entered below values

Hook Type
post_commit_hook

Working Copy Path
https:\svn.internal.net\svn\Release_Customer

Command Line to Execute
C:\postCommitHook.bat

postCommitHook.bat file content is

"C:\Program Files\TortoiseSVN\bin\svnlook.exe" log -t %2 %1 | FindStr [a-zA-Z0-9]
IF %ERRORLEVEL% EQU 0 GOTO OK
echo "Commit Comments are Required" >&2
exit 1
:OK
exit 0

But when I commit from my local box code(pointing To https:\svn.internal.net\svn\Release_Customer) without any comment, i am still able to commit. Why my
postCommitHook.bat is restricting it ?

Basically i an trying add the restriction to svn repo(https:\\svn.internal.net\svn\Release_Customer) where as batch script is lying on local box. Is it fine ?


问:
ruby hash block in ': undefined method `[]='
This works using the hash.update method:

```<code>[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a.update(i => i) }
</code>```

But this snippet using a[i] = i:

```<code>[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i }
</code>```

Results in the following error:

```<code><code>NoMethodError: undefined method \`[]=' for 4:Integer
Did you mean?  []
    from (irb):1:in \`block in irb_binding'>
    from (irb):1:in \`each'
    from (irb):1:in \`inject'
    from (irb):1
</code>
</code>```

Would someone please explain to me why I get this error? Thanks.

答:
Block of inject/reduce must return the new value of accumulator (see @ilya's answer). For some operations this happens naturally, for some - not so much. For those, I prefer each_with_object which handles tracking of the accumulator.

```<code>[4, 8, 15, 16, 23, 42].each_with_object({}) { |i, memo| memo[i] = i }
</code>```

(note that block arguments are in another order here)

Bonus

Don't know if you really want to achieve that transformation or it's just a sample code, but if you do, here's another way to do that:

```<code>ary = [4, 8, 15, 16, 23, 42]
ary.zip(ary).to_h
# => {4=>4, 8=>8, 15=>15, 16=>16, 23=>23, 42=>42}
</code>```

Title: ruby hash block in <main>': undefined method `[]='

Body:
This works using the hash.update method:

[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a.update(i => i) }

But this snippet using a[i] = i:

[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i }

Results in the following error:

NoMethodError: undefined method \`[]=' for 4:Integer
Did you mean?  []
    from (irb):1:in \`block in irb_binding'>
    from (irb):1:in \`each'
    from (irb):1:in \`inject'
    from (irb):1

Would someone please explain to me why I get this error? Thanks.

Body:
Block of inject/reduce must return the new value of accumulator (see @ilya's answer). For some operations this happens naturally, for some - not so much. For those, I prefer each_with_object which handles tracking of the accumulator.

[4, 8, 15, 16, 23, 42].each_with_object({}) { |i, memo| memo[i] = i }

(note that block arguments are in another order here)

Bonus

Don't know if you really want to achieve that transformation or it's just a sample code, but if you do, here's another way to do that:

ary = [4, 8, 15, 16, 23, 42]
ary.zip(ary).to_h
# => {4=>4, 8=>8, 15=>15, 16=>16, 23=>23, 42=>42}


问:
Check if current_user is included in active record relation
I am making an application using Ruby on Rails. I have a reservation model that has_many participants.

What I want to do is something like this:

```<code>Reservation.all.where("participants include ?", current_user)
</code>```

Is it possible to do this and how?

I know I can switch it around and do:

```<code>current_user.reservations_as_participant
</code>```

But, I am wondering if the other way around is also possible.

答:
Something like this should work:

Reservation.joins(:participants).where(participants: { id: current_user.id })
```

Body:
I am making an application using Ruby on Rails. I have a reservation model that has_many participants.

What I want to do is something like this:

Reservation.all.where("participants include ?", current_user)

Is it possible to do this and how?

I know I can switch it around and do:

current_user.reservations_as_participant

But, I am wondering if the other way around is also possible.


问:
Ext js how to pair checkbox & textfield?
I have a fieldset with textfield checkbox pairs, how do i align them in rows so that i have like below, thanks in advance.</p>

```<code>   [CHECKBOX] [TEXTBOX]
   [CHECKBOX] [TEXTBOX]
   [CHECKBOX] [TEXTBOX]
</code>```

答:
You should use fieldContainer with layout: 'hbox' configuration.

For example:

```<code>var formConfig = {
    xtype: 'form'
    // Your form configuration here
    items: [
        {
            xtype: 'fieldcontainer',
            fieldLabel: 'My pair label', // If you want a label for both fields, or you can put fieldLabel to either/both/none fields
            layout: {
                type: 'hbox',
                align: 'middle', // or any other align of your choosing
            },
            items: [
                {
                    xtype: 'checkbox',
                    // your checkbox configuration here, i.e. hideLabel: true or fieldLabel: 'checkbox label'
                },
                {
                    xtype: 'textfield',
                    // your textfield configuration here
                }
            ]
        }
    ]
}
</code>```

Body:
I have a fieldset with textfield checkbox pairs, how do i align them in rows so that i have like below, thanks in advance.

   [CHECKBOX] [TEXTBOX]
   [CHECKBOX] [TEXTBOX]
   [CHECKBOX] [TEXTBOX]

Body:
You should use fieldContainer with layout: 'hbox' configuration.

For example:

var formConfig = {
    xtype: 'form'
    // Your form configuration here
    items: [
        {
            xtype: 'fieldcontainer',
            fieldLabel: 'My pair label', // If you want a label for both fields, or you can put fieldLabel to either/both/none fields
            layout: {
                type: 'hbox',
                align: 'middle', // or any other align of your choosing
            },
            items: [
                {
                    xtype: 'checkbox',
                    // your checkbox configuration here, i.e. hideLabel: true or fieldLabel: 'checkbox label'
                },
                {
                    xtype: 'textfield',
                    // your textfield configuration here
                }
            ]
        }
    ]
}


问:
deleting datas in the table in GUI
I have question that how can I delete all datas from my jTable in GUI when a user entered a key?
thanks</p>

答:
If you are using the DefaultTableModel then you can just use:

```<code>model.setRowCount(0);
</code>```

This is better than creating a new DefaultTableModel. Creating a new TableModel causes the TableColumnModel to be recreated, which means all the TableColumns will be resize to default values and recreated in the order in which the columns exist in the model. The user may have changed these properties and shouldn't be forced to do it again.

If you are just deleting certain rows that contain a particulsar value, then you can use the DefaultTableModel.removeRow(...) method. Make sure you start by deleting row from the end of the model and count down to 0.

Title: deleting datas in the table in GUI

Body:
If you are using the DefaultTableModel then you can just use:

model.setRowCount(0);

This is better than creating a new DefaultTableModel. Creating a new TableModel causes the TableColumnModel to be recreated, which means all the TableColumns will be resize to default values and recreated in the order in which the columns exist in the model. The user may have changed these properties and shouldn't be forced to do it again.

If you are just deleting certain rows that contain a particulsar value, then you can use the DefaultTableModel.removeRow(...) method. Make sure you start by deleting row from the end of the model and count down to 0.


问:
Difference between onload() and $.ready?
Can you list the difference between onload() and $(document).ready(function(){..}) functions in the using jQuery?

答:
Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.

$.ready simply check if we have read the full DOM of the page.

Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/