问:
PHP - How to get all urls from many img's src?
Let's assume we have string like this:

```<code>Its really great to <img src="image2.png" /> hear from you "Today is good <img src="http://www.google.com/picture2.png" /> day" Let's listen song together! ---------<img src="images/profile.png" />\\\\\\
</code>```

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

```<code>output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';
</code>```

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

答:
Use preg_match_all():

```<code>$src = <<<EOL
Its really great to <img src="image2.png" /> hear from you "Today is good
<img src="http://www.google.com/picture2.png" /> day" Let's listen song
together! ---------<img src="images/profile.png" />\\\\\\
EOL;

preg_match_all('~src="([^"]+)~', $src, $matches);

var_export($matches[1]);
// output ->
//        array (
//          0 => 'image2.png',
//          1 => 'http://www.google.com/picture2.png',
//          2 => 'images/profile.png',
//        )
</code>```

Live demo

Update: you can use \K in the regex pattern to get just what is needed in $matches:

```<code>preg_match_all('~src="\K[^"]+~', $src, $matches);
var_export($matches);
// output ->
//      array (
//        0 =>
//        array (
//          0 => 'image2.png',
//          1 => 'http://www.google.com/picture2.png',
//          2 => 'images/profile.png',
//        ),
//      )
</code>```

For a reference see Escape sequences

Body:
Let's assume we have string like this:

Its really great to  hear from you "Today is good  day" Let's listen song together! ---------\\\\\\

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

Body:
Use preg_match_all():

$src = <<<EOL
Its really great to <img src="image2.png" /> hear from you "Today is good
<img src="http://www.google.com/picture2.png" /> day" Let's listen song
together! ---------<img src="images/profile.png" />\\\\\\
EOL;

preg_match_all('~src="([^"]+)~', $src, $matches);

var_export($matches[1]);
// output ->
//        array (
//          0 => 'image2.png',
//          1 => 'http://www.google.com/picture2.png',
//          2 => 'images/profile.png',
//        )

Live demo

Update: you can use \K in the regex pattern to get just what is needed in $matches:

preg_match_all('~src="\K[^"]+~', $src, $matches);
var_export($matches);
// output ->
//      array (
//        0 =>
//        array (
//          0 => 'image2.png',
//          1 => 'http://www.google.com/picture2.png',
//          2 => 'images/profile.png',
//        ),
//      )

For a reference see Escape sequences


来源: stackexchange

问:
Google OAuth 2 authorization - Error: redirect_uri_mismatch
On the website https://code.google.com/apis/console I have registered my application, set up generated Client ID: and Client Secret to my app and tried to log in with Google.
Unfortunately, I got the error message:

```<code>Error: redirect_uri_mismatch
The redirect URI in the request: http://127.0.0.1:3000/auth/google_oauth2/callback did not match a registered redirect URI

scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
response_type=code
redirect_uri=http://127.0.0.1:3000/auth/google_oauth2/callback
access_type=offline
approval_prompt=force
client_id=generated_id
</code>```

What does mean this message, and how can I fix it?
I use the gem omniauth-google-oauth2.

答:
If you use this tutorial: https://developers.google.com/identity/sign-in/web/server-side-flow then you should use "postmessage".

In GO this fixed the problem:

```<code>confg = &oauth2.Config{
        RedirectURL:  "postmessage",
        ClientID:   ...,
        ClientSecret: ...,
        Scopes:      ...,
        Endpoint:     google.Endpoint,
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On the website https://code.google.com/apis/console I have registered my application, set up generated Client ID: and Client Secret to my app and tried to log in with Google.
Unfortunately, I got the error message:

Error: redirect_uri_mismatch
The redirect URI in the request: http://127.0.0.1:3000/auth/google_oauth2/callback did not match a registered redirect URI

scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
response_type=code
redirect_uri=http://127.0.0.1:3000/auth/google_oauth2/callback
access_type=offline
approval_prompt=force
client_id=generated_id

What does mean this message, and how can I fix it?
I use the gem omniauth-google-oauth2.

Body:
If you use this tutorial: https://developers.google.com/identity/sign-in/web/server-side-flow then you should use "postmessage".

In GO this fixed the problem:

confg = &oauth2.Config{
        RedirectURL:  "postmessage",
        ClientID:   ...,
        ClientSecret: ...,
        Scopes:      ...,
        Endpoint:     google.Endpoint,
}


问:
Angular 1.6: Data not showing until scope function execute
Title might sound a bit strange but that's how it is.

Code:

```<code>angular.module('app')

.controller('TenantsCtrl', ['$scope', 'tenantsService','$window','loginService', function ($scope, tenantsService, $window, loginService) {
    $scope.mode = "list";
    $scope.g = [];
    $scope.editTenant = {
      firstName: "",
      lastName: "",
      room: "",
      to: "",
      from: ""
    }
    tenantsService.get().then((data) => {
        data.tenants.map((tenant) => {
          tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO')
          tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO')
        });
        console.log(typeof data.tenants);
        $scope.g = data.tenants;
        console.log($scope.g)
      }).catch((reason) => {
        loginService.doLogout();
        if(confirm(`${reason}. Please login`)) {
          $window.location.href="#!/login";
        }
      })
  $scope.showTenantForm = function(tenant) {
    console.log($scope.g)
  }

 }]);
</code>```

View:

```<code><div class="page-header">
    <h1>Cazati <button class="btn btn-xs btn-primary" ng-click="showTenantForm()">Cazeaza</button></h1>
</div>
<div class="row"  ng-cloak>
    {{g}}
    <table class="table table-hover">
        <thead>
            <tr>
                <th>Nume</th>
                <th>Camera</th>
                <th>Cazat din</th>
                <th>Cazat pana la</th>
                <th>Cazat de</th>
                <!--<th>Status</th>-->
                <th>Modifica</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="x in g">
                <td>{{x.lastName}} {{x.firstName}}</td>
                <td>{{x.room}}</td>
                <td>{{x.to}}</td>
                <td>{{x.from}}</td>
                <td></td>
                <td>
                    <button type="button" ng-click="editTenant(tenant.id)" class="btn btn-danger btn-xs">Modifica</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

Problem: data from table isn't shown. Strangely it gets shown only when press the button from header and the function gets called.

Data from service comes correctly.

Update: tenantsService

```<code>angular.module('app')
.service('graphQLService', ['baseUrl', 'loginService', function (baseUrl, loginService) {
  var graphQLService = {};
  graphQLService.sendQuery = function (query, vars) {
    var self = this;
    vars = vars || {};
    return new Promise(function(resolve, reject) {
      // use fetch to get the result
      fetch(baseUrl + '/gql', {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          query,
          vars,
          authToken: loginService.getToken()
        })
      })

      .then(function(response) {
        var status = response.status;
        if(status != 401) {
          return response.json().then((res) => {
            resolve(res.data);
          })
        } else {
          reject(response.statusText);
        }
        if(response.status == 401) {

        }
      })
      .catch(reject);
    });
  };
  return graphQLService;
}]);
</code>```

答:
I think the problem is that data.tenants.map returns you a new array. You don't save the reference to it.

Have you tried to do this

```<code>$scope.g = data.tenants.map((tenant) => {
      tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO');
      tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO');
      return tenant;
    });
    console.log(typeof data.tenants);
    console.log($scope.g)
</code>```

Body:
Title might sound a bit strange but that's how it is.

Code:

angular.module('app')

.controller('TenantsCtrl', ['$scope', 'tenantsService','$window','loginService', function ($scope, tenantsService, $window, loginService) {
    $scope.mode = "list";
    $scope.g = [];
    $scope.editTenant = {
      firstName: "",
      lastName: "",
      room: "",
      to: "",
      from: ""
    }
    tenantsService.get().then((data) => {
        data.tenants.map((tenant) => {
          tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO')
          tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO')
        });
        console.log(typeof data.tenants);
        $scope.g = data.tenants;
        console.log($scope.g)
      }).catch((reason) => {
        loginService.doLogout();
        if(confirm(`${reason}. Please login`)) {
          $window.location.href="#!/login";
        }
      })
  $scope.showTenantForm = function(tenant) {
    console.log($scope.g)
  }

 }]);

View:

Cazati <button class="btn btn-xs btn-primary" ng-click="showTenantForm()">Cazeaza</button>

    {{g}}

                Nume
                Camera
                Cazat din
                Cazat pana la
                Cazat de

                Modifica

                {{x.lastName}} {{x.firstName}}
                {{x.room}}
                {{x.to}}
                {{x.from}}

                    <button type="button" ng-click="editTenant(tenant.id)" class="btn btn-danger btn-xs">Modifica</button>

Problem: data from table isn't shown. Strangely it gets shown only when press the button from header and the function gets called.

Data from service comes correctly.

Update: tenantsService

angular.module('app')
.service('graphQLService', ['baseUrl', 'loginService', function (baseUrl, loginService) {
  var graphQLService = {};
  graphQLService.sendQuery = function (query, vars) {
    var self = this;
    vars = vars || {};
    return new Promise(function(resolve, reject) {
      // use fetch to get the result
      fetch(baseUrl + '/gql', {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          query,
          vars,
          authToken: loginService.getToken()
        })
      })

      .then(function(response) {
        var status = response.status;
        if(status != 401) {
          return response.json().then((res) => {
            resolve(res.data);
          })
        } else {
          reject(response.statusText);
        }
        if(response.status == 401) {

        }
      })
      .catch(reject);
    });
  };
  return graphQLService;
}]);

