问:
Mysql Search for a word/sentence that has extra characteres at the end PHP
Currently I have a query that searchs for sentences/words, it works almost as expected,

I have a regex expresion that searches for names in a table, expample:

```<code>function getNames($str){
    $stmt = "SELECT * FROM users WHERE name = :name
                                    OR name REGEXP :reg1
                                    OR name REGEXP :reg2
                                    OR name LIKE :lik1";
    $query = self::$connection->prepare($stmt);
    $query->execute(array(":name"=>$str,
                          ":reg1"=>"^$str" . "[a-zA-Z\s]*$",
                          ":reg2"=>"^[a-zA-Z]*[\s]*[$str][a-zA-Z]"
                          ":lik1"=>"%" . $str . "%"
    ));
   return $query->fetchAll(PDO::FETCH_ASSOC);
}
</code>```

Let's suppose my table contains the following values

Bob

Peter

Mark

David

John

If I run my query with Bob as $name value it gets it but I would like to be able to find Bob when I run the query using BobsomeLettersExtra or Bob something as $name value
Is there a way to do this using REGEXP or LIKE ?

答:
You may try below Query with where Clause for LIKE :

```<code>"SELECT * FROM users WHERE name = ".$name." OR name LIKE '%".$name."%' OR name REGEXP ^".$name."[a-zA-Z]*$"
</code>```

Body:
Currently I have a query that searchs for sentences/words, it works almost as expected,

I have a regex expresion that searches for names in a table, expample:

function getNames($str){
    $stmt = "SELECT * FROM users WHERE name = :name
                                    OR name REGEXP :reg1
                                    OR name REGEXP :reg2
                                    OR name LIKE :lik1";
    $query = self::$connection->prepare($stmt);
    $query->execute(array(":name"=>$str,
                          ":reg1"=>"^$str" . "[a-zA-Z\s]*$",
                          ":reg2"=>"^[a-zA-Z]*[\s]*[$str][a-zA-Z]"
                          ":lik1"=>"%" . $str . "%"
    ));
   return $query->fetchAll(PDO::FETCH_ASSOC);
}

Let's suppose my table contains the following values

Bob

Peter

Mark

David

John

If I run my query with Bob as $name value it gets it but I would like to be able to find Bob when I run the query using BobsomeLettersExtra or Bob something as $name value
Is there a way to do this using REGEXP or LIKE ?

Body:
You may try below Query with where Clause for LIKE :

"SELECT * FROM users WHERE name = ".$name." OR name LIKE '%".$name."%' OR name REGEXP ^".$name."[a-zA-Z]*$"


来源: stackexchange

问:
Group 2d array by column value and concatenate values within each group
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

```<code>$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];
</code>```

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

```<code>Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)
</code>```

I try this method, but not fix at 'code_name'

```<code>$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);
</code>```

print_r($out);

答:
Please try below one as another approach:</p>

```<code><?php
$arr = Array (
    Array
        (
            'name' => 'Jambi Selatan',
            'code' => '36139',
            'code_name' => '36139 - Jambi Selatan'
        ),
    Array
        (
            'name' => 'Jambi Selatan',
            'code' => '36137',
            'code_name' => '36137 - Jambi Selatan'
        ),
    Array
        (
            'name' => 'Bagan Pete',
            'code' => '36129',
            'code_name' => '36129 - Bagan Pete'
        ),
    Array
        (
            'name' => 'Bagan Pete',
            'code' => '36127',
            'code_name' => '36127 - Bagan Pete'
        )
);

$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
    $newarr[$aa['name']][] = $aa;
}

foreach($newarr as $kk => $bb) {
    foreach($bb as $cc) {
        $finalArr[$kk]['name'] = $cc['name'];

        if(isset($finalArr[$kk]['code'])) {
            $finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
        } else {
            $finalArr[$kk]['code'] = $cc['code'];
        }
        if(isset($finalArr[$kk]['code_name'])) {
            $finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
        } else {
            $finalArr[$kk]['code_name'] = $cc['code_name'];
        }
    }
}
echo "```";
print_r($finalArr);
echo "```";
?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)

I try this method, but not fix at 'code_name'

$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);

print_r($out);

Body:
Please try below one as another approach:

<?php
$arr = Array (
    Array
        (
            'name' => 'Jambi Selatan',
            'code' => '36139',
            'code_name' => '36139 - Jambi Selatan'
        ),
    Array
        (
            'name' => 'Jambi Selatan',
            'code' => '36137',
            'code_name' => '36137 - Jambi Selatan'
        ),
    Array
        (
            'name' => 'Bagan Pete',
            'code' => '36129',
            'code_name' => '36129 - Bagan Pete'
        ),
    Array
        (
            'name' => 'Bagan Pete',
            'code' => '36127',
            'code_name' => '36127 - Bagan Pete'
        )
);

$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
    $newarr[$aa['name']][] = $aa;
}

foreach($newarr as $kk => $bb) {
    foreach($bb as $cc) {
        $finalArr[$kk]['name'] = $cc['name'];

        if(isset($finalArr[$kk]['code'])) {
            $finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
        } else {
            $finalArr[$kk]['code'] = $cc['code'];
        }
        if(isset($finalArr[$kk]['code_name'])) {
            $finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
        } else {
            $finalArr[$kk]['code_name'] = $cc['code_name'];
        }
    }
}
echo "<pre>";
print_r($finalArr);
echo "</pre>";
?>

ContentLicense: CC BY-SA 3.0


问:
C# "Load" an object's property with text from a file during compilation
I want to load text from a file into a property on a class during compilation.

Example -

I have a file called banana.txt, the contents of which I'd like to put into a Banana class during compilation.

```<code>public class Banana
{
     public string Text { get; set; }  //contents of banana.txt goes in here
}
</code>```

How can this be done?

The purpose of this is so every time a Banana object's Text is needed, the file does not have to be read, the text from the file will only have to be read once during compile time.

(NOTE: I must read from the file, not copy the contents into a variable, or resource file. And I realize every Banana object will have the same text.)

答:
One way to achieve this would be:
Write a pre-build event.
In the pre-build event, invoke a program.
This program can be another C# program
This program would read from banana.txt.
Then this program would re-generate your source code.

for eg. if you have your code as:

```<code>public string Text = "~placeholder_for_Text~"
</code>```

the program would replace the "~placeholder_for_Text~" with the actual contents of banana.txt

Body:
I want to load text from a file into a property on a class during compilation.

Example -

I have a file called banana.txt, the contents of which I'd like to put into a Banana class during compilation.

public class Banana
{
     public string Text { get; set; }  //contents of banana.txt goes in here
}

How can this be done?

The purpose of this is so every time a Banana object's Text is needed, the file does not have to be read, the text from the file will only have to be read once during compile time.

(NOTE: I must read from the file, not copy the contents into a variable, or resource file. And I realize every Banana object will have the same text.)

Body:
One way to achieve this would be:
Write a pre-build event.
In the pre-build event, invoke a program.
This program can be another C# program
This program would read from banana.txt.
Then this program would re-generate your source code.

for eg. if you have your code as:

public string Text = "~placeholder_for_Text~"

the program would replace the "~placeholder_for_Text~" with the actual contents of banana.txt


问:
React - Empty Array When Rendering JSON Data
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

