问:
How to replace Column char(10) to int auto_increment in SQL 2008 table?
I'm working on the project where one of my tables used Fox Pro in the past. They have used server side programming language (ColdFusion) to create unique ID for each record in the table. With SQL auto increment field I don't need this technique and I would like to set my key column to INT auto increment. I was wondering what is the best way to modify key column in my table? Here is example of my table design:

```<code>Column Name  Data Type  Allow Nulls
im_key       char(10)   No
</code>```

I can't simply change the type to INT and set auto increment because my current type is char. If anyone can help please let me know. Thank you.

答:
You can add a new column im_key_ident, set it as identity. Rename the old column: sp_rename 'table_name.im_key', 'im_key_old', 'COLUMN';. Finally, you can rename the new column: sp_rename 'table_name.im_key_ident', 'im_key', 'COLUMN';. You can choose to keep or to drop the old column.

If the im_key column is currently used as primary key, foreign key, in functions, procedures or in any other way, it will become very cumbersome, very fast...

Body:
I'm working on the project where one of my tables used Fox Pro in the past. They have used server side programming language (ColdFusion) to create unique ID for each record in the table. With SQL auto increment field I don't need this technique and I would like to set my key column to INT auto increment. I was wondering what is the best way to modify key column in my table? Here is example of my table design:

Column Name  Data Type  Allow Nulls
im_key       char(10)   No

I can't simply change the type to INT and set auto increment because my current type is char. If anyone can help please let me know. Thank you.


来源: stackexchange

问:
Is Stripe Checking Customer Card or Source is Valid, After I changed it?
My question is Stripe handling customer card is valid or not. Do I have to try my own 1$ payment. And if stripe checking it how I will get informed. I am always using 424242.. test card soo it always saves card succesfuly.</p>

答:
4242 4242 4242 4242 is a VISA test card that charges a card in the test scenario. There are plenty of edge cases and failed card payments that you could try out. They provide different card number for this

For more information please follow Stripe's documentation

https://stripe.com/docs/testing

ContentLicense: CC BY-SA 3.0


问:
Passing cmdline arguments that have quotes in them
I'm trying to create a ruby script that will run the following command:

```<code>UV4.exe -j0 -cr test.uvprojx -t"test"
</code>```

I've tried to use Open3.capture3 as:

```<code>Open3.capture3("UV4.exe", '-j0', '-cr', 'test.uvprojx', '-t"test"')
</code>```

The problem I am experiencing is that the last argument becomes

```<code>"-t\"test\""
</code>```

which leads to an error for UV4 (Keil uVision IDE). If I try and escape the quotes I get

```<code>"-t\\\"test\\\""
</code>```

which is also obviously wrong.

How can I get the last argument correct?

答:
TL;DR – use '-ttest' instead of '-t"test"' in Ruby.

If you type

```<code>$ cmd -t"foo"
</code>```

at the command line, the quotes are not being passed to cmd. Instead, cmd receives a single argument -tfoo. It's equivalent to:

```<code>$ cmd -tfoo
</code>```

But if you type:

```<code>$ cmd -tfoo bar
</code>```

then cmd receives two arguments: -tfoo and bar because of the space in-between.

To avoid that, you have to escape the space somehow. All of these (and many more) would work:

```<code>$ cmd -tfoo\ bar
$ cmd -t"foo bar"
$ cmd "-tfoo bar"
</code>```

With any of the above, cmd receives a single argument -tfoo bar.

In Ruby on the other hand, capture3 will handle this for you, so no quotes are needed. You simply pass the command line arguments as separate method arguments:

```<code>Open3.capture3('cmd', '-tfoo bar')     #  $ cmd -tfoo bar
Open3.capture3('cmd', '-tfoo', 'bar')  #  $ cmd -tfoo\ bar
</code>```

If you add " Ruby assumes that you want to pass that character literally:

```<code>Open3.capture3('cmd', '-t"foo bar"')
</code>```

is equivalent to:

```<code>$ cmd -t'"foo bar"'
</code>```

cmd receives a single argument -t"foo bar", including the quotation characters.

Body:
I'm trying to create a ruby script that will run the following command:

UV4.exe -j0 -cr test.uvprojx -t"test"

I've tried to use Open3.capture3 as:

Open3.capture3("UV4.exe", '-j0', '-cr', 'test.uvprojx', '-t"test"')

The problem I am experiencing is that the last argument becomes

"-t\"test\""

which leads to an error for UV4 (Keil uVision IDE). If I try and escape the quotes I get

"-t\\\"test\\\""

which is also obviously wrong.

How can I get the last argument correct?

Body:
TL;DR – use '-ttest' instead of '-t"test"' in Ruby.

If you type

$ cmd -t"foo"

at the command line, the quotes are not being passed to cmd. Instead, cmd receives a single argument -tfoo. It's equivalent to:

$ cmd -tfoo

But if you type:

$ cmd -tfoo bar

then cmd receives two arguments: -tfoo and bar because of the space in-between.

To avoid that, you have to escape the space somehow. All of these (and many more) would work:

$ cmd -tfoo\ bar
$ cmd -t"foo bar"
$ cmd "-tfoo bar"

With any of the above, cmd receives a single argument -tfoo bar.

In Ruby on the other hand, capture3 will handle this for you, so no quotes are needed. You simply pass the command line arguments as separate method arguments:

Open3.capture3('cmd', '-tfoo bar')     #  $ cmd -tfoo bar
Open3.capture3('cmd', '-tfoo', 'bar')  #  $ cmd -tfoo\ bar

If you add " Ruby assumes that you want to pass that character literally:

Open3.capture3('cmd', '-t"foo bar"')

is equivalent to:

$ cmd -t'"foo bar"'

cmd receives a single argument -t"foo bar", including the quotation characters.


问:
Query for xml values in sql server
I have xml field in the below table in Data column

ID | website | Data

Following is the xml field

```<code><Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>
</code>```

I need to retrieve all the IsCustomer values in my table.

Following is the code part that I tried so far.

```<code>SELECT EMP.ED.value() as EmployeeID
FROM   [dbo].[Products]
CROSS APPLY Data.nodes('/Product/Field[@Name="IsCustomer"]/Boolean') as EMP(ED)
</code>```

Can anyone please help me?

答:
First of all: XML is strictly case sensitive! Your XML is not even valid... The leading <Product> is another element-name then the closing </product>. As you seem to use lower letters in all places, I changed it this way.

Your own query is close, but wrong with some capital letters and you did not use the .value()-function properly (missing paramters).

Try this:

```<code>DECLARE @mockup TABLE(ID INT IDENTITY,Descr VARCHAR(100),Data XML);
INSERT INTO @mockup VALUES
('Your Sample','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>')
,('Your sample plus another field','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
 <field name="SomeOther" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
</product>')
,('No "IsCustomer" at all','<product>
 <field name="SomeOther" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
</product>')
,('Two of them','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>');

SELECT * FROM @mockup;
</code>```

--Your query returning various variants, one of them should be okay for you:

```<code>SELECT m.ID
      ,m.Descr
      ,fld.value('(boolean/text())[1]','bit')
FROM @mockup AS m
OUTER APPLY m.Data.nodes('/product/field[@name="IsCustomer"]') AS A(fld);
</code>```

Title: Query for xml values in sql server

Body:
I have xml field in the below table in Data column

ID | website | Data

Following is the xml field

<Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>

I need to retrieve all the IsCustomer values in my table.

Following is the code part that I tried so far.

SELECT EMP.ED.value() as EmployeeID
FROM   [dbo].[Products]
CROSS APPLY Data.nodes('/Product/Field[@Name="IsCustomer"]/Boolean') as EMP(ED)

Can anyone please help me?

Body:
First of all: XML is strictly case sensitive! Your XML is not even valid... The leading <Product> is another element-name then the closing </product>. As you seem to use lower letters in all places, I changed it this way.

Your own query is close, but wrong with some capital letters and you did not use the .value()-function properly (missing paramters).

Try this:

DECLARE @mockup TABLE(ID INT IDENTITY,Descr VARCHAR(100),Data XML);
INSERT INTO @mockup VALUES
('Your Sample','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>')
,('Your sample plus another field','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
 <field name="SomeOther" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
</product>')
,('No "IsCustomer" at all','<product>
 <field name="SomeOther" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
</product>')
,('Two of them','<product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>true</boolean>
  </field>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>');

SELECT * FROM @mockup;

--Your query returning various variants, one of them should be okay for you:

SELECT m.ID
      ,m.Descr
      ,fld.value('(boolean/text())[1]','bit')
FROM @mockup AS m
OUTER APPLY m.Data.nodes('/product/field[@name="IsCustomer"]') AS A(fld);


问:
Creat 3d plot- equation (2 paramenters) time dependent ? matlab
I have an equation
 Z=aexp(kt)
Is there any way to "plot" the result "Z" in function of variation on the parameters "k" and "a" AND along time??
 or to make a surface..Or I´ll always have to fixate on of the parameters?
cheers

答:
Here is a basic example with color coding the time axis

```<code>clear;close all;clc;

t=0:0.02:0.2;
k = 0:10;
a = 0:100;
[x, y] = meshgrid(k, a);

figure;
colorList = colormap(jet);
hold on;
for ii=1:numel(t)
    z=y.*exp(x.*t(ii));
    h = surf(x, y, z);
    set(h,'edgecolor','none','FaceColor',colorList(5*ii,:),'FaceAlpha',0.5);
end
hold off;

legend(cellstr(num2str(t', 't=%.2f')), 'location', 'northwest')
view([45 30]);
xlabel('k');
ylabel('a');
zlabel('Z');
</code>```

and the result

Body:
Here is a basic example with color coding the time axis

clear;close all;clc;

t=0:0.02:0.2;
k = 0:10;
a = 0:100;
[x, y] = meshgrid(k, a);

figure;
colorList = colormap(jet);
hold on;
for ii=1:numel(t)
    z=y.*exp(x.*t(ii));
    h = surf(x, y, z);
    set(h,'edgecolor','none','FaceColor',colorList(5*ii,:),'FaceAlpha',0.5);
end
hold off;

legend(cellstr(num2str(t', 't=%.2f')), 'location', 'northwest')
view([45 30]);
xlabel('k');
ylabel('a');
zlabel('Z');

and the result


问:
PHP: is_array on $arr['key'] with non existing 'key'
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

```<code>if ( is_array ($arr['key']))
</code>```

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

答:
Try:</p>

```<code>is_array($arr) && array_key_exists('key', $arr)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

if ( is_array ($arr['key']))

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

Body:
Try:

is_array($arr) && array_key_exists('key', $arr)


问:
Autoscrolling infinite effect in .linear type of iCarousel in swift
I need infinite autoscrolling effect in .linear type in iCarousel and i already achieve autoscrolling in .cylinder type but i can't achieve this effect in .linear type.

Here is my code of achieve autoscrolling in .cylinder type

```<code>carousel.type = .linear
</code>```

carousel.autoscroll = -0.4;

```<code>carousel.reloadData()
</code>```

答:
Yes, this does not work carousel.type = .linear in the case of linear so you have to make an own timer for scrolling just like that:

```<code>self.timer = NSTimer.scheduledTimerWithTimeInterval(6, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)

func handleTimer(){

    if itemsScroll.count != 0{
        if itemsScroll.count-1 == index{
           index = 0
        }
        else {
           index += 1
        }
    }
    let x = CGFloat(index)
    if index == 0 {
       carousel.scrollToOffset(x, duration: 0)
    }
    else {
       carousel.scrollToOffset(x, duration: 2)
    }
}
</code>```

The index is used to get the current data for the carousel data source.

Body:
I need infinite autoscrolling effect in .linear type in iCarousel and i already achieve autoscrolling in .cylinder type but i can't achieve this effect in .linear type.

Here is my code of achieve autoscrolling in .cylinder type

carousel.type = .linear

carousel.autoscroll = -0.4;

carousel.reloadData()

Body:
Yes, this does not work carousel.type = .linear in the case of linear so you have to make an own timer for scrolling just like that:

self.timer = NSTimer.scheduledTimerWithTimeInterval(6, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)

func handleTimer(){

    if itemsScroll.count != 0{
        if itemsScroll.count-1 == index{
           index = 0
        }
        else {
           index += 1
        }
    }
    let x = CGFloat(index)
    if index == 0 {
       carousel.scrollToOffset(x, duration: 0)
    }
    else {
       carousel.scrollToOffset(x, duration: 2)
    }
}

The index is used to get the current data for the carousel data source.


问:
How to create DateTimeformatter with optional seconds arguments
I am trying to create a DateTimeformatter to validate following date times:

```<code>String date1 = "2017-07-06T17:25:28";
String date2 = "2017-07-06T17:25:28.1";
String date3 = "2017-07-06T17:25:28.12";
String date4 = "2017-07-06T17:25:28.123";
String date5 = "2017-07-06T17:25:28.1234";
String date6 = "2017-07-06T17:25:28.12345";
String date7 = "2017-07-06T17:25:28.123456";
String date8 = "2017-07-06T17:25:28.";
</code>```

I have tried the following date time formatter to validate above dates:

```<code>public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
                                   .appendPattern(DATE_TIME_FORMAT_PATTERN)
                                   .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
                                   .toFormatter();
</code>```

It works fine for all the above dates, but according to my requirement it should fail with java.time.format.DateTimeParseException for date8.

Note: I am aware that I can achieve expected result with following formatter:

```<code>DateTimeFormatter formatter2 = DateTimeFormatter
                       .ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]");
</code>```

But I wanted to know that can we achieve expected result by changing in formatter1?

For parsing the date I am using following:

```<code>LocalDateTime.parse(date1, formatter1);
</code>```

答:
You must create an optional section (using optionalStart() and optionalEnd() methods) containing the decimal point followed by 1 to 6 digits:

```<code>String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendPattern(".")
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, false)
    .optionalEnd()
    .toFormatter();
</code>```

This parses from date1 to date7 and throws a java.time.format.DateTimeParseException with date8.

This also works the same way:

```<code>String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true)
    .optionalEnd()
    .toFormatter();
</code>```

Body:
I am trying to create a DateTimeformatter to validate following date times:

String date1 = "2017-07-06T17:25:28";
String date2 = "2017-07-06T17:25:28.1";
String date3 = "2017-07-06T17:25:28.12";
String date4 = "2017-07-06T17:25:28.123";
String date5 = "2017-07-06T17:25:28.1234";
String date6 = "2017-07-06T17:25:28.12345";
String date7 = "2017-07-06T17:25:28.123456";
String date8 = "2017-07-06T17:25:28.";

I have tried the following date time formatter to validate above dates:

public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
                                   .appendPattern(DATE_TIME_FORMAT_PATTERN)
                                   .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
                                   .toFormatter();

It works fine for all the above dates, but according to my requirement it should fail with java.time.format.DateTimeParseException for date8.

Note: I am aware that I can achieve expected result with following formatter:

DateTimeFormatter formatter2 = DateTimeFormatter
                       .ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]");

But I wanted to know that can we achieve expected result by changing in formatter1?

For parsing the date I am using following:

LocalDateTime.parse(date1, formatter1);

Body:
You must create an optional section (using optionalStart() and optionalEnd() methods) containing the decimal point followed by 1 to 6 digits:

String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendPattern(".")
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, false)
    .optionalEnd()
    .toFormatter();

This parses from date1 to date7 and throws a java.time.format.DateTimeParseException with date8.

This also works the same way:

String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true)
    .optionalEnd()
    .toFormatter();


问:
Open method in ajax call not responding
I am new to JSON and AJAX,
SO i tried this piece of code to get JSON data from the url mentioned and then using a AJAX call i tried to print it on console, however nothing gets printed on the console.

Please someone correct what is it that i am doing wrong here, below is the code snippet.

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
btn.addEventListener("click",function(){
req.onreadystatechange = function() {
  var res = req.responseText;
  Console.log(res);
};
});
req.send();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>

<script>"Test.js"</script>

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

答:
You need to change your JS code and put everything inside the block, so it looks nice :) </p>

```<code>var btn = document.getElementById("btn");
var display = document.getElementById("display");

btn.addEventListener("click", function() {
    req = new XMLHttpRequest();
    req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
    req.send();
    req.onreadystatechange = function() {
        var res = req.responseText;
        console.log(res);
    };
});
</code>```

Title: Open method in ajax call not responding

Body:
I am new to JSON and AJAX,
SO i tried this piece of code to get JSON data from the url mentioned and then using a AJAX call i tried to print it on console, however nothing gets printed on the console.

Please someone correct what is it that i am doing wrong here, below is the code snippet.

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
btn.addEventListener("click",function(){
req.onreadystatechange = function() {
  var res = req.responseText;
  Console.log(res);
};
});
req.send();

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

Hello

<Button id= 'btn'>click me</Button>

Body:
You need to change your JS code and put everything inside the block, so it looks nice :)

var btn = document.getElementById("btn");
var display = document.getElementById("display");

btn.addEventListener("click", function() {
    req = new XMLHttpRequest();
    req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
    req.send();
    req.onreadystatechange = function() {
        var res = req.responseText;
        console.log(res);
    };
});


问:
How to remove blank from dropdown and required validation working in AngularJS?
I have a dropdown, I'm binding it with owners, but its giving extra blank option. I want to remove the blank option from it. I'm able to do but when I add these changes my required validator does show error.

```<code><md-input-container>
        <select name="owner" ng-model="form.owner" ng-options="owner.UserName for owner in owners"
                class="input-div" style="height:30px" ng-change="ownerTypeChange()" required ng-disabled="update && view">
          <option style="display:none" value=undefined>Select an owner</option>
        </select>
        <div ng-messages="DataAccessRoleForm.owner.$error">
          <div ng-message="required">required</div>
        </div>
      </md-input-container>
</code>```

If I remove the below line, then required validator works but dropdown has the blank option.

```<code><option style="display:none" value=undefined>Select an owner</option>
</code>```

答:
Check if your select has been touched before displaying the required message.

```<code><div ng-if="form.owner.$touched" ng-message="required">required</div>
</code>```

You can also set the default option to be selected but not selectable once they open the drop down.

```<code><option value="" disabled selected hidden>Select an owner</option>
</code>```

Body:
I have a dropdown, I'm binding it with owners, but its giving extra blank option. I want to remove the blank option from it. I'm able to do but when I add these changes my required validator does show error.

<md-input-container>
        <select name="owner" ng-model="form.owner" ng-options="owner.UserName for owner in owners"
                class="input-div" style="height:30px" ng-change="ownerTypeChange()" required ng-disabled="update && view">
          <option style="display:none" value=undefined>Select an owner</option>
        </select>

required

      </md-input-container>

If I remove the below line, then required validator works but dropdown has the blank option.

<option style="display:none" value=undefined>Select an owner</option>

Body:
Check if your select has been touched before displaying the required message.

<div ng-if="form.owner.$touched" ng-message="required">required</div>

You can also set the default option to be selected but not selectable once they open the drop down.

<option value="" disabled selected hidden>Select an owner</option>


问:
Logstash to convert epoch timestamp
I'm trying to parse some epoch timestamps to be something more readable.

I looked around for how to parse them into a normal time, and from what I understand all I should have to do is something like this:

```<code>mutate
{
    remove_field => [ "..."]
}

grok
{
    match => { 'message' => '%{NUMBER:time}%{SPACE}%{NUMBER:time2}...' }
}

date
{
    match => [ "time","UNIX" ]
}
</code>```

An example of a message is: 1410811884.84 1406931111.00 ....
The first two values should be UNIX time values.

My grok works, because all of the fields show in Kibana with the expected values, and all the values fields I've removed aren't there so the mutate works too. The date section seems to do nothing.

From what I understand the match => [ "time","UNIX" ]  should do what I want (Change the value of time to be a proper date format, and have it show on kibana as a field.) . So apparently I'm not understanding it.

答:
Consider also trying with UNIX_MS for milliseconds.</p>

```<code>date {
    timezone => "UTC"
    match => ["timestamp", "UNIX_MS"]
    target => "@timestamp"
}
</code>```

Title: Logstash to convert epoch timestamp

Body:
I'm trying to parse some epoch timestamps to be something more readable.

I looked around for how to parse them into a normal time, and from what I understand all I should have to do is something like this:

mutate
{
    remove_field => [ "..."]
}

grok
{
    match => { 'message' => '%{NUMBER:time}%{SPACE}%{NUMBER:time2}...' }
}

date
{
    match => [ "time","UNIX" ]
}

An example of a message is: 1410811884.84 1406931111.00 ....
The first two values should be UNIX time values.

My grok works, because all of the fields show in Kibana with the expected values, and all the values fields I've removed aren't there so the mutate works too. The date section seems to do nothing.

From what I understand the match => [ "time","UNIX" ]  should do what I want (Change the value of time to be a proper date format, and have it show on kibana as a field.) . So apparently I'm not understanding it.

Body:
Consider also trying with UNIX_MS for milliseconds.

date {
    timezone => "UTC"
    match => ["timestamp", "UNIX_MS"]
    target => "@timestamp"
}


问:
Setting initial values on load with Select2 with Ajax
I have select2 controls set up with Ajax (have both single and multiple).  I'm trying to have some values on page load but I'm not able to get this to work however.  My code for select2 is given below:

```<code>function AjaxCombo(element, url, multival ){  // multival = true or false
  multival = multival || false;
  $(element).select2({
   minimumInputLength: 2,
   multiple: multival,
   separator: '|',
   ajax: {
     url: url,
     dataType: 'json',
     data: function (term, page) {
        var targetname = $(this).attr('name');
        var target = targetname.slice(targetname.indexOf("[")+1, targetname.indexOf("]"));
       return {
         targettype: "search",
         target: target,
         search: term
       };
     },
     results: function (data, page) {
       return { results: data };
     }
   }
 });
}
AjaxCombo(".ajaxselect", "includes/linkedcontrol.php", false);
AjaxCombo(".ajaxmultiselect", "includes/linkedcontrol.php", true);
</code>```

The Ajax combo works fine, am having trouble only with the initial values load.  I tried this code below but couldn't get it to work:

```<code>initSelection : function (element, callback) {
    var elementText = $(element).attr('data-initvalue');
    callback(elementText);
}
</code>```

My HTML from php is returned as below :

```<code><input name='header[country]' class='ajaxselect'  data-initvalue='[{"id":"IN","name":"India"}]' data-placeholder='Select Country' value='' />
</code>```

I see that values are populated from php, only my jquery is having issues. My values in the control show up as US | United States of America.  I guess I have edited the select2 source for getting this format as default without using format option.

Can anyone please help me populate the default values?  Thanks in advance.

EDIT: This question pertains to Select2 version <4.0.  This option is removed from v4.0 and is much simpler now.

答:
Change the value after the page loads

$('#data').val('').change();

Body:
I have select2 controls set up with Ajax (have both single and multiple).  I'm trying to have some values on page load but I'm not able to get this to work however.  My code for select2 is given below:

function AjaxCombo(element, url, multival ){  // multival = true or false
  multival = multival || false;
  $(element).select2({
   minimumInputLength: 2,
   multiple: multival,
   separator: '|',
   ajax: {
     url: url,
     dataType: 'json',
     data: function (term, page) {
        var targetname = $(this).attr('name');
        var target = targetname.slice(targetname.indexOf("[")+1, targetname.indexOf("]"));
       return {
         targettype: "search",
         target: target,
         search: term
       };
     },
     results: function (data, page) {
       return { results: data };
     }
   }
 });
}
AjaxCombo(".ajaxselect", "includes/linkedcontrol.php", false);
AjaxCombo(".ajaxmultiselect", "includes/linkedcontrol.php", true);

The Ajax combo works fine, am having trouble only with the initial values load.  I tried this code below but couldn't get it to work:

initSelection : function (element, callback) {
    var elementText = $(element).attr('data-initvalue');
    callback(elementText);
}

My HTML from php is returned as below :

<input name='header[country]' class='ajaxselect'  data-initvalue='[{"id":"IN","name":"India"}]' data-placeholder='Select Country' value='' />

I see that values are populated from php, only my jquery is having issues. My values in the control show up as US | United States of America.  I guess I have edited the select2 source for getting this format as default without using format option.

Can anyone please help me populate the default values?  Thanks in advance.

EDIT: This question pertains to Select2 version <4.0.  This option is removed from v4.0 and is much simpler now.


问:
How can I connect to Oracle database?
I am using Fedora 23 and installed Oracle 12.1 and Go 1.7.1

When I run:

```<code>go get github.com/mattn/go-oci8
</code>```

I am getting an error:

/usr/bin/ld: skipping incompatible /usr/lib/oracle/12.1/client64/lib/libclntsh.so when searching for -lclntsh

/usr/bin/ld: cannot find -lclntsh

collect2: error: execution of ld completed with return code 1

答:
What did you put in your oci8.pc file?

I've just got this working with the below.  Keeping in mind I have only the oracle 11.2 instant client installed under the prefix path.  I assume you would have to change the version number to the appropriate number.

```<code>prefix=/home/sbr/wk/apps/oracle/product/11.2.0/client_1
exec_prefix=${prefix}
libdir=${prefix}
includedir=${prefix}/sdk/include

glib_genmarshal=glib-genmarshal
gobject_query=gobject-query
glib_mkenums=glib-mkenums

Name: oci8
Description: oci8 library
Libs: -L${libdir} -lclntsh
Cflags: -I${includedir}
Version: 11.2
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I connect to Oracle database?

Body:
I am using Fedora 23 and installed Oracle 12.1 and Go 1.7.1

When I run:

go get github.com/mattn/go-oci8

I am getting an error:

/usr/bin/ld: skipping incompatible /usr/lib/oracle/12.1/client64/lib/libclntsh.so when searching for -lclntsh

/usr/bin/ld: cannot find -lclntsh

collect2: error: execution of ld completed with return code 1

Body:
What did you put in your oci8.pc file?

I've just got this working with the below.  Keeping in mind I have only the oracle 11.2 instant client installed under the prefix path.  I assume you would have to change the version number to the appropriate number.

prefix=/home/sbr/wk/apps/oracle/product/11.2.0/client_1
exec_prefix=${prefix}
libdir=${prefix}
includedir=${prefix}/sdk/include

glib_genmarshal=glib-genmarshal
gobject_query=gobject-query
glib_mkenums=glib-mkenums

Name: oci8
Description: oci8 library
Libs: -L${libdir} -lclntsh
Cflags: -I${includedir}
Version: 11.2


问:
Add multiple empty columns to pandas DataFrame
How do I add multiple empty columns to a DataFrame from a list?

I can do:

```<code>df["B"] = None
df["C"] = None
df["D"] = None
</code>```

But I can't do:

```<code>df[["B", "C", "D"]] = None
</code>```

KeyError: "['B' 'C' 'D'] not in index"

答:
If you don't want to rewrite the name of the old columns, then you can use reindex:

```<code>df.reindex(columns=[*df.columns.tolist(), 'new_column1', 'new_column2'], fill_value=0)
</code>```

Full example:

```<code>In [1]: df = pd.DataFrame(np.random.randint(10, size=(3,1)), columns=['A'])

In [1]: df
Out[1]:
   A
0  4
1  7
2  0

In [2]: df.reindex(columns=[*df.columns.tolist(), 'col1', 'col2'], fill_value=0)
Out[2]:

   A  col1  col2
0  1     0     0
1  2     0     0
</code>```

And, if you already have a list with the column names, :

```<code>In [3]: my_cols_list=['col1','col2']

In [4]: df.reindex(columns=[*df.columns.tolist(), *my_cols_list], fill_value=0)
Out[4]:
   A  col1  col2
0  1     0     0
1  2     0     0
</code>```

Body:
How do I add multiple empty columns to a DataFrame from a list?

I can do:

df["B"] = None
df["C"] = None
df["D"] = None

But I can't do:

df[["B", "C", "D"]] = None

KeyError: "['B' 'C' 'D'] not in index"

Body:
If you don't want to rewrite the name of the old columns, then you can use reindex:

df.reindex(columns=[*df.columns.tolist(), 'new_column1', 'new_column2'], fill_value=0)

Full example:

In [1]: df = pd.DataFrame(np.random.randint(10, size=(3,1)), columns=['A'])

In [1]: df
Out[1]:
   A
0  4
1  7
2  0

In [2]: df.reindex(columns=[*df.columns.tolist(), 'col1', 'col2'], fill_value=0)
Out[2]:

   A  col1  col2
0  1     0     0
1  2     0     0

And, if you already have a list with the column names, :

In [3]: my_cols_list=['col1','col2']

In [4]: df.reindex(columns=[*df.columns.tolist(), *my_cols_list], fill_value=0)
Out[4]:
   A  col1  col2
0  1     0     0
1  2     0     0


问:
How to switch image when onload
I would like to show the image (from css id) inside div (in html). The image has to match with the template. Every user has a different template, so they need different image shown on the body view.

So far, this is my attempt:

HTML

```<code><div id="logoHeader"></div>
</code>```

CSS

```<code>    #logoheader_1 {
    height: 100px;
    background: url("/logoheader_1.png") left 20px no-repeat;
     }
   #logoheader_2 {
   height: 100px;
   background: url("/logoheader_2.jpg") left 20px no-repeat;
    }
</code>```

JS

```<code>var templates = 1; // This is just example of if user A using template 1

switch(templates) {
  case '1'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_1");
    };
  break;
  case '2'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_2");
    };
  break;
}
</code>```

jsfiddle

Well, it doesn't work up until now. Would you please help me how to show the proper image at the div body for each template?

Thank you so much.

答:
So, first of all, your switch syntax is wrong, and you were trying to compare string with number value (ie. 1 with '1') which doesn't work with switch statement as it uses strict equality.

Then I suggest you tu use classes instead of identifiers to change the style of an element.

Finally, the load event is not available on div elements, so I called it on the window in order to be sure that the div is loaded and ready to be used.

window.addEventListener('load', function() {
  var templates = 1;

  switch (templates) {
    case 1:
      document.getElementById('logoHeader').classList.add('logoheader_1');
      break;
    case 2:
      document.getElementById('logoHeader').classList.add('logoheader_2');
      break;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logoheader_1 {
  height: 100px;
  background: red;
}

.logoheader_2 {
  height: 100px;
  background: black;
}</code>```

```

Title: How to switch image when onload

Body:
I would like to show the image (from css id) inside div (in html). The image has to match with the template. Every user has a different template, so they need different image shown on the body view.

So far, this is my attempt:

HTML

CSS

    #logoheader_1 {
    height: 100px;
    background: url("/logoheader_1.png") left 20px no-repeat;
     }
   #logoheader_2 {
   height: 100px;
   background: url("/logoheader_2.jpg") left 20px no-repeat;
    }

JS

var templates = 1; // This is just example of if user A using template 1

switch(templates) {
  case '1'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_1");
    };
  break;
  case '2'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_2");
    };
  break;
}

jsfiddle

Well, it doesn't work up until now. Would you please help me how to show the proper image at the div body for each template?

Thank you so much.

Body:
So, first of all, your switch syntax is wrong, and you were trying to compare string with number value (ie. 1 with '1') which doesn't work with switch statement as it uses strict equality.

Then I suggest you tu use classes instead of identifiers to change the style of an element.

Finally, the load event is not available on div elements, so I called it on the window in order to be sure that the div is loaded and ready to be used.

window.addEventListener('load', function() {
  var templates = 1;

  switch (templates) {
    case 1:
      document.getElementById('logoHeader').classList.add('logoheader_1');
      break;
    case 2:
      document.getElementById('logoHeader').classList.add('logoheader_2');
      break;
  }
});

.logoheader_1 {
  height: 100px;
  background: red;
}

.logoheader_2 {
  height: 100px;
  background: black;
}

<div id="logoHeader"></div>


问:
Flow control in JavaScript
Is it possible to write this flow control in JavaScript?</p>

```<code>MyLib.get = function() { /* do something */ next(); };
MyLib.save = function() { /* do something */ next(); };
MyLib.alert = function() { /* do something */ next(); };

MyLib.flow([
  MyLib.get(),
  MyLib.save(),
  MyLib.alert()
], function() {
  // all functions were executed
});
</code>```

答:
Yes, but two things to know:

You should build the array from references to your functions. That means you leave off the (), because you just want to pass through the reference, not the result of calling the function!

You're going to have to deal with the fact that getting references to functions from properties of an object will not "remember" the relationship to that object. Thus, the "flow" code would have no way to know how to invoke the functions with "MyLib" as the this context reference. If that's important, you'll want to create functions that run your "member" functions in the right context.

To run the functions in the right context, you can cobble together something like the "bind" function supplied by the Prototype framework (and also, among many others, Functional.js), or $.proxy() from jQuery. It's not that hard and would probably look like this:

```<code>function bindToObject(obj, func) {
  return function() {
    func.apply(obj, arguments);
  }
}
</code>```

then you'd use it like this:

```<code>MyLib.flow([
  bindToObject(MyLib, MyLib.get),
  bindToObject(MyLib, MyLib.save),
  bindToObject(MyLib, MyLib.alert)
]);
</code>```

If you need for parameters to be passed in, you could modify "bindToObject":

```<code>function bindToObject(obj, func) {
  var preSuppliedArgs = Array.prototype.slice.call(arguments, 2);
  return function() {
    func.apply(obj, preSuppliedArgs.splice(arguments));
  }
}
</code>```

That assumes you'd want additional arguments passed when the "bound" function is called to be tacked on to the end of the argument list. In your case, I doubt you'd want to do that, so you could leave off that "splice()" call.

Title: Flow control in JavaScript

Body:
Is it possible to write this flow control in JavaScript?

MyLib.get = function() { /* do something */ next(); };
MyLib.save = function() { /* do something */ next(); };
MyLib.alert = function() { /* do something */ next(); };

MyLib.flow([
  MyLib.get(),
  MyLib.save(),
  MyLib.alert()
], function() {
  // all functions were executed
});

Body:
Yes, but two things to know:

You should build the array from references to your functions. That means you leave off the (), because you just want to pass through the reference, not the result of calling the function!

You're going to have to deal with the fact that getting references to functions from properties of an object will not "remember" the relationship to that object. Thus, the "flow" code would have no way to know how to invoke the functions with "MyLib" as the this context reference. If that's important, you'll want to create functions that run your "member" functions in the right context.

To run the functions in the right context, you can cobble together something like the "bind" function supplied by the Prototype framework (and also, among many others, Functional.js), or $.proxy() from jQuery. It's not that hard and would probably look like this:

function bindToObject(obj, func) {
  return function() {
    func.apply(obj, arguments);
  }
}

then you'd use it like this:

MyLib.flow([
  bindToObject(MyLib, MyLib.get),
  bindToObject(MyLib, MyLib.save),
  bindToObject(MyLib, MyLib.alert)
]);

If you need for parameters to be passed in, you could modify "bindToObject":

function bindToObject(obj, func) {
  var preSuppliedArgs = Array.prototype.slice.call(arguments, 2);
  return function() {
    func.apply(obj, preSuppliedArgs.splice(arguments));
  }
}

That assumes you'd want additional arguments passed when the "bound" function is called to be tacked on to the end of the argument list. In your case, I doubt you'd want to do that, so you could leave off that "splice()" call.


问:
Mozilla stop parent anchor tag behaviour
I have html code.

In Html parent element is Anchor tag and Child element is Dropdown.

I want to stop parent behavious.

Exa. When user click on dropdown so call dropdown change event and stop parent anchor tag behavious like onclick or href value

You can Edit in below url
https://jsfiddle.net/z4c4gwxa/

答:
You need to stop propagation on your dropdown's change event to prevent it from bubbling up the DOM tree, and check the e.target on your anchor tag's click event to ensure it was fired by itself.

e.stopPropagation

$( function () {
    $( "a" ).click( function ( e ) {
        if ( ! $( e.target ).is( $( this ) ) ) {
            return false;
        }
        alert( 'parent' );
    } );
    $( '#dropdown' ).change( function ( e ) {
        e.stopPropagation();
        alert($(this).val());
    } )
} )```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

  <select id="dropdown">
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
  </select>
  Click this part
</code>```

JSfiddle

Body:
You need to stop propagation on your dropdown's change event to prevent it from bubbling up the DOM tree, and check the e.target on your anchor tag's click event to ensure it was fired by itself.

e.stopPropagation

$( function () {
    $( "a" ).click( function ( e ) {
        if ( ! $( e.target ).is( $( this ) ) ) {
            return false;
        }
        alert( 'parent' );
    } );
    $( '#dropdown' ).change( function ( e ) {
        e.stopPropagation();
        alert($(this).val());
    } )
} )

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<a href="javascript:void(0);">
  <select id="dropdown">
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
  </select>
  Click this part
</a>

JSfiddle


问:
Python CashFlow Calculator
I am trying to formulate an equation that can calculate the outstanding_balance in one go using python. It is quite simple using the iterative process. For example:

```<code>for month in range(1, self.amortMonths + 1):

        # Calculate intial and future interest payments

        interest = self.originalPrin * self.rate / 12

        # Calculate intial and future principal payments

        principal_pmt = self.pmt - interest

        # Outstanding balance is reduced by the principal_pmt

        self.originalPrin = self.originalPrin - principal_pmt
</code>```

So self.amortMonths is basically the monthly duration at which the loan must be payed off and along with self.rate, they will determine the self.pmt variable which is the monthly amount the borrower has to pay inorder to reduce the self.oringalPrin value to 0 by the end of self.amortMonths.

Example:

Lets say I have a loan of $1000 (OutstandingPrin) with an interest rate of 10% then my interest payment for the first month is 1000 * 10% = $100. In order to find the self.pmt amount I used a numpy.pmt function which takes the outstandingPrin, rate, amortMonths as parameters to generate a monthly payment value that will reduce the OutstandingPrin to 0 by the end of the amortMonths. Lets say that self.pmt = $120 then the principal_pmt = 120 - 100 = $20. So the outstandingPrin for the next month is 1000-20=$980. Then this just becomes an iterative process.

So I actually need some help to determine an equation that can do this in one go without the need for an iterative process. Apparently, I need to use linear algebra but I don't come from a math background so I was wondering if anyone has any ideas?

EDIT:

So something like this:

Balance_i = Balance_i-1 - (pmt - Balance_i-1 * Rate).

答:
Here is my solution.

```<code>import numpy as np

a = np.array([[1,0,0,0,0], [1.00583333,-1,0,0,-1], [0, 1.005833333, -1, 0, -1], [0,0,1.005833333, -1, -1],[0,0,0,1,0]])
b = np.array([162000,0,0,0,0])
x = np.linalg.solve(a, b)
balance_arr = np.delete(x, -1)
print(balance_arr)

interest_arr = balance_arr * 0.07/12
print(interest_arr)

prin_payment = np.subtract(54631.22, interest_arr)
prin_payment[-1] = 0
print(prin_payment)

np.allclose(np.dot(a,x), b)
</code>```

The array values I manually created them based on hand calculations. The next step would be for me to figure out how to generate them automatically given the term, original balance, and interest rate.

Title: Python CashFlow Calculator

Body:
I am trying to formulate an equation that can calculate the outstanding_balance in one go using python. It is quite simple using the iterative process. For example:

for month in range(1, self.amortMonths + 1):

        # Calculate intial and future interest payments

        interest = self.originalPrin * self.rate / 12

        # Calculate intial and future principal payments

        principal_pmt = self.pmt - interest

        # Outstanding balance is reduced by the principal_pmt

        self.originalPrin = self.originalPrin - principal_pmt

So self.amortMonths is basically the monthly duration at which the loan must be payed off and along with self.rate, they will determine the self.pmt variable which is the monthly amount the borrower has to pay inorder to reduce the self.oringalPrin value to 0 by the end of self.amortMonths.

Example:

Lets say I have a loan of $1000 (OutstandingPrin) with an interest rate of 10% then my interest payment for the first month is 1000 * 10% = $100. In order to find the self.pmt amount I used a numpy.pmt function which takes the outstandingPrin, rate, amortMonths as parameters to generate a monthly payment value that will reduce the OutstandingPrin to 0 by the end of the amortMonths. Lets say that self.pmt = $120 then the principal_pmt = 120 - 100 = $20. So the outstandingPrin for the next month is 1000-20=$980. Then this just becomes an iterative process.

So I actually need some help to determine an equation that can do this in one go without the need for an iterative process. Apparently, I need to use linear algebra but I don't come from a math background so I was wondering if anyone has any ideas?

EDIT:

So something like this:

Balance_i = Balance_i-1 - (pmt - Balance_i-1 * Rate).

Body:
Here is my solution.

import numpy as np

a = np.array([[1,0,0,0,0], [1.00583333,-1,0,0,-1], [0, 1.005833333, -1, 0, -1], [0,0,1.005833333, -1, -1],[0,0,0,1,0]])
b = np.array([162000,0,0,0,0])
x = np.linalg.solve(a, b)
balance_arr = np.delete(x, -1)
print(balance_arr)

interest_arr = balance_arr * 0.07/12
print(interest_arr)

prin_payment = np.subtract(54631.22, interest_arr)
prin_payment[-1] = 0
print(prin_payment)

np.allclose(np.dot(a,x), b)

The array values I manually created them based on hand calculations. The next step would be for me to figure out how to generate them automatically given the term, original balance, and interest rate.


问:
50-default.conf entry meaning
I went through the rsyslog.d/50-default.conf file..
the entries in the files are like this.

```<code>auth,authpriv.*              /var/log/auth.log
*.*;auth,authpriv.none      -/var/log/syslog
#cron.*                      /var/log/cron.log
#daemon.*                   -/var/log/daemon.log
kern.*                      -/var/log/kern.log
#lpr.*                      -/var/log/lpr.log
mail.*                      -/var/log/mail.log
#user.*                     -/var/log/user.log
</code>```

In some entries the log directory path is prefixed with hyphen sign(-).
can anyone please tell me what does it means..

答: Adding the hypen (minus sign, "-") stops the log from being written to the file immediately.  Having the hyphen means you may lose some information that has not been written in the case of a crash, but not having it may have performance issues especially if you run programs that use logging in a very verbose manner.</p>

Title: 50-default.conf entry meaning

Body:
I went through the rsyslog.d/50-default.conf file..
the entries in the files are like this.

auth,authpriv.*              /var/log/auth.log
*.*;auth,authpriv.none      -/var/log/syslog
#cron.*                      /var/log/cron.log
#daemon.*                   -/var/log/daemon.log
kern.*                      -/var/log/kern.log
#lpr.*                      -/var/log/lpr.log
mail.*                      -/var/log/mail.log
#user.*                     -/var/log/user.log

In some entries the log directory path is prefixed with hyphen sign(-).
can anyone please tell me what does it means..


问:
Vue computed setter not working with checkboxes?
I have a computed setter:

```<code>rating: {
    get() {
        return this.$store.state.rating;
    },

    set(value) {
        console.log(value);

        this.$store.commit('updateFilter', {
            name: this.name,
            value
        });
    }
}
</code>```

This is linked to my rating like so:

```<code><label>
    <input type="checkbox" :value="Number(value)" v-model="rating">
    {{ index }}
</label>
</code>```

I expect the computed setter to log an array because when I use a watcher to watch for changes on the rating model I am getting an array.

Except whenever I use a computed setter like above it simply outputs true when a checkbox is selected or false when they are all deselected.

What is going on here, should I just be getting an array just as like with a watcher?

答:
v-model has somewhat "magical" behavior, particularly when applied to checkboxes. When bound to an array, the checkbox will add or remove the value to/from the array based on its checked state.

It is not clear in your example what value is in Number(value). It should be a value that you want included in the array when the box is checked.

Taking the example from the Vue docs linked above, I have modified it to use a computed, and it works as you might expect, with the set getting the new value of the array.

new Vue({
  el: '#app',
  data: {
    checkedNames: []
  },
  computed: {
    proxyCheckedNames: {
      get() {
        return this.checkedNames;
      },
      set(newValue) {
        this.checkedNames = newValue;
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <input type="checkbox" id="jack" value="Jack" v-model="proxyCheckedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="proxyCheckedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="proxyCheckedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div></code>```

Body:
I have a computed setter:

rating: {
    get() {
        return this.$store.state.rating;
    },

    set(value) {
        console.log(value);

        this.$store.commit('updateFilter', {
            name: this.name,
            value
        });
    }
}

This is linked to my rating like so:

    <input type="checkbox" :value="Number(value)" v-model="rating">
    {{ index }}

I expect the computed setter to log an array because when I use a watcher to watch for changes on the rating model I am getting an array.

Except whenever I use a computed setter like above it simply outputs true when a checkbox is selected or false when they are all deselected.

What is going on here, should I just be getting an array just as like with a watcher?

Body:
v-model has somewhat "magical" behavior, particularly when applied to checkboxes. When bound to an array, the checkbox will add or remove the value to/from the array based on its checked state.

It is not clear in your example what value is in Number(value). It should be a value that you want included in the array when the box is checked.

Taking the example from the Vue docs linked above, I have modified it to use a computed, and it works as you might expect, with the set getting the new value of the array.

new Vue({
  el: '#app',
  data: {
    checkedNames: []
  },
  computed: {
    proxyCheckedNames: {
      get() {
        return this.checkedNames;
      },
      set(newValue) {
        this.checkedNames = newValue;
      }
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <input type="checkbox" id="jack" value="Jack" v-model="proxyCheckedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="proxyCheckedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="proxyCheckedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>


问:
D3.js How to update chart display with new data?
I am trying to implement an update function for my D3 sunburst diagram where i can change the data that is displayed. I am able to successfully add or remove nodes.

However, i can't seem to be able to modify the existing data.

For example, if half of my chart is removed, i would like for the other half to fill the space leaved by the delete. Same thing goes when new data get added, i would like for the existing data to shrink and take less space

Here is my update function :

```<code>            function update(newData) {
                root = newData;
                node = root;

                g = svg.datum(root)
                    .selectAll("g")
                    .data(partition.nodes(root));

                var newG = g.enter()
                    .append("g");

                g.exit().selectAll("path").transition().duration(5000).attrTween("d", arcTween(0)).remove();

                path = g.selectAll("path").transition().duration(5000).attr("d", arc);

                newG.append("path")
                    .attr("d", arc);
            };
</code>```

Here is how the chart is built :

```<code>            function render(data) {
                root = data;
                node = root;

                width = $(".burst-chart-container").height();
                height = ($(".burst-chart-container").width() / 2);
                radius = Math.min(width, height) / 2;

                x = d3.scale.linear().range([0, 2 * Math.PI]);
                y = d3.scale.linear().range([0, radius]);

                rad = Math.min(width, height) / Math.PI - 25;

                partition = d3.layout.partition().sort(null).value(function (d) { return d.size; });

                arc = d3.svg.arc()
                    .startAngle(function (d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
                    .endAngle(function (d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
                    .innerRadius(function (d) { return Math.max(0, y(d.y)); })
                    .outerRadius(function (d) { return Math.max(0, y(d.y + d.dy)); });

                svg = d3.select(element[0]).append('svg')
                    .attr("width", width).attr("height", height)
                    .attr("class", "svgDashboard")
                    .append("g")
                    .attr("transform", "translate(" + width / 2 + "," + (height / 2) + ")");

                g = svg.datum(root).selectAll("g")
                    .data(partition.nodes)
                    .enter()
                    .append("g")

                path = g.append("path")
                    .attr("d", arc)
            }
</code>```

I do know that path.attr("d",arc) should update the visual, but it doesn't work in my case.

I think that it has something to do with the partition layout who dosen't tell the existing arcs that they need to change, or the way that I do the selection to update the data, but I might be wrong.

Any help would be appreciated.

答:
I found out that the path and text data were never updated. My update did only change g element data. To correct it, I simply take the parent data and put into into his child after I updated it.

```<code>                g = svg.datum(root)
                    .selectAll("g")
                    .data(partition.nodes(root));

                //Add this part to update child elements
                g.selectAll("path").each(function () {
                    d3.select(this).datum(d3.select(this.parentNode).datum());
                });

                g.selectAll("text").each(function () {
                    d3.select(this).datum(d3.select(this.parentNode).datum());
                });
</code>```

With those changes, i am able to call my attrTween function which update the visual with the new data.

Body:
I am trying to implement an update function for my D3 sunburst diagram where i can change the data that is displayed. I am able to successfully add or remove nodes.

However, i can't seem to be able to modify the existing data.

For example, if half of my chart is removed, i would like for the other half to fill the space leaved by the delete. Same thing goes when new data get added, i would like for the existing data to shrink and take less space

Here is my update function :

            function update(newData) {
                root = newData;
                node = root;

                g = svg.datum(root)
                    .selectAll("g")
                    .data(partition.nodes(root));

                var newG = g.enter()
                    .append("g");

                g.exit().selectAll("path").transition().duration(5000).attrTween("d", arcTween(0)).remove();

                path = g.selectAll("path").transition().duration(5000).attr("d", arc);

                newG.append("path")
                    .attr("d", arc);
            };

Here is how the chart is built :

            function render(data) {
                root = data;
                node = root;

                width = $(".burst-chart-container").height();
                height = ($(".burst-chart-container").width() / 2);
                radius = Math.min(width, height) / 2;

                x = d3.scale.linear().range([0, 2 * Math.PI]);
                y = d3.scale.linear().range([0, radius]);

                rad = Math.min(width, height) / Math.PI - 25;

                partition = d3.layout.partition().sort(null).value(function (d) { return d.size; });

                arc = d3.svg.arc()
                    .startAngle(function (d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
                    .endAngle(function (d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
                    .innerRadius(function (d) { return Math.max(0, y(d.y)); })
                    .outerRadius(function (d) { return Math.max(0, y(d.y + d.dy)); });

                svg = d3.select(element[0]).append('svg')
                    .attr("width", width).attr("height", height)
                    .attr("class", "svgDashboard")
                    .append("g")
                    .attr("transform", "translate(" + width / 2 + "," + (height / 2) + ")");

                g = svg.datum(root).selectAll("g")
                    .data(partition.nodes)
                    .enter()
                    .append("g")

                path = g.append("path")
                    .attr("d", arc)
            }

I do know that path.attr("d",arc) should update the visual, but it doesn't work in my case.

I think that it has something to do with the partition layout who dosen't tell the existing arcs that they need to change, or the way that I do the selection to update the data, but I might be wrong.

Any help would be appreciated.

Body:
I found out that the path and text data were never updated. My update did only change g element data. To correct it, I simply take the parent data and put into into his child after I updated it.

                g = svg.datum(root)
                    .selectAll("g")
                    .data(partition.nodes(root));

                //Add this part to update child elements
                g.selectAll("path").each(function () {
                    d3.select(this).datum(d3.select(this.parentNode).datum());
                });

                g.selectAll("text").each(function () {
                    d3.select(this).datum(d3.select(this.parentNode).datum());
                });

With those changes, i am able to call my attrTween function which update the visual with the new data.


问:
dynamic background-color change
I work on my portfolio website, it's based on a fullpage.js and WordPress.
I would like to have fixed background with changing custom "background-color".

I add different "background-color" to every post with a custom field.

I change class name for visible section (post) inside a full page

script, visible post gets class "active".

I know that fullpage.js doesn't allow fixed elements, so I have to put some "background" div outside of full page wrapper (and WordPress loop too).
I don't know how to copy that "background-color" from a visible (class "active") section to a fixed background in a separate div.
There are some possibilities:

use js/jQuery to copy CSS "background-color" value from one ( class "active") div to another(fixed background div), but it has to be done dynamically. How? All scripts I found and tested works only once for first "active" background-color, and when section change (another div is "active") fixed background still has the first active section background-color.

or use php with custom query outside a loop - but I don't know how to filter with a specific class name "active". I have only basic script:

```<code>style="background-color:<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'background', true);
wp_reset_query();
</code>```

how to add a filter for "active" class?

Any other ideas? Help!

EDIT2: I found two scripts which do what I need:

1 https://codepen.io/Funsella/pen/yLfAG

2 https://codepen.io/Funsella/pen/dpRPYZ

both change the background-color copying it from "source" div to second "target" div. I can keep "source" div inside a wordpress loop (fullpage wrapper too) and transfer the background-color value to my fixed background div outside of WP's loop and fullpage.
First script works with scroll events - so it probably won't work with fullpage.js plugin which doesn't scroll content.
But the second script does his job exactly how I needed. I tested it.

So the question is: can it be done in more simple way? Without additional jQuery plugin (in-view.js)? Just plain JS or jQuery?

答:
So, you'll be showing various blog posts on a single page and want each one to have its own background color, correct?  If so, try fullpage.js' sectionsColor option.

You can read about it here
https://github.com/alvarotrigo/fullPage.js#options

Here's an example from that page:

```<code>$('#fullpage').fullpage({
    sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE', 'whitesmoke', '#000'],
});
</code>```

The documentation doesn't explain precisely what's happening here, but it looks like you're simply sending in an array of section colors in order of their appearance.

EDIT BASED ON COMMENTS:

From your picture I think I better understand what you're trying to do.  Basically you want a slide layer (transparent) and a fixed background layer (color of active slide).  First, is this parallex example what you're trying to achieve? https://alvarotrigo.com/fullPage/extensions/parallax.html#firstPage

If so, there is a basic example in the repo.  If this won't accomplish exactly what you're trying to do, follow these directions:

Use the onLeave or afterLoad callback to make an ajax request to your site.

Query your posts using your post Id to retrieve the post attribute background.

Retrieve the background color and set/fade-in your background-color property.

Here's a very simple ajax request example using jQuery:

```<code>//set the function to perform for onLeave in the options
onLeave: goGetThatColor(index)

//not in your options
function goGetThatColor(index){
    $.ajax({
      method: "POST",
      url: "get_post_color.php",
      data: { id: index }
    })
      .done(function( color ) {
        $(#background-element).css('background-color', color);
      });
}
</code>```

I'm just going based off of the documentation, the index that's passed in might be an arbitrary ordering or the post id from Wordpress.  I'm not sure about that so you might have to grab the post id from an attribute in your dom.

Title: dynamic background-color change

Body:
I work on my portfolio website, it's based on a fullpage.js and WordPress.
I would like to have fixed background with changing custom "background-color".

I add different "background-color" to every post with a custom field.

I change class name for visible section (post) inside a full page

script, visible post gets class "active".

I know that fullpage.js doesn't allow fixed elements, so I have to put some "background" div outside of full page wrapper (and WordPress loop too).
I don't know how to copy that "background-color" from a visible (class "active") section to a fixed background in a separate div.
There are some possibilities:

use js/jQuery to copy CSS "background-color" value from one ( class "active") div to another(fixed background div), but it has to be done dynamically. How? All scripts I found and tested works only once for first "active" background-color, and when section change (another div is "active") fixed background still has the first active section background-color.

or use php with custom query outside a loop - but I don't know how to filter with a specific class name "active". I have only basic script:

style="background-color:<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'background', true);
wp_reset_query();

how to add a filter for "active" class?

Any other ideas? Help!

EDIT2: I found two scripts which do what I need:

1 https://codepen.io/Funsella/pen/yLfAG

2 https://codepen.io/Funsella/pen/dpRPYZ

both change the background-color copying it from "source" div to second "target" div. I can keep "source" div inside a wordpress loop (fullpage wrapper too) and transfer the background-color value to my fixed background div outside of WP's loop and fullpage.
First script works with scroll events - so it probably won't work with fullpage.js plugin which doesn't scroll content.
But the second script does his job exactly how I needed. I tested it.

So the question is: can it be done in more simple way? Without additional jQuery plugin (in-view.js)? Just plain JS or jQuery?

Body:
So, you'll be showing various blog posts on a single page and want each one to have its own background color, correct?  If so, try fullpage.js' sectionsColor option.

You can read about it here
https://github.com/alvarotrigo/fullPage.js#options

Here's an example from that page:

$('#fullpage').fullpage({
    sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE', 'whitesmoke', '#000'],
});

The documentation doesn't explain precisely what's happening here, but it looks like you're simply sending in an array of section colors in order of their appearance.

EDIT BASED ON COMMENTS:

From your picture I think I better understand what you're trying to do.  Basically you want a slide layer (transparent) and a fixed background layer (color of active slide).  First, is this parallex example what you're trying to achieve? https://alvarotrigo.com/fullPage/extensions/parallax.html#firstPage

If so, there is a basic example in the repo.  If this won't accomplish exactly what you're trying to do, follow these directions:

Use the onLeave or afterLoad callback to make an ajax request to your site.

Query your posts using your post Id to retrieve the post attribute background.

Retrieve the background color and set/fade-in your background-color property.

Here's a very simple ajax request example using jQuery:

//set the function to perform for onLeave in the options
onLeave: goGetThatColor(index)

//not in your options
function goGetThatColor(index){
    $.ajax({
      method: "POST",
      url: "get_post_color.php",
      data: { id: index }
    })
      .done(function( color ) {
        $(#background-element).css('background-color', color);
      });
}

I'm just going based off of the documentation, the index that's passed in might be an arbitrary ordering or the post id from Wordpress.  I'm not sure about that so you might have to grab the post id from an attribute in your dom.


问:
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object
I am getting this error:

```<code>Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
</code>```

This is my code:

```<code>var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
        </ul>
      </div>
    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)
</code>```

My Home.jsx file:

```<code>var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;
</code>```

答:
In my case, one of the exported child module was not returning a proper react component.

```<code>const Component = <div> Content </div>;
</code>```

instead of

```<code>const Component = () => <div>Content</div>;
</code>```

The error shown was for the parent, hence couldn't figure out.

Body:
I am getting this error:

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is my code:

var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (

App

<Link to="/about">About</Link>

    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)

My Home.jsx file:

var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;

Body:
In my case, one of the exported child module was not returning a proper react component.

const Component = <div> Content </div>;

instead of

const Component = () => <div>Content</div>;

The error shown was for the parent, hence couldn't figure out.


问:
How to convert 12 bit DICOM image to 8 bit jpeg?
I am trying to load DICOM files into python using the DICOM library. I have done the following

```<code>ds=dicom.read_file(r"C:\Users\Z003SPFR.AD005\ML\GLCM AND SVM\data\NECT\1.IMA")
#    # store the raw image data
DicomImage = ds.pixel_array
</code>```

This gives me values that appear to be 12 bit, since the highest value obtained was around 3047 and lowest value was 0. Then I made my own mapping function to bring it to the range 0-255. I used the following code:

```<code>leftMin = 0
leftMax = np.amax(DicomImage)

rightMin = 0
rightMax = 255

def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

#print(translate(value, leftMin, leftMax, rightMin, rightMax))

def int12_to_int8(img):
    img_array = []

    for eachRow in img:
        for eachPix in eachRow:
            img_array.append(translate(eachPix,leftMin, leftMax, rightMin, rightMax))
    img_array = np.array(img_array)
    img_array = img_array.reshape(512,512)
    return img_array

correct_range_image = int12_to_int8(DicomImage)
</code>```

After doing this, I realized that the array img_array was of type uint16. I wanted it as uint8. So I used the following line to convert to uint8:

```<code>cvuint8 = cv2.convertScaleAbs(correct_range_image)
</code>```

Then I displayed the resulting image. But I received an image that didn't represent the original image very well. I have posted pictures of the original image and the converted image. How can I make the conversion better so that I get a better representation of the original image? Code I used to display is here :

```<code>cv2.imwrite('1.jpeg', cvuint8 )
cv2.imshow('image',cvuint8 )[enter image description here][1]
cv2.waitKey(0)
</code>```

IMAGES

Converted Image

Original Image

答:
please refer to http://dicom.nema.org/DICOM/2013/output/chtml/part04/sect_N.2.html to see how the medical image pixel data is rendered before its displayed
not all mentioned concepts is applied but i assume your missing the importance of Window level and window Center Values .
read about Windowing equation here
Window width and center calculation of DICOM image

So if you are trying to downgrade the bitDepth of the Image before its correctly rendered (losing least important data) , for sure you will get a bad image .
consider applying windowing on original data before conversion , you can play with imageJ tool to see image operations (WL ,  Downgrading Depth) in action before writing the code for it

Body:
I am trying to load DICOM files into python using the DICOM library. I have done the following

ds=dicom.read_file(r"C:\Users\Z003SPFR.AD005\ML\GLCM AND SVM\data\NECT\1.IMA")
#    # store the raw image data
DicomImage = ds.pixel_array

This gives me values that appear to be 12 bit, since the highest value obtained was around 3047 and lowest value was 0. Then I made my own mapping function to bring it to the range 0-255. I used the following code:

leftMin = 0
leftMax = np.amax(DicomImage)

rightMin = 0
rightMax = 255

def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

#print(translate(value, leftMin, leftMax, rightMin, rightMax))

def int12_to_int8(img):
    img_array = []

    for eachRow in img:
        for eachPix in eachRow:
            img_array.append(translate(eachPix,leftMin, leftMax, rightMin, rightMax))
    img_array = np.array(img_array)
    img_array = img_array.reshape(512,512)
    return img_array

correct_range_image = int12_to_int8(DicomImage)

After doing this, I realized that the array img_array was of type uint16. I wanted it as uint8. So I used the following line to convert to uint8:

cvuint8 = cv2.convertScaleAbs(correct_range_image)

Then I displayed the resulting image. But I received an image that didn't represent the original image very well. I have posted pictures of the original image and the converted image. How can I make the conversion better so that I get a better representation of the original image? Code I used to display is here :

cv2.imwrite('1.jpeg', cvuint8 )
cv2.imshow('image',cvuint8 )[enter image description here][1]
cv2.waitKey(0)

IMAGES

Converted Image

Original Image


问:
How to use the value of Blogger tags in custom Javascript?
I've been trying to find out the name of the author of a post using javascript and blogger tags.

The name of the author is stored in the data tag <data:post.author>.

I want to detect that name in custom javascript code I wrote.

```<code><script type="text/javascript">
    var author = "<data:post.author>";
    document.getElementById("author").innerHTML = author;
</script>
</code>```

But it doesn't extract the value from it. How can I get the value of that data tag to use inside javascript?

答:
You will need to replace <data:post.author> with <data:post.author/> otherwise you will see the following error when saving theme code -

The element type "data:post.author" must be terminated by the matching
  end-tag "</data:post.author>"

Also, a thing to note is that, the data:post dictionary data layout tags will only work if they are added between the statement -

```<code><b:loop values='data:posts' var='post'>
<!-- Your Code -->
</b:loop>
</code>```

This b:loop is present inside the Blog widget.

If these data layout tags are used outside that b:loop statement, then they won't work because Blogger won't be able to find the dictionary of data:post (The globally available dictionaries in Blogger themes are data:blog , data:view , data:skin , data:widgets and data:messages)

Body:
I've been trying to find out the name of the author of a post using javascript and blogger tags.

The name of the author is stored in the data tag <data:post.author>.

I want to detect that name in custom javascript code I wrote.

But it doesn't extract the value from it. How can I get the value of that data tag to use inside javascript?

Body:
You will need to replace <data:post.author> with <data:post.author/> otherwise you will see the following error when saving theme code -

The element type "data:post.author" must be terminated by the matching
  end-tag "</data:post.author>"

Also, a thing to note is that, the data:post dictionary data layout tags will only work if they are added between the statement -

<b:loop values='data:posts' var='post'>
<!-- Your Code -->
</b:loop>

This b:loop is present inside the Blog widget.

If these data layout tags are used outside that b:loop statement, then they won't work because Blogger won't be able to find the dictionary of data:post (The globally available dictionaries in Blogger themes are data:blog , data:view , data:skin , data:widgets and data:messages)


问:
jQuery - How to get an element's class from ajax request
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

```<code><body id="body" class="home page-id-number other-classes">
    <main>
        <div class="cd-main-content">
            <!-- inside is the dynamically loaded content-->
        </div>
    </main>
</body>
</code>```

jQuery

```<code>$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});
</code>```

答:
Your jQuery code is wrong:

```<code>$.ajax({url: url,
    success: function(data){
        var body = $(data).find("body"); //not #body
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});
</code>```

The right selector is body not #body, which is an id selector

So, to change your body classes use this code:

```<code>$.ajax({url: url,
    success: function(data){
        var classes = $(data).find("body").attr("class"); //get the classes
        $("body").attr("class", classes); //set the classes
    }
});
</code>```

jQuery Selectors

Body:
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

jQuery

$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});

Body:
Your jQuery code is wrong:

$.ajax({url: url,
    success: function(data){
        var body = $(data).find("body"); //not #body
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});

The right selector is body not #body, which is an id selector

So, to change your body classes use this code:

$.ajax({url: url,
    success: function(data){
        var classes = $(data).find("body").attr("class"); //get the classes
        $("body").attr("class", classes); //set the classes
    }
});

jQuery Selectors


问:
How can I easily and simply schedule a cron job in PHP?
How can I easily and simply schedule a cron job in PHP? Rails has BackgroundRB...</p>

答:
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks. </p>

<p>Here is a useful link if you have control over the machine.
http://troy.jdmz.net/cron/
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base. </p>

OwnerDisplayName: Newbie Prog

Body:
You're conflating a language with a framework. PHP doesn't have a cron scheduling any more than Ruby does. If you're using a PHP framework or cms however, there is likely some utility for cron tasks.

Here is a useful link if you have control over the machine.
http://troy.jdmz.net/cron/
If you have shared hosting, there's probably some tool they'd give you for cron jobs; ask them or look in the knowledge base.


问:
How do i hide git-bash.exe and just run it in the background whilst I'm calling a git clone through a C# process?
Hello I have the following code

```<code>string newDist = destination + "/" + fileName;
var o = new Process
{
    StartInfo =
    {
        FileName = pathToGitClient,
        Arguments = $"-c \"eval $(ssh-agent) && ssh-add {privateKey} && git clone {repoUrl} {repoDest}\""
    }
};
o.Start();
</code>```

This basically creates a git clone process using git-bash.exe in my git folder. If i wanted to hide the command line window whilst it's cloning how would I do that?

I tried

```<code>o.StartInfo.UseShellExecute = false;
o.StartInfo.CreateNoWindow = true;
</code>```

but it didn't work

答:
You can use StartInfo.WindowStyle which takes an instance of the ProcessWindowStyle enum.

```<code>o.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
// or
o.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
</code>```

You will still need to set UseShellExecute to false for this to work.

Body:
Hello I have the following code

string newDist = destination + "/" + fileName;
var o = new Process
{
    StartInfo =
    {
        FileName = pathToGitClient,
        Arguments = $"-c \"eval $(ssh-agent) && ssh-add {privateKey} && git clone {repoUrl} {repoDest}\""
    }
};
o.Start();

This basically creates a git clone process using git-bash.exe in my git folder. If i wanted to hide the command line window whilst it's cloning how would I do that?

I tried

o.StartInfo.UseShellExecute = false;
o.StartInfo.CreateNoWindow = true;

but it didn't work

Body:
You can use StartInfo.WindowStyle which takes an instance of the ProcessWindowStyle enum.

o.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
// or
o.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

You will still need to set UseShellExecute to false for this to work.


问:
Is DispatchSemaphore a good replacement for NSLock?
I've been using NSLocks to synchronize touchy parts of code, but have been running into issues due to the fact that they must be unlocked from the same thread that they were locked from. Then I found that GCD's DispatchSemaphores seem to do the same thing, with the added convenience that they can be signaled from any thread. I was wondering, though, if this convenience comes at the price of thread-safety. Is it advisable to replace

```<code>let lock = NSLock()
lock.lock()
// do things...
lock.unlock()
</code>```

with

```<code>let semaphore = DispatchSemaphore(value: 1)
semaphore.wait()
// do things...
semaphore.signal()
</code>```

or will I run into issues regarding thread-safety anyway?

答:
Yes they have the same function, both to deal with producer-consumer problem.

Semaphore allows more than one thread to access a shared resource if it is configured accordingly. You can make the execution of the blocks in the same concurrent dispatchQueue.

{
    semaphore.wait()
    // do things...
    semaphore.signal()
}
```

Actually the same applies to Lock, if you only want one thread to touch the resource at one time, in the concurrent way.

I found this to be helpful: https://priteshrnandgaonkar.github.io/concurrency-with-swift-3/

Body:
I've been using NSLocks to synchronize touchy parts of code, but have been running into issues due to the fact that they must be unlocked from the same thread that they were locked from. Then I found that GCD's DispatchSemaphores seem to do the same thing, with the added convenience that they can be signaled from any thread. I was wondering, though, if this convenience comes at the price of thread-safety. Is it advisable to replace

let lock = NSLock()
lock.lock()
// do things...
lock.unlock()

with

let semaphore = DispatchSemaphore(value: 1)
semaphore.wait()
// do things...
semaphore.signal()

or will I run into issues regarding thread-safety anyway?

Body:
Yes they have the same function, both to deal with producer-consumer problem.

Semaphore allows more than one thread to access a shared resource if it is configured accordingly. You can make the execution of the blocks in the same concurrent dispatchQueue.

{
    semaphore.wait()
    // do things...
    semaphore.signal()
}

Actually the same applies to Lock, if you only want one thread to touch the resource at one time, in the concurrent way.

I found this to be helpful: https://priteshrnandgaonkar.github.io/concurrency-with-swift-3/


问:
Cython cannot convert float ndarray to int ndarray
I am having a very weird error when I cast a numpy ndarray from one type to the other in Cython. For instance when I write the following convert_test.pyx:

```<code>cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    cdef np.ndarray[np.int, ndim=2] int_matrix=float_matrix.astype(np.int)
    return int_matrix
</code>```

compile it and test:

```<code>from convert_test import convert_to_int
a_int=convert_to_int(np.zeros((2,2)).astype(np.float32))
</code>```

I got the very familiar message:

ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

It is probably super obvious but I don't quite see it yet.

答: You have to use _t types in your declaration: cdef np.ndarray[np.int_t, ndim=2].</p>

Body:
I am having a very weird error when I cast a numpy ndarray from one type to the other in Cython. For instance when I write the following convert_test.pyx:

cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    cdef np.ndarray[np.int, ndim=2] int_matrix=float_matrix.astype(np.int)
    return int_matrix

compile it and test:

from convert_test import convert_to_int
a_int=convert_to_int(np.zeros((2,2)).astype(np.float32))

I got the very familiar message:

ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

It is probably super obvious but I don't quite see it yet.


问:
Cannot find symbol variable activity_main
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }
</code>```

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me

答:
Your display function like below.

private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
} }

Threre is "\" in your findValueById in place of "."

Body:
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

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

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me