Body:
I think the problem is that data.tenants.map returns you a new array. You don't save the reference to it.

Have you tried to do this

$scope.g = data.tenants.map((tenant) => {
      tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO');
      tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO');
      return tenant;
    });
    console.log(typeof data.tenants);
    console.log($scope.g)


问:
unrecognized option : --print-module-descriptor
I am following the steps in Java 9 Jigsaw early access release quick start guide at http://openjdk.java.net/projects/jigsaw/quick-start

```<code>➜  tmp java --version
java 9-ea
Java(TM) SE Runtime Environment (build 9-ea+172)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+172, mixed mode)
</code>```

The jar command is picked up from the correct Java 9 directory.

```<code>➜  tmp which jar
/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/jar
</code>```

One of the steps in the quick start guide says to run the jar command with --print-module-descriptor option however when I try that I get the error message below.

```<code>➜  tmp jar --print-module-descriptor --file=mlib/org.astro@1.0.jar
unrecognized option : --print-module-descriptor
Try `jar --help' for more information.
</code>```

It looks like this option does not exist on the latest Early access build was it removed or moved to some other place? jar --help output below for reference

```<code>➜  tmp jar --help
Usage: jar [OPTION...] [ [--release VERSION] [-C dir] files] ...
jar creates an archive for classes and resources, and can manipulate or
restore individual classes or resources from an archive.

 Examples:
 # Create an archive called classes.jar with two class files:
 jar --create --file classes.jar Foo.class Bar.class
 # Create an archive using an existing manifest, with all the files in foo/:
 jar --create --file classes.jar --manifest mymanifest -C foo/ .
 # Create a modular jar archive, where the module descriptor is located in
 # classes/module-info.class:
 jar --create --file foo.jar --main-class com.foo.Main --module-version 1.0
     -C foo/ classes resources
 # Update an existing non-modular jar to a modular jar:
 jar --update --file foo.jar --main-class com.foo.Main --module-version 1.0
     -C foo/ module-info.class
 # Create a multi-release jar, placing some files in the META-INF/versions/9 directory:
 jar --create --file mr.jar -C foo classes --release 9 -C foo9 classes

To shorten or simplify the jar command, you can specify arguments in a separate
text file and pass it to the jar command with the at sign (@) as a prefix.

 Examples:
 # Read additional options and list of class files from the file classes.list
 jar --create --file my.jar @classes.list

 Main operation mode:

  -c, --create               Create the archive
  -i, --generate-index=FILE  Generate index information for the specified jar
                             archives
  -t, --list                 List the table of contents for the archive
  -u, --update               Update an existing jar archive
  -x, --extract              Extract named (or all) files from the archive
  -d, --describe-module      Print the module descriptor, or automatic module name

 Operation modifiers valid in any mode:

  -C DIR                     Change to the specified directory and include the
                             following file
  -f, --file=FILE            The archive file name. When omitted, either stdin or
                             stdout is used based on the operation
      --release VERSION      Places all following files in a versioned directory
                             of the jar (i.e. META-INF/versions/VERSION/)
  -v, --verbose              Generate verbose output on standard output

 Operation modifiers valid only in create and update mode:

  -e, --main-class=CLASSNAME The application entry point for stand-alone
                             applications bundled into a modular, or executable,
                             jar archive
  -m, --manifest=FILE        Include the manifest information from the given
                             manifest file
  -M, --no-manifest          Do not create a manifest file for the entries
      --module-version=VERSION    The module version, when creating a modular
                             jar, or updating a non-modular jar
      --hash-modules=PATTERN Compute and record the hashes of modules
                             matched by the given pattern and that depend upon
                             directly or indirectly on a modular jar being
                             created or a non-modular jar being updated
  -p, --module-path          Location of module dependence for generating
                             the hash

 Operation modifiers valid only in create, update, and generate-index mode:

  -0, --no-compress          Store only; use no ZIP compression

 Other options:

  -h, --help[:compat]        Give this, or optionally the compatibility, help
      --help-extra           Give help on extra options
      --version              Print program version

 An archive is a modular jar if a module descriptor, 'module-info.class', is
 located in the root of the given directories, or the root of the jar archive
 itself. The following operations are only valid when creating a modular jar,
 or updating an existing non-modular jar: '--module-version',
 '--hash-modules', and '--module-path'.

 Mandatory or optional arguments to long options are also mandatory or optional
 for any corresponding short options.
</code>```

答: Yes it seems the option was replaced with --describe-module (which is shown in the help output that you posted). This was done in JDK-8176772 which is resolved in build 162.

Body:
I am following the steps in Java 9 Jigsaw early access release quick start guide at http://openjdk.java.net/projects/jigsaw/quick-start

➜  tmp java --version
java 9-ea
Java(TM) SE Runtime Environment (build 9-ea+172)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+172, mixed mode)

The jar command is picked up from the correct Java 9 directory.

➜  tmp which jar
/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/jar

One of the steps in the quick start guide says to run the jar command with --print-module-descriptor option however when I try that I get the error message below.

➜  tmp jar --print-module-descriptor --file=mlib/org.astro@1.0.jar
unrecognized option : --print-module-descriptor
Try `jar --help' for more information.

It looks like this option does not exist on the latest Early access build was it removed or moved to some other place? jar --help output below for reference

➜  tmp jar --help
Usage: jar [OPTION...] [ [--release VERSION] [-C dir] files] ...
jar creates an archive for classes and resources, and can manipulate or
restore individual classes or resources from an archive.

 Examples:
 # Create an archive called classes.jar with two class files:
 jar --create --file classes.jar Foo.class Bar.class
 # Create an archive using an existing manifest, with all the files in foo/:
 jar --create --file classes.jar --manifest mymanifest -C foo/ .
 # Create a modular jar archive, where the module descriptor is located in
 # classes/module-info.class:
 jar --create --file foo.jar --main-class com.foo.Main --module-version 1.0
     -C foo/ classes resources
 # Update an existing non-modular jar to a modular jar:
 jar --update --file foo.jar --main-class com.foo.Main --module-version 1.0
     -C foo/ module-info.class
 # Create a multi-release jar, placing some files in the META-INF/versions/9 directory:
 jar --create --file mr.jar -C foo classes --release 9 -C foo9 classes

To shorten or simplify the jar command, you can specify arguments in a separate
text file and pass it to the jar command with the at sign (@) as a prefix.

 Examples:
 # Read additional options and list of class files from the file classes.list
 jar --create --file my.jar @classes.list

 Main operation mode:

  -c, --create               Create the archive
  -i, --generate-index=FILE  Generate index information for the specified jar
                             archives
  -t, --list                 List the table of contents for the archive
  -u, --update               Update an existing jar archive
  -x, --extract              Extract named (or all) files from the archive
  -d, --describe-module      Print the module descriptor, or automatic module name

 Operation modifiers valid in any mode:

  -C DIR                     Change to the specified directory and include the
                             following file
  -f, --file=FILE            The archive file name. When omitted, either stdin or
                             stdout is used based on the operation
      --release VERSION      Places all following files in a versioned directory
                             of the jar (i.e. META-INF/versions/VERSION/)
  -v, --verbose              Generate verbose output on standard output

 Operation modifiers valid only in create and update mode:

  -e, --main-class=CLASSNAME The application entry point for stand-alone
                             applications bundled into a modular, or executable,
                             jar archive
  -m, --manifest=FILE        Include the manifest information from the given
                             manifest file
  -M, --no-manifest          Do not create a manifest file for the entries
      --module-version=VERSION    The module version, when creating a modular
                             jar, or updating a non-modular jar
      --hash-modules=PATTERN Compute and record the hashes of modules
                             matched by the given pattern and that depend upon
                             directly or indirectly on a modular jar being
                             created or a non-modular jar being updated
  -p, --module-path          Location of module dependence for generating
                             the hash

 Operation modifiers valid only in create, update, and generate-index mode:

  -0, --no-compress          Store only; use no ZIP compression

 Other options:

  -h, --help[:compat]        Give this, or optionally the compatibility, help
      --help-extra           Give help on extra options
      --version              Print program version

 An archive is a modular jar if a module descriptor, 'module-info.class', is
 located in the root of the given directories, or the root of the jar archive
 itself. The following operations are only valid when creating a modular jar,
 or updating an existing non-modular jar: '--module-version',
 '--hash-modules', and '--module-path'.

 Mandatory or optional arguments to long options are also mandatory or optional
 for any corresponding short options.


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答:
After populating $data array (as instructed by Dan Grossman or beamrider9) you can use your custom callback function like:

```<code>function compare($a, $b)
{
    // Assuming you're sorting on bar field
    return strcmp($a['bar'], $b['bar']);
}
</code>```

But as many have commented, do it in database end (using ORDER BY) rather than in your PHP code.

Also if you use mysql_fetch_array($details_query, MYSQL_ASSOC), you'll get a better result. PHP has a fantastic function called print_r(). Use it extensively to debug your code.

ContentLicense: CC BY-SA 2.5

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

Body:
After populating $data array (as instructed by Dan Grossman or beamrider9) you can use your custom callback function like:

function compare($a, $b)
{
    // Assuming you're sorting on bar field
    return strcmp($a['bar'], $b['bar']);
}

But as many have commented, do it in database end (using ORDER BY) rather than in your PHP code.

Also if you use mysql_fetch_array($details_query, MYSQL_ASSOC), you'll get a better result. PHP has a fantastic function called print_r(). Use it extensively to debug your code.


问:
Reset notification timer by hitting button (swift3)
My code has two buttons:

One should start a "notification sequence" where a notification will appear every 30 seconds indefinitely.

The other should stop the notification sequence.

If you hit the start button while the notification sequence is in progress, the timer should reset -- so the next notification should appear 30s after the last time you hit the button. If you hit the button every 25s, you should never see a notification.

I have only included the code that is needed to solve this problem:

```<code> func startTimer(){

    let timeInterval = 30.0
    if isGrantedAccess && !timer.isValid { //allowed notification and timer off
        timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { (timer) in
            self.sendNotification()
        })}}
func stopTimer(){
    //shut down timer
    timer.invalidate()
    //clear out any pending and delivered notifications
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
    @IBAction func startButton(_ sender: UIButton) {

    startTimer()
}
@IBAction func stopButton(_ sender: UIButton) {
    stopTimer()
}
</code>```

答:
What you need is commonly referred to as debouncing, with a twist. Commonly used on type as you go searches, etc.

I would use a repeating timer and simply cancel it if the button is tapped before the 30 seconds is up, and start the thirty second repeating timer again every time it fires. I would also fire the local notifications immediately and invalidate the timers instead of invalidating the local notifications.

Here's a gist with an example in objective-c that you could refactor for use in swift.
Objective-C Debounce Example

Body:
My code has two buttons:

One should start a "notification sequence" where a notification will appear every 30 seconds indefinitely.

The other should stop the notification sequence.

If you hit the start button while the notification sequence is in progress, the timer should reset -- so the next notification should appear 30s after the last time you hit the button. If you hit the button every 25s, you should never see a notification.

I have only included the code that is needed to solve this problem:

 func startTimer(){

    let timeInterval = 30.0
    if isGrantedAccess && !timer.isValid { //allowed notification and timer off
        timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { (timer) in
            self.sendNotification()
        })}}