```<code>class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>
      <ul key={job.id}>
        <div class="company">{job.company_name}</div>
        <div class="title">{job.title}</div>
      </ul>
    );
    return(
      <div>{formattedJobs}</div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (
    <div className="app">
      <div className="header">
        <h1 id="header-title">Job Postings</h1>
      </div>
      <div className="content">
        <Jobs jobs={this.state.jobs}/>
      </div>
    </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

答:
You are getting the jobs from an ajax request wich is async. Thats why the initial value is an empty array.

App.render is executed before your ajax request is finished and thats why you are not givin any job to the Jobs component. Once the ajax is finished, the jobs array is filled with the results and sendeded to the Jobs component to render the results of that ajax request.

Body:
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>

{job.company_name}

{job.title}

    );
    return(

{formattedJobs}

    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (

Job Postings

        <Jobs jobs={this.state.jobs}/>

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);


问:
matplotlib: generate a new graph in a new window for subsequent program runs
I have a Python program that generates graphs using matplotlib. I am trying to get the program to generate a bunch of plots in one program run (the user is asked if they want to generate another graph) all in separate windows. Any way I can do this?</p>

答:
Using the latest matlibplot, I found the following to work for my purposes:</p>

```<code># create figure (will only create new window if needed)
plt.figure()
# Generate plot1
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

# create figure (will only create new window if needed)
plt.figure()
# Generate plot2
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

...

# Finally block main thread until all plots are closed
plt.show()
</code>```

Body:
Using the latest matlibplot, I found the following to work for my purposes:

# create figure (will only create new window if needed)
plt.figure()
# Generate plot1
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

# create figure (will only create new window if needed)
plt.figure()
# Generate plot2
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

...

# Finally block main thread until all plots are closed
plt.show()


问:
Webservice Parsing using Afnetworking stopped working
********************** Update  **********************

upon initial analysis i found that the website with https is not opening in iPhone,iPad or iPod if i tried hitting the website from app with just http i am able to load the JSON .

It seems like the concern is with HTTPS and i am able to get the DATA from HTTP URL

Simply

HTTPS://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz

  ---->   no response

HTTP://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,

  ---->    valid JSON

i cross checked the api as from my end Request is being sent on backend and valid JSON gets generated

i did this all by adding a mail function in the api file for each request made from my app is sent to me on mail with  intended response and request paramter .BUT in xcode i always getting Response null .Even it is not returning any kind of error or invalid content received in app.

********************** Original Question **********************

Our website migrated to new server.Now the previous working web-services are not working in iOS But are working FINE in POSTMAN .Below is my implementation

```<code> NSURL *url = [NSURL URLWithString:urlWithAction];
NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded",
                           @"cache-control": @"no-cache",
                           @"web-token": @"eb7524958-aghf-31fd8-00e4-e887df00035c"};

NSString *parmetersToPost=[NSString stringWithFormat:@"%@%@",postDataStr,appCommonParamters ];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[parmetersToPost   dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:3000.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
[[manager dataTaskWithRequest:request completionHandler:responseBlock] resume];
</code>```

i am getting the following error

2017-07-06 15:20:45.538 DE[4013:1659696] Error
  Domain=NSURLErrorDomain Code=-1017 "cannot parse response"
  UserInfo={NSErrorFailingURLStringKey=https://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,
  _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=https://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,
  NSLocalizedDescription=cannot parse response,
  _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x19266180 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)"
  UserInfo={_kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey={length = 16, capacity = 16, bytes =
  0x100201bb4834d0520000000000000000}, _kCFStreamErrorCodeKey=-1}}}

How can i troubleshoot the concern ,If i tried to check the webservices response on postman response is showing .

In Postman there is code section to make web request .i tried using postmen code but no luck and still getting the same error.

答:
Have you tried with adding ATS flag in project info.plist file for https .May be your server does not have SSL/TLS certificate installed.</p>

```<code><dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</code>```

Body:
********************** Update  **********************

upon initial analysis i found that the website with https is not opening in iPhone,iPad or iPod if i tried hitting the website from app with just http i am able to load the JSON .

It seems like the concern is with HTTPS and i am able to get the DATA from HTTP URL

Simply

HTTPS://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz

  ---->   no response

HTTP://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,

  ---->    valid JSON

i cross checked the api as from my end Request is being sent on backend and valid JSON gets generated

i did this all by adding a mail function in the api file for each request made from my app is sent to me on mail with  intended response and request paramter .BUT in xcode i always getting Response null .Even it is not returning any kind of error or invalid content received in app.

********************** Original Question **********************

Our website migrated to new server.Now the previous working web-services are not working in iOS But are working FINE in POSTMAN .Below is my implementation

 NSURL *url = [NSURL URLWithString:urlWithAction];
NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded",
                           @"cache-control": @"no-cache",
                           @"web-token": @"eb7524958-aghf-31fd8-00e4-e887df00035c"};

NSString *parmetersToPost=[NSString stringWithFormat:@"%@%@",postDataStr,appCommonParamters ];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[parmetersToPost   dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:3000.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
[[manager dataTaskWithRequest:request completionHandler:responseBlock] resume];

i am getting the following error

2017-07-06 15:20:45.538 DE[4013:1659696] Error
  Domain=NSURLErrorDomain Code=-1017 "cannot parse response"
  UserInfo={NSErrorFailingURLStringKey=https://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,
  _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=https://www.xzzx.xzzx.com/app/zxzx/zx.php/zx_xz,
  NSLocalizedDescription=cannot parse response,
  _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x19266180 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)"
  UserInfo={_kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey={length = 16, capacity = 16, bytes =
  0x100201bb4834d0520000000000000000}, _kCFStreamErrorCodeKey=-1}}}

How can i troubleshoot the concern ,If i tried to check the webservices response on postman response is showing .

In Postman there is code section to make web request .i tried using postmen code but no luck and still getting the same error.

Body:
Have you tried with adding ATS flag in project info.plist file for https .May be your server does not have SSL/TLS certificate installed.

<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


问:
AFNetworking 3.0 Error: “Request failed: internal server error (500)”
I am using Afnetwork 3. I am a new one for IOS development. I want to connect some API using POST method.

```<code>+(void)postExecuteWithParams:(NSString *)first  secondParm:(NSDictionary *)inParams onCompletion:(JSONResponseBlock)completionBlock {

NSString *baseURL = @"xyz";

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:first parameters:inParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     completionBlock(responseObject);

     //here is place for code executed in success case

 } failure:^(NSURLSessionDataTask *task, NSError *error) {

     NSLog(@"Error: %@", [error localizedDescription]);
 }];

}
</code>```

When I use this code I am getting the error like this

Error: Request failed: internal server error (500)

can i know what is the reason for this error and how can i modify it?

答: It clearly says there was some error from server. It can also happen if you didn't correctly send the parameters. So check if you are sending all the required parameters, its spelling & the case. Also check if you missed any headers</p>

Body:
I am using Afnetwork 3. I am a new one for IOS development. I want to connect some API using POST method.

+(void)postExecuteWithParams:(NSString *)first  secondParm:(NSDictionary *)inParams onCompletion:(JSONResponseBlock)completionBlock {

NSString *baseURL = @"xyz";

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:first parameters:inParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     completionBlock(responseObject);

     //here is place for code executed in success case

 } failure:^(NSURLSessionDataTask *task, NSError *error) {

     NSLog(@"Error: %@", [error localizedDescription]);
 }];

}

When I use this code I am getting the error like this

Error: Request failed: internal server error (500)

can i know what is the reason for this error and how can i modify it?


问:
how to use rowcount in mysql using python
We are implementing a database in a student record project. We want to see that how many rows are there in a table before and after deleting a row from a table.
The code we tried is as follows:

```<code>1  roll=5
2  m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
3  cur = m.cursor()
4  rc = cur.rowcount
5  print("%d"%rc)
6  e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
7  print("%d"%cur.rowcount)
</code>```

In the above code, the first rowcount in line 4 is giving -1 as the output and the rowcount in the last line is giving the no of rows that the table has after deleting a row.

Why is the first rowcount in line 4 give -1 as the output?

Any help shall be great.

答:
have your code include

```<code>m.commit()
cur.close()
m.close()
</code>```

If your code don't have these, maybe you can add them.
and your first 4 lines ,I think you should add

```<code>cur.execute('select * from 'table_name'')
cur.fetchall()
</code>```

then you can get the rowcount.I hope my answer can help you.

Body:
We are implementing a database in a student record project. We want to see that how many rows are there in a table before and after deleting a row from a table.
The code we tried is as follows:

1  roll=5
2  m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
3  cur = m.cursor()
4  rc = cur.rowcount
5  print("%d"%rc)
6  e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
7  print("%d"%cur.rowcount)

In the above code, the first rowcount in line 4 is giving -1 as the output and the rowcount in the last line is giving the no of rows that the table has after deleting a row.

Why is the first rowcount in line 4 give -1 as the output?

Any help shall be great.

Body:
have your code include

m.commit()
cur.close()
m.close()

If your code don't have these, maybe you can add them.
and your first 4 lines ,I think you should add

cur.execute('select * from 'table_name'')
cur.fetchall()

then you can get the rowcount.I hope my answer can help you.


问:
How to finish all activity when move to other modul via sidemenu
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

```<code>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.

答:
try this it requires API level >= 11.

```<code>Intent i = new Intent(OldActivity.this, NewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
</code>```

Body:
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.

Body:
try this it requires API level >= 11.

Intent i = new Intent(OldActivity.this, NewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);


问:
Processing key presses in C#
I'm making a game, and I have a class called MainCharacter that first initializes the main character (in a pictureBox) and then I had a KeyDown event for handling the movement. Inside that event, I was able to handle character movement if I pressed arrow keys, and I've even done a timer-based animation of movement to make it seem more smooth.

However, the problem with KeyDown event is that it fires every time I press the key, meaning that if I'm holding down the arrow key so that the character would continue moving in one direction, the event is fired repeatedly, meaning that the character runs over the screen like a torpedo, because the event is fired as fast as computer can handle it.

That's why I decided to use the KeyPress event, so that when I held the key down, the character would move in the designated direction at a steady velocity. However, KeyPress event can't handle arrow keys, which is why I had to override the ProcessDialogKey method in the main form. But if I override it in main form, then the event will be fired every time I press the arrow key, even when I'm not in the game, but for example in main menu or anywhere else. Beside, I think that would be bad practice, if I tried to program things through crossing classes so much anyway.

So, is there any other way for me to handle the KeyPress event on arrows inside my MainCharacter class without affecting other classes? Or is there a chance for me to stay with the KeyDown event, which I already had working, and make it so that it cannot fire repeatedly if I hold down the key? Remember, what I want to achieve is for my character to move fluently when I hold down my key. So far, it works fine, if I press it only once, but usually people hold down keys when they walk in one direction.

答: this.position.X += (this.direction * (this.speed+10));</p>

Title: Processing key presses in C#

ContentLicense: CC BY-SA 2.5


问:
Recipe compile error - Chef
I have 2 recipes in my cookbook namely - Get.rb and Post.rb.

Get.rb creates one file app.conf which is ultimately gets open in Post.rb.

So Post.rb depends on Get.rb, hence in my run-list I have placed Get.rb first and then Post.rb.

When I run chef-client, I am getting recipe compile error because the file app.conf is not present.

Looks like chef compiles both recipes simultaneously.
What is the way to solve this?

Edit :
 I have come this far:

```<code>ruby_block 'run' do
     action :nothing
     file = ::File.read('/etc/test.conf')
     data = JSON.parse(file) unless file.nil?
     puts data
     only_if { File.exist?('/etc/test.conf') }
end
</code>```

I am still getting the error. What could be the issue in this block?

答:
Did it with some editing:</p>

```<code>ruby_block 'run' do
   action :run
   block do
      file = ::File.read('/etc/test.conf')
      data = JSON.parse(file) unless file.nil?
      puts data
   end
   only_if { File.exist?('/etc/test.conf') }
end
</code>```

Title: Recipe compile error - Chef

Body:
I have 2 recipes in my cookbook namely - Get.rb and Post.rb.

Get.rb creates one file app.conf which is ultimately gets open in Post.rb.

So Post.rb depends on Get.rb, hence in my run-list I have placed Get.rb first and then Post.rb.

When I run chef-client, I am getting recipe compile error because the file app.conf is not present.

Looks like chef compiles both recipes simultaneously.
What is the way to solve this?

Edit :
 I have come this far:

ruby_block 'run' do
     action :nothing
     file = ::File.read('/etc/test.conf')
     data = JSON.parse(file) unless file.nil?
     puts data
     only_if { File.exist?('/etc/test.conf') }
end

I am still getting the error. What could be the issue in this block?

Body:
Did it with some editing:

ruby_block 'run' do
   action :run
   block do
      file = ::File.read('/etc/test.conf')
      data = JSON.parse(file) unless file.nil?
      puts data
   end
   only_if { File.exist?('/etc/test.conf') }
end


答:
When you are going to A -> SubA-1 you have to set flag like this

```<code>intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
</code>```

So it will not add your activity in your stack .

When you are going to SubA-2 -> B you have to set flag FLAG_ACTIVITY_NO_HISTORY

```<code>intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
</code>```

And in your B activity onbackpress set simple intent to Dashboard activity

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(this, DashboardActivity.class));
}
</code>```

Title: How to finish all activity when move to other modul via sidemenu

Body:
When you are going to A -> SubA-1 you have to set flag like this

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

So it will not add your activity in your stack .

When you are going to SubA-2 -> B you have to set flag FLAG_ACTIVITY_NO_HISTORY

intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

And in your B activity onbackpress set simple intent to Dashboard activity

@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(this, DashboardActivity.class));
}


问:
Retrofit2 - Requests are always status 404 and the response null
I saw 3 other SO posts regarding this but the solutions didn't work. Every endpoint is returned as status code 404 and the response is null in retrofit2. This is my retrofit implementation:

RetrofitService:

```<code>//code setup for HTTP client for Retrofit goes here
......
......
public static void initRetrofit() {
        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}
</code>```

BuildConfig

```<code>buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
        debug {
            versionNameSuffix ".staging"
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
}
</code>```

Endpoints:

```<code>public interface APIServices {

    @POST("api/users/register.json")
    Call<HttpResponse<Auth>> register(@Body RegisterData data);

}
</code>```

What am I doing wrong here? Other SO threads suggested to remove the / of /api from the /api/users/register.json, which I did and yet no change in the response.

答:
You didn't setup HTTP client for your Retrofit object. Try to use OkHttpClient for this.

```<code>public static void initRetrofit() {
    OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Config.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .build();

        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
                        .client(client)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}