func stopTimer(){
    //shut down timer
    timer.invalidate()
    //clear out any pending and delivered notifications
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
    @IBAction func startButton(_ sender: UIButton) {

    startTimer()
}
@IBAction func stopButton(_ sender: UIButton) {
    stopTimer()
}


问:
Using driver.find_element_by_class_name("btn-success") Not working (Python)

Hello I have been trying to do this one thing for days what I can't do is use the class name I've got on this element when I do driver.find_element_by_class_name("btn-success") But... I get this in the console

```<code><https://pastebin.com/JDejrGaA>
</code>```

Btw The thing i am clicking is a copy button if that makes a diffrence

答:
There is no method named find_element_by_class in web driver. Please use the method find_element_by_class_name also this method takes only one class name at a time. You are passing three class name. Please use any one of the unique class name.
For eg. Here the class names are btn, btn-success and alt-credentials-copy.
Please try with following code

```<code>driver.find_element_by_class_name("btn-success")
</code>```

Body:
Hello I have been trying to do this one thing for days what I can't do is use the class name I've got on this element when I do driver.find_element_by_class_name("btn-success") But... I get this in the console

<https://pastebin.com/JDejrGaA>

Btw The thing i am clicking is a copy button if that makes a diffrence

Body:
There is no method named find_element_by_class in web driver. Please use the method find_element_by_class_name also this method takes only one class name at a time. You are passing three class name. Please use any one of the unique class name.
For eg. Here the class names are btn, btn-success and alt-credentials-copy.
Please try with following code

driver.find_element_by_class_name("btn-success")


问:
Consecutive 1 byte write to global memory results in multiple transactions
I'm doing a project where each thread writes 1-byte value to global memory, and I'm trying to minimize global memory write latency in my project.

In section 5.3.2. of CUDA C Programming guide(link) it says:

Global memory resides in device memory and device memory is accessed via 32-, 64-, or 128-byte memory transactions. These memory transactions must be naturally aligned: Only the 32-, 64-, or 128-byte segments of device memory that are aligned to their size (i.e., whose first address is a multiple of their size) can be read or written by memory transactions.

So I thought consecutive 1-byte write to global memory should be handled with one transaction, given that they are properly aligned.

But when I profile the following minimal example with Nsight in Visual Studio, although it takes 1 transaction(as expected) for 4 threads accessing consecutive 1-byte address, in the case of 5 threads, it takes 2 transactions.

```<code>__global__ void copyKernel(const unsigned char* a, unsigned char* b)
{
    int i = threadIdx.x;
    a[i] = b[i];
}

int main()
{
    char *d_a;
    char *d_b;

    // ... (stuffs like cudaMalloc)

    // to check that the address is aligned
    printf("%p\n", d_a); // aligned to 512-Byte
    printf("%p\n", d_b); // aligned to 512-Byte

    // copy 4 elements
    copyKernel<<<1, 4>>>(d_a, d_b);

    // copy 5 elements
    copyKernel<<<1, 5>>>(d_a, d_b);

    // ...
}
</code>```

The profiling results are as follows. (left - 4 threads / right - 5 threads)

What am I missing here? How should I write my code to make it perform writes in one transaction?

Environment: Windows 10, Visual Studio 2015, GeForce GTX 1080 (cc 6.1)

答:
It seems that I was looking at the results from wrong experiment. Nsight provides a number of experiments to "Profile CUDA Application", and the images posted in the question was from the result of "Memory Statistics - Global" experiment. From the User Guide for Nsight, the "Global" experiment reports following data:

The Transactions Per Request chart shows the average number of L1 transactions required per executed global memory instruction, separately for load and store operations.

So the number of write transactions shown in the "Global" experiment actually was to the L1 cache, not to L2. (Although in Nsight UI, it says it is to L2.)

On the other hand, "Memory Statistics - Caches" seems to show the number of L2 transactions, which contained data more relevant to what I was looking for. The numbers there were same as commented by Robert Crovella.

Test result for 1M threads:

Update

It seems that L2 transactions are in 32-byte granularity. Looking at profiling result for 4-byte consecutive store, the number of L2 store transactions reported for 1M threads is 131,072, which is equal to 1M(#threads) times 4(size of data) divided by 32.

So I came to a conclusion that the statement from the quote in my question saying "device memory can be accessed via 128-byte transaction" cannot be verified with Nsight, becuase it seems doesn't count transactions between L2 and device memory. (test code)

Body:
I'm doing a project where each thread writes 1-byte value to global memory, and I'm trying to minimize global memory write latency in my project.

In section 5.3.2. of CUDA C Programming guide(link) it says:

Global memory resides in device memory and device memory is accessed via 32-, 64-, or 128-byte memory transactions. These memory transactions must be naturally aligned: Only the 32-, 64-, or 128-byte segments of device memory that are aligned to their size (i.e., whose first address is a multiple of their size) can be read or written by memory transactions.

So I thought consecutive 1-byte write to global memory should be handled with one transaction, given that they are properly aligned.

But when I profile the following minimal example with Nsight in Visual Studio, although it takes 1 transaction(as expected) for 4 threads accessing consecutive 1-byte address, in the case of 5 threads, it takes 2 transactions.

__global__ void copyKernel(const unsigned char* a, unsigned char* b)
{
    int i = threadIdx.x;
    a[i] = b[i];
}

int main()
{
    char *d_a;
    char *d_b;

    // ... (stuffs like cudaMalloc)

    // to check that the address is aligned
    printf("%p\n", d_a); // aligned to 512-Byte
    printf("%p\n", d_b); // aligned to 512-Byte

    // copy 4 elements
    copyKernel<<<1, 4>>>(d_a, d_b);

    // copy 5 elements
    copyKernel<<<1, 5>>>(d_a, d_b);

    // ...
}

The profiling results are as follows. (left - 4 threads / right - 5 threads)

What am I missing here? How should I write my code to make it perform writes in one transaction?

Environment: Windows 10, Visual Studio 2015, GeForce GTX 1080 (cc 6.1)


问:
Slow Query when using class
This is my View (show.php) where i have the courses (each course has 2-4 lessons)

```<code><table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-mot">
    <?php
    if (count($corsi) > 0) {
        foreach ($corsi as $mm) {

            $lezioni=$mm->getLessons($mm->cou_id);
            echo "<tr class='odd gradeX'>";
            foreach ($lezioni as $lez) {
                $data=date('d-m-Y', (float)$lez->les_ts);
                $ora=date('H:i', (float)$lez->les_ts);
                echo "
                                                <td><span style=\"display: none;\">". $lez->les_ts."</span>
                                                    <a href='?controller=courses&action=manageMoto&id=" . $mm->cou_id . "'>" . $data . "
                                                    <div>".$ora."</div>
                                                </td>";
            }
        }
    }
    else {
        echo "<tr class='odd gradeX'><td>Nessun corso presente.</td><td></td><td><td></td><td></tr>";
    }
    ?>
</table>
</code>```

This is the controller (courses.controller):

```<code><?php
class CoursesController {

    public $tipo;
    public function show() {
        //I set the course type
        if (isset($_GET['type'])) {
            $this->tipo=$_GET['type'];
        }
        $lezioni=getNumberLessonsByCourseType($this->getTipo());
        $corsi = Course::getCoursesbyType($this->getTipo());
        require_once('views/courses/show.php');
    }
}
?>
</code>```

And the courses_model.php

```<code><?php
include_once("connection.php");
include_once("model.php");
include_once("lessons_model.php");

Class Course extends Model{
    public $cou_id;
    public $cou_type;
    public $cou_status;
    public $cou_fbid;

    public function __construct($cou_id=null, $cou_type=null, $cou_status=null, $cou_fbid=null)
    {
        $this->cou_id = $cou_id;
        $this->cou_type = $cou_type;
        $this->cou_status = $cou_status;
        $this->cou_fbid = $cou_fbid;
    }

    public static function getCoursesbyType($type) {
        $connection= new Database();
        $selectCou = $connection->prepare('SELECT * FROM courses WHERE cou_type = :type order by cou_id desc');
        $selectCou->bindParam(':type', $type, PDO::PARAM_INT);
        $selectCou->execute();

        $list = [];
        foreach($selectCou->fetchAll() as $corso) {
            $list[] = new Course($corso['cou_id'], $corso['cou_type'], $corso['cou_status'],$corso['cou_fbid']);
        }

        return $list;
        $connection=null;
    }

    public static function getLessons($id) {
        $connection= new Database();
        $id = intval($id);

        $selectLess = $connection->prepare('SELECT * FROM lessons WHERE les_course = :id');

        $selectLess->bindParam(':id', $id, PDO::PARAM_INT);
        $selectLess->execute();

        $list = [];
        foreach($selectLess->fetchAll() as $lezione) {
            $list[] = new Lesson($lezione['les_id'], $lezione['les_course'], $lezione['les_ts'],$lezione['les_number'],$lezione['les_instructor']);
        }
        return $list;
        $connection=null;
    }
}
</code>```

And I have also lessons_model.php (for each course I have an array of Lessons)

```<code>Class Lesson extends Model{

public $les_id;
public $les_course;
public $les_ts;
public $les_number;
public $les_instructor;

public function __construct($les_id=null, $les_course=null, $les_ts=null, $les_number=null, $les_instructor=null)
{
$this->les_id = $les_id;
$this->les_course = $les_course;
$this->les_ts = $les_ts;
$this->les_number = $les_number;
$this->les_instructor = $les_instructor;
}
}
</code>```

getNumberLessonsByCourseType is a simple function:

```<code>function getNumberLessonsByCourseType($course) {
    switch($course){
        case 'mot': $number=3; break;
        case 'mos': $number=3; break;
        case 'mop': $number=2; break;
        case 'sam': $number=2; break;
        case 'sen': $number=4; break;
    }

    return $number;

}
</code>```

The problem is that when I call the controller (method show) I need almost 10 seconds to have all the courses and for each of them his lessons. It is too slow.
The query in workbench is not slow, and the courses are 700, so not many.

答:
The problem is: You have 700 courses - And for each one you are running $lezioni=$mm->getLessons($mm->cou_id); where an SQL query is executed.
So if the query to get the lessons executes in 15 msec (which can be considered fast) 700 of those queries will take about 10 seconds.

What you can do is to fetch all lessons for all courses in one query and assign them to the courses in PHP.

```<code>Class Course extends Model{
    // ...

    public $lessons = [];

    // ...

    public static function getCoursesWithLessonsByType($type) {
        $connection = new Database();
        $selectCou = $connection->prepare('
            SELECT *
            FROM courses
            WHERE cou_type = :type
            order by cou_id desc
        ');
        $selectCou->bindParam(':type', $type, PDO::PARAM_INT);
        $selectCou->execute();

        $list = [];
        foreach($selectCou->fetchAll() as $corso) {
            $list[$corso['cou_id']] = new Course(
                $corso['cou_id'],
                $corso['cou_type'],
                $corso['cou_status'],
                $corso['cou_fbid']
            );
        }

        $selectLess = $connection->prepare('
            SELECT l.*
            FROM lessons l
            JOIN courses c ON c.cou_id = l.les_course
            WHERE c.cou_type = :type'
        );
        $selectLess->bindParam(':type', $type, PDO::PARAM_INT);;
        $selectLess->execute();

        foreach($selectLess->fetchAll() as $lezione) {
            $list[$lezione['les_course']]->lessons[] = new Lesson(
                $lezione['les_id'],
                $lezione['les_course'],
                $lezione['les_ts'],
                $lezione['les_number'],
                $lezione['les_instructor']
            );
        }

        return $list;
    }

    // ...
}
</code>```

In your controller:

```<code>$corsi = Course::getCoursesWithLessonsByType($this->getTipo());
</code>```

In your view:

```<code>$lezioni = $mm->lessons;
</code>```

Notes

You shouldn't open and close a connection every time you want to run a query. At least use a singleton like:

```<code>$connection = Database::getInstance();
</code>```

For best performance you should have the following indexes:

courses(cou_type, cou_id) or just courses(cou_type) which is the same if cou_id is the primary key

lessons(les_course[, ...]) - It can be a composite index, but must begin with les_course

Title: Slow Query when using class

Body:
This is my View (show.php) where i have the courses (each course has 2-4 lessons)

    <?php
    if (count($corsi) > 0) {
        foreach ($corsi as $mm) {

            $lezioni=$mm->getLessons($mm->cou_id);
            echo "
";
            foreach ($lezioni as $lez) {
                $data=date('d-m-Y', (float)$lez->les_ts);
                $ora=date('H:i', (float)$lez->les_ts);
                echo "
                                                ". $lez->les_ts."
                                                    cou_id . "'>" . $data . "

".$ora."

                                                	";
            }
        }
    }
    else {
        echo "
Nessun corso presente.
";
    }
    ?>

This is the controller (courses.controller):

<?php
class CoursesController {

    public $tipo;
    public function show() {
        //I set the course type
        if (isset($_GET['type'])) {
            $this->tipo=$_GET['type'];
        }
        $lezioni=getNumberLessonsByCourseType($this->getTipo());
        $corsi = Course::getCoursesbyType($this->getTipo());
        require_once('views/courses/show.php');
    }
}
?>

And the courses_model.php

<?php
include_once("connection.php");
include_once("model.php");
include_once("lessons_model.php");

Class Course extends Model{
    public $cou_id;
    public $cou_type;
    public $cou_status;
    public $cou_fbid;

    public function __construct($cou_id=null, $cou_type=null, $cou_status=null, $cou_fbid=null)
    {
        $this->cou_id = $cou_id;
        $this->cou_type = $cou_type;
        $this->cou_status = $cou_status;
        $this->cou_fbid = $cou_fbid;
    }

    public static function getCoursesbyType($type) {
        $connection= new Database();
        $selectCou = $connection->prepare('SELECT * FROM courses WHERE cou_type = :type order by cou_id desc');
        $selectCou->bindParam(':type', $type, PDO::PARAM_INT);
        $selectCou->execute();

        $list = [];
        foreach($selectCou->fetchAll() as $corso) {
            $list[] = new Course($corso['cou_id'], $corso['cou_type'], $corso['cou_status'],$corso['cou_fbid']);
        }

        return $list;
        $connection=null;
    }

    public static function getLessons($id) {
        $connection= new Database();
        $id = intval($id);

        $selectLess = $connection->prepare('SELECT * FROM lessons WHERE les_course = :id');

        $selectLess->bindParam(':id', $id, PDO::PARAM_INT);
        $selectLess->execute();

        $list = [];
        foreach($selectLess->fetchAll() as $lezione) {
            $list[] = new Lesson($lezione['les_id'], $lezione['les_course'], $lezione['les_ts'],$lezione['les_number'],$lezione['les_instructor']);
        }
        return $list;
        $connection=null;
    }
}

And I have also lessons_model.php (for each course I have an array of Lessons)

Class Lesson extends Model{

public $les_id;
public $les_course;
public $les_ts;
public $les_number;
public $les_instructor;

public function __construct($les_id=null, $les_course=null, $les_ts=null, $les_number=null, $les_instructor=null)
{
$this->les_id = $les_id;
$this->les_course = $les_course;
$this->les_ts = $les_ts;
$this->les_number = $les_number;
$this->les_instructor = $les_instructor;
}
}

getNumberLessonsByCourseType is a simple function:

function getNumberLessonsByCourseType($course) {
    switch($course){
        case 'mot': $number=3; break;
        case 'mos': $number=3; break;
        case 'mop': $number=2; break;
        case 'sam': $number=2; break;
        case 'sen': $number=4; break;
    }

    return $number;

}

The problem is that when I call the controller (method show) I need almost 10 seconds to have all the courses and for each of them his lessons. It is too slow.
The query in workbench is not slow, and the courses are 700, so not many.

Body:
The problem is: You have 700 courses - And for each one you are running $lezioni=$mm->getLessons($mm->cou_id); where an SQL query is executed.
So if the query to get the lessons executes in 15 msec (which can be considered fast) 700 of those queries will take about 10 seconds.

What you can do is to fetch all lessons for all courses in one query and assign them to the courses in PHP.

Class Course extends Model{
    // ...

    public $lessons = [];

    // ...

    public static function getCoursesWithLessonsByType($type) {
        $connection = new Database();
        $selectCou = $connection->prepare('
            SELECT *
            FROM courses
            WHERE cou_type = :type
            order by cou_id desc
        ');
        $selectCou->bindParam(':type', $type, PDO::PARAM_INT);
        $selectCou->execute();

        $list = [];
        foreach($selectCou->fetchAll() as $corso) {
            $list[$corso['cou_id']] = new Course(
                $corso['cou_id'],
                $corso['cou_type'],
                $corso['cou_status'],
                $corso['cou_fbid']
            );
        }

        $selectLess = $connection->prepare('
            SELECT l.*
            FROM lessons l
            JOIN courses c ON c.cou_id = l.les_course
            WHERE c.cou_type = :type'
        );
        $selectLess->bindParam(':type', $type, PDO::PARAM_INT);;
        $selectLess->execute();

        foreach($selectLess->fetchAll() as $lezione) {
            $list[$lezione['les_course']]->lessons[] = new Lesson(
                $lezione['les_id'],
                $lezione['les_course'],
                $lezione['les_ts'],
                $lezione['les_number'],
                $lezione['les_instructor']
            );
        }

        return $list;
    }

    // ...
}

In your controller:

$corsi = Course::getCoursesWithLessonsByType($this->getTipo());

In your view:

$lezioni = $mm->lessons;

Notes

You shouldn't open and close a connection every time you want to run a query. At least use a singleton like:

$connection = Database::getInstance();

For best performance you should have the following indexes:

courses(cou_type, cou_id) or just courses(cou_type) which is the same if cou_id is the primary key

lessons(les_course[, ...]) - It can be a composite index, but must begin with les_course


问:
Ksh, better way to ssh and run multiple commands
What is nice way to ssh and run multiple commands in korn shell ? I came across related question  and top answer works for me but I specify /bin/bash/ in this and running it over korn shell.

Is it ok to run below list of commands (copied from answer of referenced question) or there can be better way for ksh ?

```<code>ssh otherhost /bin/bash << EOF
  ls some_folder;
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF
</code>```

答:
It does not matter what shell you are using. I would rather stick with the solution provided in one of the answers, that recommended using connection multiplexing.

What is it? You will run separate ssh commands, but all of them will run in a single TCP connection.

And how to achieve that? Create a configuration file in ~/.ssh/config with similar content:

```<code>Host otherhost
  ControlPath ~/.ssh/controlmasters/%r@%h:%p
  ControlMaster auto
  ControlPersist yes
</code>```

And then run the commands as you would be running locally (with ssh server prefixed). The first will initiate the connection, the other will just use it

```<code>ssh otherhost ls some_folder;
ssh otherhost ./someaction.sh 'some params'
ssh otherhost pwd
ssh otherhost ./some_other_action 'other params'
</code>```

Body:
What is nice way to ssh and run multiple commands in korn shell ? I came across related question  and top answer works for me but I specify /bin/bash/ in this and running it over korn shell.

Is it ok to run below list of commands (copied from answer of referenced question) or there can be better way for ksh ?

ssh otherhost /bin/bash << EOF
  ls some_folder;
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

Body:
It does not matter what shell you are using. I would rather stick with the solution provided in one of the answers, that recommended using connection multiplexing.

What is it? You will run separate ssh commands, but all of them will run in a single TCP connection.

And how to achieve that? Create a configuration file in ~/.ssh/config with similar content:

Host otherhost
  ControlPath ~/.ssh/controlmasters/%r@%h:%p
  ControlMaster auto
  ControlPersist yes

And then run the commands as you would be running locally (with ssh server prefixed). The first will initiate the connection, the other will just use it

ssh otherhost ls some_folder;
ssh otherhost ./someaction.sh 'some params'
ssh otherhost pwd
ssh otherhost ./some_other_action 'other params'


问:
Extend 'Component'; Uncaught TypeError: Super expression must either be null or a function, not object
I am trying to extend React Component for that thing I dislike doing over and over again, the this.onInputChange = this.onInputChange.bind(this); requirement. So far I have tried:

MyComponent.js-

```<code>import React, { Component } from 'react';

// function bindReactMethod(this_value, method_name) {
//     // Bind all of your custom methods, like:
//     //   this.onInputChange = this.onInputChange.bind(this);
//     this_value[method_name] = this_value[method_name].bind(this_value)
// }

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.bindReactMethods = this.bindReactMethods.bind(this)
    }

    bindReactMethods(this_value, method_name) {
        // Bind all of your custom methods, like:
        //   this.onInputChange = this.onInputChange.bind(this);
        this_value[method_name] = this_value[method_name].bind(this_value)
    }
}
</code>```

SearchBar.js-

```<code>import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props);
        this.state = {term: ''};
        this.bindReactMethods(['onInputChange'])
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }
</code>```

fails with

```<code>Uncaught TypeError: Super expression must either be null or a function, not object
</code>```

and

MyComponent.js-

```<code>import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}
</code>```

SearchBar.js-

```<code>import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }
</code>```

also fails on

```<code>Uncaught TypeError: Super expression must either be null or a function, not object
</code>```

I would like to extend Component and always use my component, with this bindReactMethods callback being optional.

答:
MyComponent just wasn't being exported, the code works as:

```<code>import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
export default class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}
</code>```

and

```<code>import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }
</code>```

also it allows regular super, like

```<code>constructor(props) {
            super(props);
</code>```

Body:
I am trying to extend React Component for that thing I dislike doing over and over again, the this.onInputChange = this.onInputChange.bind(this); requirement. So far I have tried:

MyComponent.js-

import React, { Component } from 'react';

// function bindReactMethod(this_value, method_name) {
//     // Bind all of your custom methods, like:
//     //   this.onInputChange = this.onInputChange.bind(this);
//     this_value[method_name] = this_value[method_name].bind(this_value)
// }

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.bindReactMethods = this.bindReactMethods.bind(this)
    }

    bindReactMethods(this_value, method_name) {
        // Bind all of your custom methods, like:
        //   this.onInputChange = this.onInputChange.bind(this);
        this_value[method_name] = this_value[method_name].bind(this_value)
    }
}

SearchBar.js-

import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props);
        this.state = {term: ''};
        this.bindReactMethods(['onInputChange'])
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }

fails with

Uncaught TypeError: Super expression must either be null or a function, not object

and

MyComponent.js-

import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}

SearchBar.js-

import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }

also fails on

Uncaught TypeError: Super expression must either be null or a function, not object

I would like to extend Component and always use my component, with this bindReactMethods callback being optional.

Body:
MyComponent just wasn't being exported, the code works as:

import React, { Component } from 'react';

function bindReactMethod(this_value, method_name) {
    // Bind all of your custom methods, like:
    //   this.onInputChange = this.onInputChange.bind(this);
    this_value[method_name] = this_value[method_name].bind(this_value)
}

// https://stackoverflow.com/questions/15192722/javascript-extending-class
export default class MyComponent extends Component {

    constructor(props, custom_methods=[]) {
        super(props);
        try {
            custom_methods.map((method_name) => {
                bindReactMethod(this, method_name)
            });
        }
        catch (error) { } // ignore error because that means the user didnt have custom methods to bind
    }
}

and

import React from 'react';
import MyComponent from '../utils/MyComponent';

export default class SearchBar extends MyComponent {

    constructor(props) {
        super(props, ['onInputChange']);
        this.state = {term: ''};
    }

    onInputChange(event) {
        console.log(event.target.value);
        this.setState({term: event.target.value})
    }

also it allows regular super, like

constructor(props) {
            super(props);


问:
Select index from listview
I'm having some problem to get the index of the selected row in a listview. I wonder why this code isn't working? I get a red line below the SelectedIndex

```<code>    private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.SelectedIndex;
        string specialData = motelManager.GetInfoFromList(index);
        UppdateSpecialData(specialData);
    }
</code>```

Help is preciated. Thanks!

EDIT:

For some strange reason I get two messages when I click on one of the lines in the listView!? First I get the previous number and then the number for the last clicked line. What could be wrong?

```<code> private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.FocusedItem.Index;
        MessageBox.Show(Convert.ToString(index));
    }
</code>```

It's working now when I added a check like this:

```<code>if(lvRegAnimals.SelectedIndices.Count > 0)
</code>```

答:
There is another thread like this one, but here it goes again.

It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.

So the only safe way to find it is like this:

```<code>    private void lv1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv1.FocusedItem == null) return;
        int p = lv1.FocusedItem.Index;
</code>```

... now int p has the correct value...

Title: Select index from listview

Body:
I'm having some problem to get the index of the selected row in a listview. I wonder why this code isn't working? I get a red line below the SelectedIndex

    private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.SelectedIndex;
        string specialData = motelManager.GetInfoFromList(index);
        UppdateSpecialData(specialData);
    }

Help is preciated. Thanks!

EDIT:

For some strange reason I get two messages when I click on one of the lines in the listView!? First I get the previous number and then the number for the last clicked line. What could be wrong?

 private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.FocusedItem.Index;
        MessageBox.Show(Convert.ToString(index));
    }

It's working now when I added a check like this:

if(lvRegAnimals.SelectedIndices.Count > 0)

Body:
There is another thread like this one, but here it goes again.

It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.

So the only safe way to find it is like this:

    private void lv1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv1.FocusedItem == null) return;
        int p = lv1.FocusedItem.Index;