</code>```

Plus, check your API address - try to use some service (e.g. Postman) for this: enter your address (from your code it is: 'http://MY_SERVICE.azurewebsites.netapi/users/register.json').

Body:
I saw 3 other SO posts regarding this but the solutions didn't work. Every endpoint is returned as status code 404 and the response is null in retrofit2. This is my retrofit implementation:

RetrofitService:

//code setup for HTTP client for Retrofit goes here
......
......
public static void initRetrofit() {
        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}

BuildConfig

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
        debug {
            versionNameSuffix ".staging"
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
}

Endpoints:

public interface APIServices {

    @POST("api/users/register.json")
    Call<HttpResponse<Auth>> register(@Body RegisterData data);

}

What am I doing wrong here? Other SO threads suggested to remove the / of /api from the /api/users/register.json, which I did and yet no change in the response.

Body:
You didn't setup HTTP client for your Retrofit object. Try to use OkHttpClient for this.

public static void initRetrofit() {
    OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Config.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .build();

        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
                        .client(client)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}

Plus, check your API address - try to use some service (e.g. Postman) for this: enter your address (from your code it is: 'http://MY_SERVICE.azurewebsites.netapi/users/register.json').


问:
Why aren't the Server and X-Powered-By headers being removed?
My ASP.NET 4.5 app is being deployed to shared hosting so I do not have access to IIS settings. To remove the X-Powered-By header, I specify in web.config:

```<code><system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
</code>```

And to remove the Server header, I specify in Global.asax:

```<code>protected void Application_PreSendRequestHeaders(object sender, EventArgs e) {
  HttpContext.Current.Response.Headers.Remove("Server");
}
</code>```

However, responses still contain both headers:

Cache-Control:private
Content-Encoding:deflate
Content-Length:672
Content-Type:text/html; charset=utf-8
Date:Sun, 06 Jan 2013 00:41:20 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ARR/2.5
X-Powered-By:ASP.NET
```

How can I remove them?

答:
Mostly server IIS doesn't allow us to remove server tags. You can try following code to achieve your goal.
Add in Global.asax

```<code>protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("X-AspNet-Version");
     HttpContext.Current.Response.Headers.Set("Server", "");
 }
</code>```

This code will remove your "X-AspNet-Version" and set Server value as blank.

Body:
My ASP.NET 4.5 app is being deployed to shared hosting so I do not have access to IIS settings. To remove the X-Powered-By header, I specify in web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

And to remove the Server header, I specify in Global.asax:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e) {
  HttpContext.Current.Response.Headers.Remove("Server");
}

However, responses still contain both headers:

Cache-Control:private
Content-Encoding:deflate
Content-Length:672
Content-Type:text/html; charset=utf-8
Date:Sun, 06 Jan 2013 00:41:20 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ARR/2.5
X-Powered-By:ASP.NET

How can I remove them?

Body:
Mostly server IIS doesn't allow us to remove server tags. You can try following code to achieve your goal.
Add in Global.asax

protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("X-AspNet-Version");
     HttpContext.Current.Response.Headers.Set("Server", "");
 }

This code will remove your "X-AspNet-Version" and set Server value as blank.


问:
jQuery Value Help
I'm having problems getting the value of the input field.

```<code>function Send(id){
var send_to=$("#id").val();
$.post("send.php", { id:id }, function(data) { if(data==="OK"){  } else { } });
}
</code>```

Below is an example of the page.

```<code><input type=text id=4543><button onclick=Send(4543);>SEND</button>
<input type=text id=8643><button onclick=Send(8643);>SEND</button>
<input type=text id=8645><button onclick=Send(8645);>SEND</button>
<input type=text id=2421><button onclick=Send(2421);>SEND</button>
</code>```

I need to get the value of the input control whose id is passed to the send method.

Thank you! :)

答:
If I understood correctly, then:

```<code>var send_to=$("#id").val();
</code>```

should be

```<code>var send_to=$("#" + id).val();
</code>```

Title: jQuery Value Help

Body:
I'm having problems getting the value of the input field.

function Send(id){
var send_to=$("#id").val();
$.post("send.php", { id:id }, function(data) { if(data==="OK"){  } else { } });
}

Below is an example of the page.

<input type=text id=4543><button onclick=Send(4543);>SEND</button>
<input type=text id=8643><button onclick=Send(8643);>SEND</button>
<input type=text id=8645><button onclick=Send(8645);>SEND</button>
<input type=text id=2421><button onclick=Send(2421);>SEND</button>

I need to get the value of the input control whose id is passed to the send method.

Thank you! :)

Body:
If I understood correctly, then:

var send_to=$("#id").val();

should be

var send_to=$("#" + id).val();


问:
Ionic V1 $http post json data params
I have 2 objects generated by sqlite execution:

```<code>var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}

var participantes = [
    {id: "10",
     nome: "Antonio",
     idade: "4",
     ativo: 1,
     msg: "Backorder"
     },
    {id: "11",
     nome: "Carlos",
     idade: "1",
     ativo: 1,
     msg: "Flagged"
    }
]
</code>```

For send the object I use this method on service:

```<code>var headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        };
    return $http({
        method: "POST",
        url: "remote_url.com/action",
        data: {info_update: info_update, participantes: participantes},
        headers : headers
    })
</code>```

What's the problem?

The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image

I need send ALL data for serve.
How i do it?

答: Your participantes is not object its array try changing it to object using .map function

Title: Ionic V1 $http post json data params

Body:
I have 2 objects generated by sqlite execution:

var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}

var participantes = [
    {id: "10",
     nome: "Antonio",
     idade: "4",
     ativo: 1,
     msg: "Backorder"
     },
    {id: "11",
     nome: "Carlos",
     idade: "1",
     ativo: 1,
     msg: "Flagged"
    }
]

For send the object I use this method on service:

var headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        };
    return $http({
        method: "POST",
        url: "remote_url.com/action",
        data: {info_update: info_update, participantes: participantes},
        headers : headers
    })

What's the problem?

The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image

I need send ALL data for serve.
How i do it?


问:
Access a Named Control Inside a XAML DataTemplate
I managed to access control in the datatemplate of a GridViewItem, the following code:

```<code>private void btnChangePhoneNumber_Click(object sender, RoutedEventArgs e)
    {
        GridCell.SelectedItem = GridCell.Items[3];
        var container = GridCell.ContainerFromIndex(3);
        var _children = AllChildren(container);
        var _control = _children.First(c => c.Name == "PhoneNumber");
        _control.text = "123456789";
    }

public List<TextBlock> AllChildrenText(DependencyObject parent)
    {
        var _List = new List<TextBlock> { };
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var _Child = VisualTreeHelper.GetChild(parent, i);
            if (_Child is TextBlock)
            {
                _List.Add(_Child as TextBlock);
            }

            _List.AddRange(AllChildrenText(_Child));
        }
        return _List;
    }
</code>```

where the GridCell is a Gridview.

This work.. but..

If I implement GridView with less than 40 items it's all right.
Unlike if I implement gridView with 10000 items, the text change that happens with the method: btnChangePhoneNumber_Click, also happens in other items ... and I can not understand the reason since, in the btnChangePhoneNumber_Click method, only one item is chosen.

Thanks in advance. A greeting.

答:
I have tested your code, but I could not reproduce your issue in my side. As far as I'm concerned, It is low performance to render 10000 items in your GridView. And using VisualTreeHelper will bring about worse performance. You could bind
the text of TextBlock in the datatemplate with mvvm ViewModel. You just need
to modify the view model and the text of TextBlock will be changed. For more please refer to Data binding in depth. And the following is segment code of ViewModel.

MainPageViewModel.cs

```<code>public class MainPageViewModel : ViewModelBase
{
    private ObservableCollection<Phone> _items;
    public ObservableCollection<Phone> Items
    {
        get
        {
            return _items;
        }
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }
    public MainPageViewModel()
    {
        var list = new ObservableCollection<Phone>();
        for (var i = 0; i < 1000; i++)
        {
            list.Add(new Phone { PhoneNumber = "123456" });
        }
        _items = list;
    }

}
</code>```

MainPage.xaml

```<code><Page.DataContext>
    <local:MainPageViewModel x:Name="ViewModel"/>
</Page.DataContext>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Click="btnChangePhoneNumber_Click" Content=" click me"/>
    <GridView x:Name="GridCell" Height="400" ItemsSource="{Binding Items}" >
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="local:Phone">
                <TextBlock Text="{x:Bind PhoneNumber ,Mode=OneWay}"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</StackPanel>
</code>```

I have upload the code sample to github. Please check!

Body:
I managed to access control in the datatemplate of a GridViewItem, the following code:

private void btnChangePhoneNumber_Click(object sender, RoutedEventArgs e)
    {
        GridCell.SelectedItem = GridCell.Items[3];
        var container = GridCell.ContainerFromIndex(3);
        var _children = AllChildren(container);
        var _control = _children.First(c => c.Name == "PhoneNumber");
        _control.text = "123456789";
    }

public List<TextBlock> AllChildrenText(DependencyObject parent)
    {
        var _List = new List<TextBlock> { };
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var _Child = VisualTreeHelper.GetChild(parent, i);
            if (_Child is TextBlock)
            {
                _List.Add(_Child as TextBlock);
            }

            _List.AddRange(AllChildrenText(_Child));
        }
        return _List;
    }

where the GridCell is a Gridview.

This work.. but..

If I implement GridView with less than 40 items it's all right.
Unlike if I implement gridView with 10000 items, the text change that happens with the method: btnChangePhoneNumber_Click, also happens in other items ... and I can not understand the reason since, in the btnChangePhoneNumber_Click method, only one item is chosen.

Thanks in advance. A greeting.

Body:
I have tested your code, but I could not reproduce your issue in my side. As far as I'm concerned, It is low performance to render 10000 items in your GridView. And using VisualTreeHelper will bring about worse performance. You could bind
the text of TextBlock in the datatemplate with mvvm ViewModel. You just need
to modify the view model and the text of TextBlock will be changed. For more please refer to Data binding in depth. And the following is segment code of ViewModel.

MainPageViewModel.cs

public class MainPageViewModel : ViewModelBase
{
    private ObservableCollection<Phone> _items;
    public ObservableCollection<Phone> Items
    {
        get
        {
            return _items;
        }
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }
    public MainPageViewModel()
    {
        var list = new ObservableCollection<Phone>();
        for (var i = 0; i < 1000; i++)
        {
            list.Add(new Phone { PhoneNumber = "123456" });
        }
        _items = list;
    }

}

MainPage.xaml

<Page.DataContext>
    <local:MainPageViewModel x:Name="ViewModel"/>
</Page.DataContext>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Click="btnChangePhoneNumber_Click" Content=" click me"/>
    <GridView x:Name="GridCell" Height="400" ItemsSource="{Binding Items}" >
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="local:Phone">
                <TextBlock Text="{x:Bind PhoneNumber ,Mode=OneWay}"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</StackPanel>

I have upload the code sample to github. Please check!


问:
save image in local machine
I have made an application that convert a text into image format now how do i save the converted image in my local machine,</p>

答: I assume you are using GD image functions to create the image? So if you are already getting PHP to display the image, you can encourage the browser to download it instead by adding header('Content-Disposition: attachment; filename="filename.fileext"'); to the top of your file. This will encourage the browser to pop up a download box. The filename attribute is the name that the browser will prompt to save the image as

Title: save image in local machine


问:
How to achieve inheritance in javascript using OLOO pattern
I am trying to achieve inheritance of this code snippet

function parent(name) {
  this.name = name;

}

function child(childname) {
  parent.call(this, "cde");
  this.childname = childname;
}

var p1 = new parent("abc");
child.prototype = Object.create(parent.prototype);
var p2 = new child("def");

console.log(p1.name);

console.log(p2.name);```
</div>
</div>
</p>

<p>Using OLOO patternOLOO pattern</p>

<p>Here is my try for it</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function person(name) {
  this.name = name;
}

var p1 = new person("abc");

var p2;

p2 = Object.create(person);

console.log(p2.name);
p2.childname = "def";</code>```

While creating p2 object here im not sending name to it. How can send name to it while creating p2 object .

Can some one please explain is this the right approach to achieve inheritance using OLOO pattern

Thanks

答:
Both the current answers posted here are "correct" in that they appropriately apply object-only prototype linkage (without constructors). I would make two points of clarification, though:

I would never recommend "shadowing" of properties (or methods, for that matter), meaning having both p1 and p2 objects having a .name property on them. This is one of the most common sources of confusion, IME, with JS prototypes. I always recommend using different property names on each object in a prototype chain.

OLOO is not just about wiring up a traditional "inheritance" hierarchy without using constructors, as the OP appears to be doing. That's valid, but a very reduced, simplified view of OLOO. OLOO is really intended to build off that capability to model software differently than with "classes". The point of OLOO is so that you set up two peer objects where one can delegate to the other (and vice versa, if you like) so they can virtually compose during the call-time of a method; aka: Behavior Delegation. Consult Chapter 6 of my "YDKJS: this & Object Prototypes" book for more info.

Body:
I am trying to achieve inheritance of this code snippet

function parent(name) {
  this.name = name;

}

function child(childname) {
  parent.call(this, "cde");
  this.childname = childname;
}

var p1 = new parent("abc");
child.prototype = Object.create(parent.prototype);
var p2 = new child("def");

console.log(p1.name);

console.log(p2.name);

Using OLOO patternOLOO pattern

Here is my try for it

function person(name) {
  this.name = name;
}

var p1 = new person("abc");

var p2;

p2 = Object.create(person);

console.log(p2.name);
p2.childname = "def";

While creating p2 object here im not sending name to it. How can send name to it while creating p2 object .

Can some one please explain is this the right approach to achieve inheritance using OLOO pattern

Thanks


问:
TemplateDoesNotExist at /polls/
I have been trying out the Django tutorialDjango Tutorial Page 3 and encountered this error

"TemplateDoesNotExist at /polls/ " .

I assume the problem is with my code pointing the templates file index.html. This is my file structure for index.html:  mysite/polls/templates/polls.
I am copying my settings.py and views.py here.

settings.py

```<code>TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
</code>```

views. Py

```<code>from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader

from polls.models import Poll

# Create your views here.

#def index(request):
    #return HttpResponse("Hello, world. You are at the poll index.")

def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(template.render(context))

def detail(request,poll_id):
    return HttpResponse("You're looking at the results of the poll %s." % poll_id)

def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request,poll_id):
    return HttpResponse("You're voting on poll %s." % poll_id)
</code>```

Can someone look into it and help me to solve this error. Any help would be appreciated.
This is the traceback `Environment:

```<code>Request Method: GET
Request URL: http://localhost:8000/polls/

Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)

Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
  14.     template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
  138.     template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
  131.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`
</code>```

Please let me know if i missed out anything that would give a more clear picture. Thanks in advance.