... now int p has the correct value...


问:
nullpointerexception while implementing priority queue with nodes
I am getting the error java.lang.NullPointerException while implementing priority queue with nodes. Does anyone have a solution without using built in priorityqueue class?

```<code>class node {                          //NODE CLASS

    public String ch;
    public int freq;
    node right_child, left_child;

    public node(String ch, int freq) {
        this.ch = ch;
        this.freq = freq;

    }

    public String get_char() {
        return ch;
    }

    public int get_freq() {
        return freq;
    }

}

//END NODE CLASS
class priority_queue {

    private final int size;
    private final node[] q_array;

    private int no_items = 0;

    public priority_queue(int max) {
        this.size = max;
        q_array = new node[size];
    }

    public void insert(node item) {
        int j;
        if (no_items == 0) {
            q_array[++no_items] = item;
            System.out.println("first item");
        } else {
            for (j = no_items - 1; j >= 0; j--) {
                if (item.get_freq()> q_array[j].get_freq()) {
                    q_array[j + 1] = q_array[j];

                } else {
                    break;
                }

            }
            q_array[j] = item;
            no_items++;
        }
    }

    public node remove() {
        return q_array[--no_items];

    }

    public void process() {
        node first, second;
        int new_freq;
        while (q_array.length > 1) {
            new_freq = 0;
            first = this.remove();
            //f1 = first.freq;
            second = this.remove();
            //f2=second.freq;

            new_freq = first.get_freq() + second.get_freq();
            node new_node = new node("*", new_freq);
            new_node.left_child = first;
            new_node.right_child = second;
            this.insert(new_node);

        }

    }
</code>```

答:
You don't add anything to q_array[0]. When no_items is 0 you're increasing it first and then insert the element with 1 position. That is how q_array[++no_items] works.
Hence you have NPE in q_array[j].get_freq() for the second insertion.

Body:
I am getting the error java.lang.NullPointerException while implementing priority queue with nodes. Does anyone have a solution without using built in priorityqueue class?

class node {                          //NODE CLASS

    public String ch;
    public int freq;
    node right_child, left_child;

    public node(String ch, int freq) {
        this.ch = ch;
        this.freq = freq;

    }

    public String get_char() {
        return ch;
    }

    public int get_freq() {
        return freq;
    }

}

//END NODE CLASS
class priority_queue {

    private final int size;
    private final node[] q_array;

    private int no_items = 0;

    public priority_queue(int max) {
        this.size = max;
        q_array = new node[size];
    }

    public void insert(node item) {
        int j;
        if (no_items == 0) {
            q_array[++no_items] = item;
            System.out.println("first item");
        } else {
            for (j = no_items - 1; j >= 0; j--) {
                if (item.get_freq()> q_array[j].get_freq()) {
                    q_array[j + 1] = q_array[j];

                } else {
                    break;
                }

            }
            q_array[j] = item;
            no_items++;
        }
    }

    public node remove() {
        return q_array[--no_items];

    }

    public void process() {
        node first, second;
        int new_freq;
        while (q_array.length > 1) {
            new_freq = 0;
            first = this.remove();
            //f1 = first.freq;
            second = this.remove();
            //f2=second.freq;

            new_freq = first.get_freq() + second.get_freq();
            node new_node = new node("*", new_freq);
            new_node.left_child = first;
            new_node.right_child = second;
            this.insert(new_node);

        }

    }


问:
Query the _id of a document in MongoDB
I wanted to find a document by using the object id. However, there is no result even though the object id was correct. This is my java code.

```<code>ObjectId id = (ObjectId)request.getParameter("id");
MongoCollection collection = db.getCollection("source");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id",id);
</code>```

I believe I need to change something at the    whereQuery.put().

答:
Instead of passing the String id, you need to pass the ObjectId, e.g.:

```<code>BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id",new ObjectId(id));
DBObject result = collection.findOne(query);
</code>```

Title: Query the _id of a document in MongoDB

Body:
I wanted to find a document by using the object id. However, there is no result even though the object id was correct. This is my java code.

ObjectId id = (ObjectId)request.getParameter("id");
MongoCollection collection = db.getCollection("source");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id",id);

I believe I need to change something at the    whereQuery.put().

Body:
Instead of passing the String id, you need to pass the ObjectId, e.g.:

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id",new ObjectId(id));
DBObject result = collection.findOne(query);


问:
CSS text-align does not work
I tried to use the text-align in CSS but it does not work.
here is the CSS and I also had all the body set to center, does that have to do with something?
Here is my CSS:

#Swell {
 text-align: left;
}```
</div>
</div>
</p>

<p>Here is my HTML:</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-html lang-html prettyprint-override"><code>Use Swell Bottles<img src="https://s-media-cache-ak0.pinimg.com/originals/f9/93/95/f99395b48463ee8d3bfa16f32df51c98.jpg" height="50"></code>```

Also my CSS body text-align:

body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}```

Dose the text-align: center have to do with the error and if that is true then how do I overwrite/fix this error

答:
An anchor element  is an inline element per default. Meaning it has no width or height on its own but rather is exactly as big as its content.

The text-align property does work in your example. It's just that the text is aligned regarding it's container. Which in this case is exactly as big as it's content. Therefore you would not see any difference.

Try to set the display property of the anchor element to block and see what happens.

a{
display:block;
text-align:right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a>Blocking beautiful</a></code>```

Edit: More in line with your example:

body{
text-align:center;
}