Settings.py """

```<code>Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
</code>```

答:
You forgot to add your app config in the INSTALLED_APP in settings.py

INSTALLED_APPS = (

```<code>'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
</code>```

)

The startapp command creates an apps.py file. Since it doesn’t use default_app_config (a
  discouraged API), you must specify the app config’s path, e.g. 'polls.apps.PollsConfig', in
  INSTALLED_APPS for it to be used (instead of just 'polls').

Title: TemplateDoesNotExist at /polls/

Body:
I have been trying out the Django tutorialDjango Tutorial Page 3 and encountered this error

"TemplateDoesNotExist at /polls/ " .

I assume the problem is with my code pointing the templates file index.html. This is my file structure for index.html:  mysite/polls/templates/polls.
I am copying my settings.py and views.py here.

settings.py

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

views. Py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader

from polls.models import Poll

# Create your views here.

#def index(request):
    #return HttpResponse("Hello, world. You are at the poll index.")

def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(template.render(context))

def detail(request,poll_id):
    return HttpResponse("You're looking at the results of the poll %s." % poll_id)

def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request,poll_id):
    return HttpResponse("You're voting on poll %s." % poll_id)

Can someone look into it and help me to solve this error. Any help would be appreciated.
This is the traceback `Environment:

Request Method: GET
Request URL: http://localhost:8000/polls/

Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)

Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
  14.     template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
  138.     template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
  131.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`

Please let me know if i missed out anything that would give a more clear picture. Thanks in advance.

Settings.py """

Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

Body:
You forgot to add your app config in the INSTALLED_APP in settings.py

INSTALLED_APPS = (

'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

)

The startapp command creates an apps.py file. Since it doesn’t use default_app_config (a
  discouraged API), you must specify the app config’s path, e.g. 'polls.apps.PollsConfig', in
  INSTALLED_APPS for it to be used (instead of just 'polls').


问:
how to select not null values column dynamically?
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

```<code>create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;
</code>```

data like below

```<code>NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)
</code>```

Expected op:

```<code>NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10
</code>```

答:
Try This,

 I have checked and exactly match your output.

    ```select no,"NAME",sal_1 from sample having count(sal_1)>0  group by
sal_1,name,no order by name desc ```

Body:
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;

data like below

NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)

Expected op:

NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10

Body:
Try This,

 I have checked and exactly match your output.

select no,"NAME",sal_1 from sample having count(sal_1)>0  group by
sal_1,name,no order by name desc


问:
How can I consistently handle vertical scroll bars in table with scrollable tbody?
I have a table with a thead and tbody. The table with thead is "fixed", but the div that contains the table with the tbody scrolls. The problem is that I cannot find a consistent way to handle the scroll bars. For example, if the user has (via their system settings) the scrollbars set to always show, then the columns inside the tbody are pushed to the left. If they have their scroll bars set to only show on scroll, then it looks fine.

Here is a simplified version of what I'm trying to do:

```<code><div class="this_is_fixed">
    <table class="my_table">
        <thead>
            <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </thead>
    </table>
</div>
<div class="scroll_container">
    <div class="scroll">
        <table class="my_table">
            <tbody>
                <tr>
                    <td>Col 1</td>
                    <td>Col 2</td>
                    <td>Col 3</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

CSS:

```<code>.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}
</code>```

The table inside .scroll is shifted to the left if the user has their scrollbars set to always show, but is fine if they have it set to only show scrollbars when scrolling. Is there a consistent way for me to handle this (cross browser)? I don't want solutions that involve hiding the scroll bars. Thanks in advance for any solutions!

答:
This issue, in a generic sense, comes up often. For instance, when a full-screen overlay is used to hide the content behind a modal dialog. We might set the page to hide overflow to match the overlay size and prevent scrolling from interfering with the desired appearance. As a result, a scrollbar that was there suddenly disappears and the screen "jumps" as all the content shifts.

As with the way Bootstrap addresses the problem, the most robust solution is to measure the scrollbar width using JS and a dummy/hidden div that will always increase it's size to include the scrollbar if the useragent is configured to show them. Then you can adjust your margins, etc, to account for that width (you would also need to determine whether the content is overflowing its container, otherwise you'll adjust for a scrollbar that isn't there.) Easy enough with a some additional JS, but you'd have to recheck anytime the window resizes or the table content changes.

Anyway, borrowing some code from https://github.com/stempler/bootstrap

```<code>.modal-scrollbar-measure {
  position: absolute;
  top: -9999px;
  width: 50px;
  height: 50px;
  overflow: scroll;
}
</code>```

--

```<code>function measureScrollbar() {
  var scrollDiv = angular.element('<div class="'+MEASURE_SCROLLBAR_CLASS+'"></div>');
  bodyEl.append(scrollDiv);
  var width = scrollDiv[0].offsetWidth - scrollDiv[0].clientWidth;
  console.log('measureScrollbar', width);
  scrollDiv.remove();
  return width;
}
</code>```

There may be a much simpler solution that involves creative CSS to force everything to align, but I'm not seeing it at the moment since you have everything relative positioned within absolute containers. This answer more-or-less just addresses the general problem of "I don't want things to shift when a scrollbar appears".

Body:
I have a table with a thead and tbody. The table with thead is "fixed", but the div that contains the table with the tbody scrolls. The problem is that I cannot find a consistent way to handle the scroll bars. For example, if the user has (via their system settings) the scrollbars set to always show, then the columns inside the tbody are pushed to the left. If they have their scroll bars set to only show on scroll, then it looks fine.

Here is a simplified version of what I'm trying to do:

                Col 1
                Col 2
                Col 3

                    Col 1
                    Col 2
                    Col 3

CSS:

.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}

The table inside .scroll is shifted to the left if the user has their scrollbars set to always show, but is fine if they have it set to only show scrollbars when scrolling. Is there a consistent way for me to handle this (cross browser)? I don't want solutions that involve hiding the scroll bars. Thanks in advance for any solutions!

Body:
This issue, in a generic sense, comes up often. For instance, when a full-screen overlay is used to hide the content behind a modal dialog. We might set the page to hide overflow to match the overlay size and prevent scrolling from interfering with the desired appearance. As a result, a scrollbar that was there suddenly disappears and the screen "jumps" as all the content shifts.

As with the way Bootstrap addresses the problem, the most robust solution is to measure the scrollbar width using JS and a dummy/hidden div that will always increase it's size to include the scrollbar if the useragent is configured to show them. Then you can adjust your margins, etc, to account for that width (you would also need to determine whether the content is overflowing its container, otherwise you'll adjust for a scrollbar that isn't there.) Easy enough with a some additional JS, but you'd have to recheck anytime the window resizes or the table content changes.

Anyway, borrowing some code from https://github.com/stempler/bootstrap

.modal-scrollbar-measure {
  position: absolute;
  top: -9999px;
  width: 50px;
  height: 50px;
  overflow: scroll;
}

--

function measureScrollbar() {
  var scrollDiv = angular.element('<div class="'+MEASURE_SCROLLBAR_CLASS+'"></div>');
  bodyEl.append(scrollDiv);
  var width = scrollDiv[0].offsetWidth - scrollDiv[0].clientWidth;
  console.log('measureScrollbar', width);
  scrollDiv.remove();
  return width;
}

There may be a much simpler solution that involves creative CSS to force everything to align, but I'm not seeing it at the moment since you have everything relative positioned within absolute containers. This answer more-or-less just addresses the general problem of "I don't want things to shift when a scrollbar appears".


问:
How can I selectively merge or pick changes from another branch in Git?
I'm using Git on a new project that has two parallel -- but currently experimental -- development branches:

master: import of existing codebase plus a few modifications that I'm generally sure of

exp1: experimental branch #1

exp2: experimental branch #2

exp1 and exp2 represent two very different architectural approaches. Until I get further along I have no way of knowing which one (if either) will work. As I make progress in one branch I sometimes have edits that would be useful in the other branch and would like to merge just those.

What is the best way to merge selective changes from one development branch to another while leaving behind everything else?

Approaches I've considered:

git merge --no-commit followed by manual unstaging of a large number of edits that I don't want to make common between the branches.

Manual copying of common files into a temporary directory followed by git checkout to move to the other branch and then more manual copying out of the temporary directory into the working tree.

A variation on the above. Abandon the exp branches for now and use two additional local repositories for experimentation.  This makes the manual copying of files much more straightforward.

All three of these approaches seem tedious and error-prone.  I'm hoping there is a better approach; something akin to a filter path parameter that would make git-merge more selective.

答:
You use the cherry-pick command to get individual commits from one branch.

If the change(s) you want are not in individual commits, then use the method shown here to split the commit into individual commits. Roughly speaking, you use git rebase -i to get the original commit to edit, then git reset HEAD^ to selectively revert changes, then git commit to commit that bit as a new commit in the history.

There is another nice method here in Red Hat Magazine, where they use git add --patch or possibly git add --interactive which allows you to add just parts of a hunk, if you want to split different changes to an individual file (search in that page for "split").

Having split the changes, you can now cherry-pick just the ones you want.

OwnerDisplayName: David Joyner

OwnerDisplayName: 1800 INFORMATION


问:
Is there any way to get numbers separated by comma?
I have

```<code>line = "abcde:abc/abcd=(12, 20)"
</code>```

and I want to get 12 and 20 in an array. My solution is:

```<code>array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")
</code>```

Is there any better way to solve it using ruby?

Body:
I have

line = "abcde:abc/abcd=(12, 20)"

and I want to get 12 and 20 in an array. My solution is:

array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")

Is there any better way to solve it using ruby?

Body:
Just out of curiosity:

require 'json'
JSON.parse "[#{'abcde:abc/abcd=(12, 20)'[/(?<=\().*?(?=\))/]}]"
#⇒ [12, 20]


问:
parse data from Dictionary in python
So i have this dictionary "runs":

```<code>[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }
</code>```

there is "id" for about 50 times. that is just a part of it.
i need to find all "id":s (Not joku_ids, ncie_ids etc. Only "id") and make  a string/dict of them
and same for name, and description

i have tried:

```<code>j = json.load(run)
ids = (j["id"])

j = json.load(run)
names = (j["name"])

j = json.load(run)
descriptions = (j["description"])
</code>```

but it returns:

```<code>AttributeError: 'list' object has no attribute 'read'
</code>```

I also need to send a request with specific id and in this case the specific id is marked by o. so id[o]
the request code is below:

```<code>test = client.send_get('get_tests/1/ ')
</code>```

so i need to have the id[o] instead of the 1.
i have tried

```<code>test = client.send_get('get_tests/' + id[o] + '/ ')
</code>```

but it returns:

```<code>TypeError: 'int' object is not subscriptable
</code>```

答:
If you want your result in list of dictionary then:

```<code>result = [{x:y} for i in range(len(data)) for x,y in data[i].items() if x=='id' or x=='name' or x=='description']
</code>```

output:

```<code>[{'name': 'name'}, {'id': 12}, {'description': 'desc.'}, {'name': 'namae)'}, {'id': 16}, {'description': 'desc1'}]
</code>```

the data is your list of dictionary data.
hope this answer helpful for you.

Title: parse data from Dictionary in python

Body:
So i have this dictionary "runs":

[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }

there is "id" for about 50 times. that is just a part of it.
i need to find all "id":s (Not joku_ids, ncie_ids etc. Only "id") and make  a string/dict of them
and same for name, and description

i have tried:

j = json.load(run)
ids = (j["id"])

j = json.load(run)
names = (j["name"])

j = json.load(run)
descriptions = (j["description"])

but it returns:

AttributeError: 'list' object has no attribute 'read'

I also need to send a request with specific id and in this case the specific id is marked by o. so id[o]
the request code is below:

test = client.send_get('get_tests/1/ ')

so i need to have the id[o] instead of the 1.
i have tried

test = client.send_get('get_tests/' + id[o] + '/ ')

but it returns:

TypeError: 'int' object is not subscriptable

Body:
If you want your result in list of dictionary then:

result = [{x:y} for i in range(len(data)) for x,y in data[i].items() if x=='id' or x=='name' or x=='description']

output:

[{'name': 'name'}, {'id': 12}, {'description': 'desc.'}, {'name': 'namae)'}, {'id': 16}, {'description': 'desc1'}]

the data is your list of dictionary data.
hope this answer helpful for you.


问:
How create a mdl checkbox element
By getmdl.io, a checkbox element is:

#d{
padding:20px```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>
<div id="d">
<label for="chkbox1" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 <span class="mdl-checkbox__label">Checkbox</span>
</label></code>```

and i try to add this element with js

function addCB(){
  var cb = document.createElement('div');
  cb.innerHTML = `
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox
`;
  document.getElementById('d').appendChild(cb);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#d{
padding:20px</code>```

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

<button class="mdl-button mdl-js-button mdl-js-ripple-effect " onClick="addCB()">Add checkbox</button>```

but the design doesn't work, idk why, can anyone help me?

答:
I managed to get the effect you wanted by using the following two additional lines:

```<code>componentHandler.upgradeDom('MaterialCheckbox');
componentHandler.upgradeAllRegistered();
</code>```

Here is some information about componentHandler.

Here is a working pen.

Title: How create a mdl checkbox element

Body:
By getmdl.io, a checkbox element is:

#d{
padding:20px

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox

and i try to add this element with js

function addCB(){
  var cb = document.createElement('div');
  cb.innerHTML = `
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox
`;
  document.getElementById('d').appendChild(cb);
}

#d{
padding:20px

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

<button class="mdl-button mdl-js-button mdl-js-ripple-effect " onClick="addCB()">Add checkbox</button>

but the design doesn't work, idk why, can anyone help me?

Body:
I managed to get the effect you wanted by using the following two additional lines:

componentHandler.upgradeDom('MaterialCheckbox');
componentHandler.upgradeAllRegistered();

Here is some information about componentHandler.

Here is a working pen.


问:
How can you emulate object serialization on java in C#
I need to call a servlet call for an automation of a java applet using c#. What the java applet is it calls a servlet using a URL Connection object.

```<code>URL servlet = new URL(servletProtocol, servletHost, servletPort, "/" + ServletName);
URLConnection con = servlet.openConnection();
con.setDoOutput(true);
ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
// Write several parameters strings
out.writeObject(param[0]);
out.writeObject(param[1]);
out.flush();
out.close();
</code>```

The problem is i need to simulate this using c#. I believe the counterpart object would be HttpWebRequest

```<code>HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(servletPath);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(param[0],0,param[0].length);
newStream.Write(param[1],0,param[1].length);
newStream.Close();
</code>```

How do I write the string as a serialized java string? Is there any workaround here? According to the documentation of ObjectOutputStream in java, it serialize the object except for primitive type. I know String is class, so does it serialzie it like an object or some special case?

I have tried one solution, I have imported the IKVM (http://www.ikvm.net/) java virtual machine in my reference and am trying to use the java.io library in Java. Unforunately, when the ObjectInputStream constructor is called, a "invalid stream header" is thrown.

Here is my altered code:

```<code>myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();

// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

byte[] bArr = lByte.ToArray();
ObjectInputStream inputStream = null;