a{
display:block;
text-align:left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<a>Still beautiful</a>
<span>centered</span>
</body></code>```

Title: CSS text-align does not work

Body:
I tried to use the text-align in CSS but it does not work.
here is the CSS and I also had all the body set to center, does that have to do with something?
Here is my CSS:

#Swell {
 text-align: left;
}

Here is my HTML:

Use Swell Bottles

Also my CSS body text-align:

body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}

Dose the text-align: center have to do with the error and if that is true then how do I overwrite/fix this error

Body:
An anchor element <a> is an inline element per default. Meaning it has no width or height on its own but rather is exactly as big as its content.

The text-align property does work in your example. It's just that the text is aligned regarding it's container. Which in this case is exactly as big as it's content. Therefore you would not see any difference.

Try to set the display property of the anchor element to block and see what happens.

a{
display:block;
text-align:right;
}

<a>Blocking beautiful</a>

Edit: More in line with your example:

body{
text-align:center;
}

a{
display:block;
text-align:left;
}

<body>
<a>Still beautiful</a>
<span>centered</span>
</body>


问:
Best way to generate random file names in Python
In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I'm saving to a server, just to make sure it does not overwrite. Thank you!</p>

答:
If you need no the file path, but only the random string having predefined length you can use something like this.</p>

```<code>>>> import random
>>> import string

>>> file_name = ''.join(random.choice(string.ascii_lowercase) for i in range(16))
>>> file_name
'ytrvmyhkaxlfaugx'
</code>```

Body:
If you need no the file path, but only the random string having predefined length you can use something like this.

>>> import random
>>> import string

>>> file_name = ''.join(random.choice(string.ascii_lowercase) for i in range(16))
>>> file_name
'ytrvmyhkaxlfaugx'

ContentLicense: CC BY-SA 4.0


问:
Correlation between 2 different json file with jq
Is it possible with jq to find a correlation between 2 different json file? I have 2 files where both of the same ID key with different pieces of information.

File1

```<code>{
  "id": 3918389,
  "name": "Application",
  "servers": 5566625
}
</code>```

File2

```<code>{
  "ServerID": 5566625,
  "AccountID": 661737,
  "HostName": "example.com",

}
</code>```

I want a file where "ServerID" and "servers" is the same then merge all info like this:

Output

```<code>{
"id": 3918389,
"name": "Application",
"AccountID": 661737,
"HostName": "example.com",
}
</code>```

Any advice is appreciated.

Thanks!

答:
jq solution:

```<code>cat File[1-2] | jq -s 'if .[0].servers == .[1].ServerID then
              .[0] + .[1] | del(.servers,.ServerID)  else "not match" end'
</code>```

The output:

```<code>{
  "id": 3918389,
  "name": "Application",
  "AccountID": 661737,
  "HostName": "example.com"
}
</code>```

Details:

cat File[1-2] - concatenates and send to the standard output contents of File1 and File2 sequentially

-s (--slurp) - instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.

if-then-else - condition, performs merging of 2 objects .[0] + .[1] along with deleting the compared keys del(.servers,.ServerID) if crucial properties are equal .[0].servers == .[1].ServerID, otherwise - prints not match

Body:
Is it possible with jq to find a correlation between 2 different json file? I have 2 files where both of the same ID key with different pieces of information.

File1

{
  "id": 3918389,
  "name": "Application",
  "servers": 5566625
}

File2

{
  "ServerID": 5566625,
  "AccountID": 661737,
  "HostName": "example.com",

}

I want a file where "ServerID" and "servers" is the same then merge all info like this:

Output

{
"id": 3918389,
"name": "Application",
"AccountID": 661737,
"HostName": "example.com",
}

Any advice is appreciated.

Thanks!

Body:
jq solution:

cat File[1-2] | jq -s 'if .[0].servers == .[1].ServerID then
              .[0] + .[1] | del(.servers,.ServerID)  else "not match" end'

The output:

{
  "id": 3918389,
  "name": "Application",
  "AccountID": 661737,
  "HostName": "example.com"
}

Details:

cat File[1-2] - concatenates and send to the standard output contents of File1 and File2 sequentially

-s (--slurp) - instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.

if-then-else - condition, performs merging of 2 objects .[0] + .[1] along with deleting the compared keys del(.servers,.ServerID) if crucial properties are equal .[0].servers == .[1].ServerID, otherwise - prints not match


问:
impossible ton access to my phone Android studio
*

Windows 8| Android version 4.4.2  |trouble for connection

Hi,

i would like to run an app on my device but i can't acces to it by usb. I have tried to use adb directly in android studio with the command:

```<code>abd devices -l .
</code>```

Unfortunately, it show me an empty list of device.

 i 've also installed google usb driver but it make no differences.

Nevertheless, something disturb me:
 When i connect my phone to my computer , i can't find any notification about the connection of the phone, and i can't access to my device in the windows file manager too.

a)Does it mean that my device is not recognize by my computer?

b)What could be the missing step that i should perform to get access to my device?
does somebody have a solution ?

答:
Follow these steps to enable communication between your phone and Android Studio.

Open Settings -> About on your Android phone or tablet.

If you have a Samsung Galaxy S4, Note 8.0, Tab 3  or any other Galaxy device with Android 4.2, open Settings> More tab> About and tap it.

If you have Galaxy Note 3 or any Galaxy device with Android 4.3, go to Galaxy Note 3 from Settings> General> About and tap the Build version 7 times.
Now scroll to Build number and tap it 7  times.

After tapping the Build Number 7 times, you will see a message “You are now a developer!” If you have a Galaxy S4 or any other Samsung Galaxy device with Android 4.2, the message reads as follows- “Developer mode has been enabled”.

Return to the main Settings menu and now you’ll be able to see Developer Options.

Tap on Developer options and mark the box in front of  USB Debugging  to enable it.

To disable USB Debugging mode later, you can uncheck the box before the option
To enable Developer Options, go to Settings> Developer options and tap on the ON/OFF slider on the top of the page.

Body:
*

Windows 8| Android version 4.4.2  |trouble for connection

Hi,

i would like to run an app on my device but i can't acces to it by usb. I have tried to use adb directly in android studio with the command:

abd devices -l .

Unfortunately, it show me an empty list of device.

 i 've also installed google usb driver but it make no differences.

Nevertheless, something disturb me:
 When i connect my phone to my computer , i can't find any notification about the connection of the phone, and i can't access to my device in the windows file manager too.

a)Does it mean that my device is not recognize by my computer?

b)What could be the missing step that i should perform to get access to my device?
does somebody have a solution ?


问:
Sinatra force logged in on controller
I have a helper defined in helpers/loggedin.rb that has a function called logged_in? which checks if a user is logged in or not. is there any way I can call this at the top of a controller to force all views in that controller to redirect if the condition is not met or do I have to add the check to the dozens of views

controller currently looks something like this:

```<code>class ServiceController < ApplicationController
  ...
  get '/service/:id' do
  ...
end
</code>```

答:
I found a way to do this if anyone else gets stuck.

```<code>before do
     redirect('/login') unless logged_in?
end
</code>```

Please note that this will redirect all urls not just the ones explicitly defined in the controller

Title: Sinatra force logged in on controller

Body:
I have a helper defined in helpers/loggedin.rb that has a function called logged_in? which checks if a user is logged in or not. is there any way I can call this at the top of a controller to force all views in that controller to redirect if the condition is not met or do I have to add the check to the dozens of views

controller currently looks something like this:

class ServiceController < ApplicationController
  ...
  get '/service/:id' do
  ...
end

Body:
I found a way to do this if anyone else gets stuck.

before do
     redirect('/login') unless logged_in?
end

Please note that this will redirect all urls not just the ones explicitly defined in the controller


问:
write code join same table in laravel
I have 2 tables

```<code>Table 1: farm has columns id, name, id_tech, id_manager
Table 2: User has columns: id, name
</code>```

And I run the following statement in mysql:

```<code> SELECT eco_farm.id, eco_farm.name as farmname, A.name as manager,
       B.name as tech
 FROM eco_farm
 LEFT JOIN eco_user A ON A.id = eco_farm.id_manager
 LEFT JOIN eco_user B ON B.id = eco_farm.id_tech
</code>```

and the result is

But I do not know how to write code in laravel how to retrieve data in laravel. May you help me. thank you

答:
This is using the query builder.

```<code>$result = \DB::table('eco_farm')
    ->leftJoin('eco_user as A', 'A.id', '=', 'eco_farm.id_manager')
    ->leftJoin('eco_user as B', 'B.id', '=', 'eco_farm.id_tech')
    ->selectRaw('eco_farm.id, eco_farm.name as farmname, A.name as manager, B.name as tech')
    ->get();
</code>```

Check the documentation for more information and examples https://laravel.com/docs/5.4/queries

Title: write code join same table in laravel

Body:
I have 2 tables

Table 1: farm has columns id, name, id_tech, id_manager
Table 2: User has columns: id, name

And I run the following statement in mysql:

 SELECT eco_farm.id, eco_farm.name as farmname, A.name as manager,
       B.name as tech
 FROM eco_farm
 LEFT JOIN eco_user A ON A.id = eco_farm.id_manager
 LEFT JOIN eco_user B ON B.id = eco_farm.id_tech

and the result is

But I do not know how to write code in laravel how to retrieve data in laravel. May you help me. thank you

Body:
This is using the query builder.

$result = \DB::table('eco_farm')
    ->leftJoin('eco_user as A', 'A.id', '=', 'eco_farm.id_manager')
    ->leftJoin('eco_user as B', 'B.id', '=', 'eco_farm.id_tech')
    ->selectRaw('eco_farm.id, eco_farm.name as farmname, A.name as manager, B.name as tech')
    ->get();

Check the documentation for more information and examples https://laravel.com/docs/5.4/queries


问:
Instantiating new redis-server (Linux)
I'm instantiating a new redis-server in my set up (it runs just one currently). One of the steps is to make a copy of redis-server in /etc/init.d/ and configure it for the new instance.

Specifically, I'm changing values for DAEMON_ARGS, NAME, DESC and PIDFILE within the script. Here's the code:

```<code>PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/redis-server
DAEMON_ARGS=/etc/redis/redis-2.conf
NAME=redis2-server
DESC=redis2-server

RUNDIR=/var/run/redis
PIDFILE=$RUNDIR/redis2-server.pid
</code>```

My question is: do I need to also change the value of DAEMON and RUNDIR? Currently they're set to /usr/bin/redis-serverand /var/run/redis respectively. What's the correct way to configure this?

答:
The DAEMON variable is the executable to run, so that should not change.
The RUNDIR is the directory where your executable is run, I would recommend changing this to different directory from your first Redis instance.

Title: Instantiating new redis-server (Linux)

Body:
I'm instantiating a new redis-server in my set up (it runs just one currently). One of the steps is to make a copy of redis-server in /etc/init.d/ and configure it for the new instance.

Specifically, I'm changing values for DAEMON_ARGS, NAME, DESC and PIDFILE within the script. Here's the code:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/redis-server
DAEMON_ARGS=/etc/redis/redis-2.conf
NAME=redis2-server
DESC=redis2-server

RUNDIR=/var/run/redis
PIDFILE=$RUNDIR/redis2-server.pid

My question is: do I need to also change the value of DAEMON and RUNDIR? Currently they're set to /usr/bin/redis-serverand /var/run/redis respectively. What's the correct way to configure this?


问:
Inconsistency with Large Number Subtraction
I'm relatively new to C++, and I'm attempting to create a set of arithmetic functions that are able to handle large numbers, using a struct called biggie that handles the numbers like a string. I'm currently having difficulty with the subtract function.

When I run try subtracting with small numbers, it works perfectly fine. When I attempt to scale up, it works fine the first time I call the function.

The second time I call it with large numbers, in another function that will later find the GCD of two large numbers, the answer changes with different runtimes, just slightly. Sometimes, it is the exactly same output as the first. Other times, it is wrong in only 3 digits, and the rest is fine.

This is my code from the subtract function:

```<code>biggie subtract (biggie a, biggie subtractor) {
    biggie difference;
    string aCopy = a.value;

    int digitDifference = 0;

    for (int i = aCopy.length(); i >= 0; i--) {
        digitDifference = strToInt(aCopy[i]) - strToInt (subtractor.value[i]);

        if (digitDifference < 0) {
            aCopy[i - 1] -= 1;
            digitDifference += 10;
        }

        difference.value += intToStr(digitDifference);
    }

    return difference;
}
</code>```

And this is the code in my int main():

```<code>biggie a;
a.value = "29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852";

biggie b;
b.value = "293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852";

cout << "a: " << a.value << endl;
cout << "b: " << b.value << endl;
cout << "diff: " << (subtract(a, b)).value << endl;

biggie gcf = gcd(a, b);
</code>```

Here is my gcd function:

```<code>biggie gcd (biggie a, biggie b) {
    cout << endl;
    cout << "a: " << a.value << endl;
    cout << "b: " << b.value << endl;
    cout << "diff: " << (subtract(a, b)).value;
    return (subtract(a, b));
}
</code>```

Here was the output I got once, when I run the program (everything is perfect except digits 162 to 164, which are different).

```<code>a: 29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
b: 293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
diff: 191013225540743444660078221856942595327491518824156154841295494507920769420781195934078007415265514746382795296725955236558257111156901806817869021100000300281988654648450355571495534474845762360522388515575714067347551318851969118525074113760326683276593397094179939610669980991987011160199799330883848833298072487612158549561427422487741178249739429387671688555714646431881066874165038582214771077947621912806007974406604465925076449662429801117865470000000000000000000000000000000000000000000000000000000000000

a: 29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
b: 293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
diff: 191013225540743444660078221856942595327491518824156154841295494507920769420781195934078007415265514746382795296725955236558257111156901806817869021100000300281985724648450355571495534474845762360522388515575714067347551318851969118525074113760326683276593397094179939610669980991987011160199799330883848833298072487612158549561427422487741178249739429387671688555714646431881066874165038582214771077947621912806007974406604465925076449662429801117865470000000000000000000000000000000000000000000000000000000000000
Process returned 0 (0x0)   execution time : 0.085 s
Press ENTER to continue.
</code>```

I'm also using OSX Yosemite and running the program on CodeBlocks, if that changes anything.

EDIT: To clarify, biggie is a struct that handles big numbers. biggie.value would be a string that contains a large number. The strToInt() and intToStr() are functions that do exactly as the name implies using the <sstream>library. Hope this helps.

答:
Since this is a school project, I'll provide some clues and no direct answers.

You don't show the operator[] for biggie.  This could be a problem; consider what happens when a is longer than subtractor.

Try this test case:  284 - 86.

Is left-to-right the best way to go about doing a subtraction?

Body:
I'm relatively new to C++, and I'm attempting to create a set of arithmetic functions that are able to handle large numbers, using a struct called biggie that handles the numbers like a string. I'm currently having difficulty with the subtract function.

When I run try subtracting with small numbers, it works perfectly fine. When I attempt to scale up, it works fine the first time I call the function.

The second time I call it with large numbers, in another function that will later find the GCD of two large numbers, the answer changes with different runtimes, just slightly. Sometimes, it is the exactly same output as the first. Other times, it is wrong in only 3 digits, and the rest is fine.

This is my code from the subtract function:

biggie subtract (biggie a, biggie subtractor) {
    biggie difference;
    string aCopy = a.value;

    int digitDifference = 0;

    for (int i = aCopy.length(); i >= 0; i--) {
        digitDifference = strToInt(aCopy[i]) - strToInt (subtractor.value[i]);

        if (digitDifference < 0) {
            aCopy[i - 1] -= 1;
            digitDifference += 10;
        }

        difference.value += intToStr(digitDifference);
    }

    return difference;
}

And this is the code in my int main():

biggie a;
a.value = "29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852";

biggie b;
b.value = "293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852";

cout << "a: " << a.value << endl;
cout << "b: " << b.value << endl;
cout << "diff: " << (subtract(a, b)).value << endl;

biggie gcf = gcd(a, b);

Here is my gcd function:

biggie gcd (biggie a, biggie b) {
    cout << endl;
    cout << "a: " << a.value << endl;
    cout << "b: " << b.value << endl;
    cout << "diff: " << (subtract(a, b)).value;
    return (subtract(a, b));
}

Here was the output I got once, when I run the program (everything is perfect except digits 162 to 164, which are different).

a: 29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
b: 293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
diff: 191013225540743444660078221856942595327491518824156154841295494507920769420781195934078007415265514746382795296725955236558257111156901806817869021100000300281988654648450355571495534474845762360522388515575714067347551318851969118525074113760326683276593397094179939610669980991987011160199799330883848833298072487612158549561427422487741178249739429387671688555714646431881066874165038582214771077947621912806007974406604465925076449662429801117865470000000000000000000000000000000000000000000000000000000000000

a: 29345983548974568765879456985698642934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852598678954398652934598329345983548974568765879456985679864986789543986579865489756897345980650953489754687453987456984569085254897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852798654897568973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
b: 293459835489745687658794569856986429345983548974568765879456911111153489754687453987456984569085254897456876222225698567986459867895439865798654897568973459806509534897546874539874569845690852798651111168973459806509534975468745398745698456908522934598354897456876587945698567986459867895439865798654897568973459806509534897546874539874569845690852
diff: 191013225540743444660078221856942595327491518824156154841295494507920769420781195934078007415265514746382795296725955236558257111156901806817869021100000300281985724648450355571495534474845762360522388515575714067347551318851969118525074113760326683276593397094179939610669980991987011160199799330883848833298072487612158549561427422487741178249739429387671688555714646431881066874165038582214771077947621912806007974406604465925076449662429801117865470000000000000000000000000000000000000000000000000000000000000
Process returned 0 (0x0)   execution time : 0.085 s
Press ENTER to continue.

I'm also using OSX Yosemite and running the program on CodeBlocks, if that changes anything.

EDIT: To clarify, biggie is a struct that handles big numbers. biggie.value would be a string that contains a large number. The strToInt() and intToStr() are functions that do exactly as the name implies using the <sstream>library. Hope this helps.


问:
How to implement an API key on PHP software?
I am distributing a PHP created plugin like a Wordpress plugin but I want to implement an API key for it and users would need to enter an API key to unlock it for it to work.

How can that be done?  And yes I already know it could be easily bypassed since PHP is not compiled but atleast it will deter some people with no PHP knowledge.

Thanks..

答:
Its absolutely pointless. As its php you have to send the source code and any user can just remove the license check code and run it.

Besides people don't like messing with license keys unless you software is really, really useful, desirable or essential they will either find a license key free alternative or just not bother with it.


问:
Will YouTube re-encode a file when uploading, which has the recommended video format (H.264)?
Will YouTube re-encode a video file, which will be uploaded with H.264 encoding? I'm currently working on a video steganography project. Will it be possible to upload to YouTube without any video re-encoding?</p>

答:
YouTube always re-encodes your video, but if you're trying to decrease how bad YT's compression makes a video look, there is one option.

Upscale. From a percentage standpoint, YT allots much more bitrates to 1440p or higher resolution videos. I'm not just talking about "well the video has more pixels, so it requires more bitrates". YT increases the allotted bitrate amount far beyond that requirement, and the result is that a 1080p or lower vid upscaled to 1440p or 4k has far less visible compression when compared frame by frame to just uploading a low res video at its native resolution.

Night and day difference, but the viewer must watch the vid with the player set to 1440p or higher, even if their monitor doesn't support high resolutions. They'll still see the drastic difference.

Drawbacks, small text won't be "crisp", but a great option for video that's otherwise ruined by what low bitrates on YT does. Fast paced video games, for example, greatly benefit from upscaling to trick YT into a better compression ratio.

The compression ratio goes up, as the uploaded resolution increases. 1080p has less artifacts than 720p, 1440p is drastically better than 1080p, and 4k video has almost no visible compression.

source: I recorded fast-paced video that demands high bitrates for clear quality, and uploaded it at 1080p, and then 2k, and 4k. Uploaded all 3 versions at 80,000bitrate, found the exact same frame in each video after upload, and compared the 3 uploaded frames to the 3 rendered frames before upload.


问:
How to check the defined error class of a connection?
How to check the defined error class of a connection (DSI) of Sybase Replication Server?

I use alter connection to change the error class associated to the DSI but I want a command that list its information in order to confirm that the error class was correctly associated.

How can I do that?

答:
Not sure where rs_getconn and ral_connection_details came from (3rd party app? custom proc? one of a slew of fly-by-night SRS management tools Sybase provided over the years?), but the simplest (and guaranteed to be in any RSSD going back eons - unless someone dropped it) is the rs_helpdb stored proc.

rs_helpdb generates a result set showing dsname, dbname, did, prs, error and function classes; for RS 15.7+ you'll also get connid (associated with multipath rep / alternate connections) and the repserver error class.


问:
How are algorithms hidden in Android APKs
I came across this question on Stack Overflow:
How to avoid reverse engineering of an APK file?

But, if what they say there is true, and you can't completely protect the code, I am then still remained with a question:

What do you do when you have an algorithm you want to keep secret? I really find it hard to believe big apps such as Facebook, Gmail, etc. only obfuscate their code. Don't they somehow connect the Android Java code to a remote server where it runs all the background stuff?

For example: can you make a button in Android connect to a remote server which will do some PHP scripts on the server, and then return data to the app, just as you would do in web development? Or there is another way?

(*Currently trying to learn Android development, so maybe it has answer in further videos I am watching, but I am really curious now)

答:
You don't.  If you wanted to, you could reverse engineer Google, Facebook, or any other app (although for Google especially a lot of the interesting algorithms are on the serverside, not the client).

This is no different from any other application ever written.  I've disassembled DOS programs and figured out how they worked to interact with hardware they controlled.  If the code exists on the client, it can be reverse engineered.  If a processor needs to be able to run it, then a human can read it.

Your best bet is just not to worry about it.  Your code isn't that special, or that different from every other app out there that it needs to be protected.  What's valuable about it is the time spent writing it, promoting it, building a business around it.  The code itself is dead simple in 99.999% of cases.  If you truly have something unique you can consider a patent, but the value of the code is in the time taken to get it right, not in its secrecy.