try
{
    //Construct the ObjectInputStream object
    inputStream = new ObjectInputStream(new ByteArrayInputStream(bArr));

    Object obj = null;

    while ((obj = inputStream.readObject()) != null)
    {
        string objStr = obj as string;
    }

}
catch (java.lang.Exception ex)
</code>```

答:
If you have control over the serialization/deserialization on the Java side, your best bet is to use a cross-platform serialization protocol such as Protocol Buffers. For C++, Java, and Python:

http://code.google.com/p/protobuf/

For .NET, Jon Skeet wrote a port:

http://code.google.com/p/protobuf-net/

Body:
I need to call a servlet call for an automation of a java applet using c#. What the java applet is it calls a servlet using a URL Connection object.

URL servlet = new URL(servletProtocol, servletHost, servletPort, "/" + ServletName);
URLConnection con = servlet.openConnection();
con.setDoOutput(true);
ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
// Write several parameters strings
out.writeObject(param[0]);
out.writeObject(param[1]);
out.flush();
out.close();

The problem is i need to simulate this using c#. I believe the counterpart object would be HttpWebRequest

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(servletPath);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(param[0],0,param[0].length);
newStream.Write(param[1],0,param[1].length);
newStream.Close();

How do I write the string as a serialized java string? Is there any workaround here? According to the documentation of ObjectOutputStream in java, it serialize the object except for primitive type. I know String is class, so does it serialzie it like an object or some special case?

I have tried one solution, I have imported the IKVM (http://www.ikvm.net/) java virtual machine in my reference and am trying to use the java.io library in Java. Unforunately, when the ObjectInputStream constructor is called, a "invalid stream header" is thrown.

Here is my altered code:

myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();

// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

byte[] bArr = lByte.ToArray();
ObjectInputStream inputStream = null;

try
{
    //Construct the ObjectInputStream object
    inputStream = new ObjectInputStream(new ByteArrayInputStream(bArr));

    Object obj = null;

    while ((obj = inputStream.readObject()) != null)
    {
        string objStr = obj as string;
    }

}
catch (java.lang.Exception ex)


问:
How to get client's IP in a golang thrift server
I'm writing a thrift service in golang and I would like to understand how I can get the client's IP address in the handler functions context.

Thanks, Love.

答:
I think you're using this Godoc Thrift library. It would be good to have code snippets in your question; such as type of thrift server, handler definition, etc.

As per Thrift Go library doc-

func (p *TSocket) Addr() net.Addr

Returns the remote address of the socket.

So if you have access to TSocket then you can get remote address.


问:
Find multiple files open write new line save
In Linux I need to write a new line in the same file saved in multiple different directories.

They are saved for example in:

```<code>Home/user1/settings/settings.ini
Home/user2/settings/settings.ini
...
Home/user500/settings/settings.ini
</code>```

How can I do it?

答:
With find:</p>

```<code>find /home/*/settings -name 'settings.ini' -exec sh -c 'echo >> {}' \;
</code>```

Body:
In Linux I need to write a new line in the same file saved in multiple different directories.

They are saved for example in:

Home/user1/settings/settings.ini
Home/user2/settings/settings.ini
...
Home/user500/settings/settings.ini

How can I do it?

Body:
With find:

find /home/*/settings -name 'settings.ini' -exec sh -c 'echo >> {}' \;


问:
Boolean value not getting mapped properly in Hibernate with MySQL
I am trying to map the result of an exists query (which returns TRUE/FALSE) from a MySQL database to a POJO via resultSetTransformer. I would hope the result of this exists query can get mapped to a boolean but it does not and throws the below error:

org.hibernate.PropertyAccessException: IllegalArgumentException
  occurred while calling setter of TestBean.value

The cause of this exception is shown as:

java.lang.IllegalArgumentException: argument type mismatch

My sample class:

```<code>public class TestHibernate {

    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public static void main(String[] args) throws ParseException {
        try {
            Query query = sessionFactory.openSession().createSQLQuery(
                "SELECT " +
                "EXISTS (SELECT * FROM A WHERE id = 3) AS value"
            );

            query.setResultTransformer(Transformers.aliasToBean(TestBean.class));
            List<TestBean> beanList = (List<TestBean>) query.list();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}
</code>```

The POJO:

```<code>public class TestBean {

    private boolean value;

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }

}
</code>```

Am I missing something or is it a bug with Hibernate or MySQL JDBC Driver?

Hibernate version: 3.2.6GA

MySQL JDBC Driver: mysql-connector-java-5.1.2

答:
The transform of the result query can be explicitly set each parameter to the corresponding model datatype using hibernate addScalar() method. Please find the solution below.

```<code>    Query query = sessionFactory.openSession().createSQLQuery(""+
                "select " +
                " exists(select * from A where id = 3) as value"
                ).addScalar("value",  BooleanType.INSTANCE);
</code>```

This will resolve to set to the Boolean value.

Body:
I am trying to map the result of an exists query (which returns TRUE/FALSE) from a MySQL database to a POJO via resultSetTransformer. I would hope the result of this exists query can get mapped to a boolean but it does not and throws the below error:

org.hibernate.PropertyAccessException: IllegalArgumentException
  occurred while calling setter of TestBean.value

The cause of this exception is shown as:

java.lang.IllegalArgumentException: argument type mismatch

My sample class:

public class TestHibernate {

    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public static void main(String[] args) throws ParseException {
        try {
            Query query = sessionFactory.openSession().createSQLQuery(
                "SELECT " +
                "EXISTS (SELECT * FROM A WHERE id = 3) AS value"
            );

            query.setResultTransformer(Transformers.aliasToBean(TestBean.class));
            List<TestBean> beanList = (List<TestBean>) query.list();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}

The POJO:

public class TestBean {

    private boolean value;

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }

}

Am I missing something or is it a bug with Hibernate or MySQL JDBC Driver?

Hibernate version: 3.2.6GA

MySQL JDBC Driver: mysql-connector-java-5.1.2

Body:
The transform of the result query can be explicitly set each parameter to the corresponding model datatype using hibernate addScalar() method. Please find the solution below.

    Query query = sessionFactory.openSession().createSQLQuery(""+
                "select " +
                " exists(select * from A where id = 3) as value"
                ).addScalar("value",  BooleanType.INSTANCE);

This will resolve to set to the Boolean value.


问:
TimeSpan to UTC milliseconds
I currently have a TimeSpan variable that holds the time set from a TimePicker. I need a long similar to the one given by TimeSpan.TotalMilliseconds() but I need it in respect to UTC.

I saw some tactics like converting to a DateTime and then using DateTime.ToUniversalTime() but I haven't successfully gotten the total milliseconds from it after the conversion. I tried taking the new UTC DateTime and using DateTime.TimeOfDay() to put it back into a TimeSpan type and then use the TimeSpan.TotalMilliseconds() again but it did not work.

Any ideas?

答:
You can use this method</p>

```<code>public double MilliTimeStamp(DateTime TheDate)
        {
            DateTime d1 = new DateTime(1970, 1, 1);
            DateTime d2 = TheDate.ToUniversalTime();
            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
            return ts.TotalMilliseconds;
        }
</code>```

Title: TimeSpan to UTC milliseconds

Body:
You can use this method

public double MilliTimeStamp(DateTime TheDate)
        {
            DateTime d1 = new DateTime(1970, 1, 1);
            DateTime d2 = TheDate.ToUniversalTime();
            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
            return ts.TotalMilliseconds;
        }