问:
Select and append rows with null value (SQL/VBA)
Can someone help in coding a Access SQL statement/Query where I have a table with columns as shown with Ident No not primary

```<code>Ident_No-----Data1-----Data2-----Data3-----Data4-----Data5-----Data6

1----------------abc--------def---------null---------null--------null--------null

1----------------null--------null---------ghi----------jkl----------null--------null

1----------------null--------null---------null---------null--------mno--------pqr
</code>```

Looking for result as shown below in the query result or a new table.

```<code>Ident_No-----Data1-----Data2-----Data3-----Data4-----Data5-----Data6

1----------------abc--------def---------ghi---------jkl--------mno--------pqr
</code>```

Please Help Thanks in advance

答:
You need to use group by and get the MAX() value for each column like

```<code>select `Ident_No`, max(`Data1`), max(`Data2`),
        max(`Data3`), max(`Data4`), max(`Data5`), max(`Data6`)
from tbl9999
group by Ident_No
</code>```

See live here http://rextester.com/CIHY78216

Body:
Can someone help in coding a Access SQL statement/Query where I have a table with columns as shown with Ident No not primary

Ident_No-----Data1-----Data2-----Data3-----Data4-----Data5-----Data6

1----------------abc--------def---------null---------null--------null--------null

1----------------null--------null---------ghi----------jkl----------null--------null

1----------------null--------null---------null---------null--------mno--------pqr

Looking for result as shown below in the query result or a new table.

Ident_No-----Data1-----Data2-----Data3-----Data4-----Data5-----Data6

1----------------abc--------def---------ghi---------jkl--------mno--------pqr

Please Help Thanks in advance

Body:
You need to use group by and get the MAX() value for each column like

select `Ident_No`, max(`Data1`), max(`Data2`),
        max(`Data3`), max(`Data4`), max(`Data5`), max(`Data6`)
from tbl9999
group by Ident_No

See live here http://rextester.com/CIHY78216


来源: stackexchange

问:
Change Enter from submission to Tab?
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

```<code>e.returnValue = false;
e.cancel = true;
</code>```

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

答:
Based on this post:
http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order

I came up with this.  I eventually chose not to use focasables though, and instead use input to get the effect I wanted.  The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.

```<code>$(document).ready(function() {
var focusables = $(":input").not('[type="image"]').not('[type="submit"]');

  focusables.keydown(function(e) {
    if (e.keyCode == 13) {
      e.preventDefault();
      var current = focusables.index(this),
              next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
      next.focus();
    }
  });
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Change Enter from submission to Tab?

Body:
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

e.returnValue = false;
e.cancel = true;

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

Body:
Based on this post:
http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order

I came up with this.  I eventually chose not to use focasables though, and instead use input to get the effect I wanted.  The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.

$(document).ready(function() {
var focusables = $(":input").not('[type="image"]').not('[type="submit"]');

  focusables.keydown(function(e) {
    if (e.keyCode == 13) {
      e.preventDefault();
      var current = focusables.index(this),
              next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
      next.focus();
    }
  });
});


问:
maps in power BI: how bing resolve city names, world cities database?
I am running into an issue with Maps from Power BI.

I have a list of city name around the world in a different language than English.

Excel containing distinct city name in Italian

Using the visualizations Maps I get no feedback (i.e. map remain empty), so I started to translate the name into English, add country, state and continent. Nothing. The map remain still empty. I even change the data type of each column. NO-THING.
Finally I insert the Latitude and Longitude and then the visualization shows me what I want.

Full geographics description database

1) Does anyone knows how bings works? I though it will to the best guess, but nothing happens till I insert the lat and long.

2) Does anyone knows about a database with the lat and Long of cities around the world?

答:
I found this database of latitude and longitude of major cities around the world.
It's a 40MB compressed txt file.

https://www.maxmind.com/fr/free-world-cities-database

Uncompressed file is about 140 MB of data, quite big for a power BI file.
I tried to load the entire file, and the pbix come out with 120MB.

ContentLicense: CC BY-SA 3.0


问:
Open Inbox of Email Client (Gmail, Outlook,etc) from android app
I have made an android application which uses firebase authentication. I am sending a verification email and want to show a button on my app that can launch a email client where the user can access there email to click on the verification link. How to achieve this?</p>

答:
Try this</p>

```<code>Intent intent=Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_EMAIL);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Min SDK 15
            startActivity(intent);
</code>```

Body:
Try this

Intent intent=Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_EMAIL);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Min SDK 15
            startActivity(intent);


问:
Obtaining matches for faces\ts with only a count of 1 in SOLR
I am writing a testng test that does a SOLR query and gives a facet field (in this case it is taxid).  I can get the facet results for entries with each taxid that looks similar to this:

```<code>    "123456780",
    104059,
    "123456781",
    76777,
    "123456782",
    72797,
    ...
</code>```

the values in quotes are the IDs and the other numbers are the count.  What I want to do is find the ones with a count of 1.  If I could have it return the facet value in ascending order that would be good.  Specifying in the query to return only facets with count of 1 would be better.

I could feasibly read them all into a Java array and sort or find which have a value of 1 (as a count) but there are "numFound": 11952086.  Eleven million is too many to parse.  Is there a way to return the count ascending or just return values which have a count of 1?

答:
I am fairly sure that there is no way to return facet result satisfying condition on count.

But following may help you.

Facet result can be sorted using facet.sort=count parameter. It will sort facet result in descending order of count.

```<code>curl -XGET 'http://172.26.98.10:8886/solr/SF_CaseComments/select?q=lock&rows=0&facet=true&facet.field=CreatedById&facet.sort=count&facet.limit=-1&facet.mincount=1&wt=json'
</code>```

You may ignore result till you find 1 and process there onwards.

Body:
I am writing a testng test that does a SOLR query and gives a facet field (in this case it is taxid).  I can get the facet results for entries with each taxid that looks similar to this:

    "123456780",
    104059,
    "123456781",
    76777,
    "123456782",
    72797,
    ...

the values in quotes are the IDs and the other numbers are the count.  What I want to do is find the ones with a count of 1.  If I could have it return the facet value in ascending order that would be good.  Specifying in the query to return only facets with count of 1 would be better.

I could feasibly read them all into a Java array and sort or find which have a value of 1 (as a count) but there are "numFound": 11952086.  Eleven million is too many to parse.  Is there a way to return the count ascending or just return values which have a count of 1?

Body:
I am fairly sure that there is no way to return facet result satisfying condition on count.

But following may help you.

Facet result can be sorted using facet.sort=count parameter. It will sort facet result in descending order of count.

curl -XGET 'http://172.26.98.10:8886/solr/SF_CaseComments/select?q=lock&rows=0&facet=true&facet.field=CreatedById&facet.sort=count&facet.limit=-1&facet.mincount=1&wt=json'

You may ignore result till you find 1 and process there onwards.


问:
Why would apache refuse connection to localhost 127.0.0.1 on OSX?
When trying to access sites on my localhost the connection is refused. Two days ago the set up was working without issues with multiple virtual hosts configured. I'm not aware of any changes that could have affected the set up. I spent all day yesterday trying to troubleshoot the issue but have been going around in circles.

OS: OSX 10.11.16

httpd -V returns this:

```<code>Server version: Apache/2.4.18 (Unix)
Server built:   Feb 20 2016 20:03:19
Server's Module Magic Number: 20120211:52
Server loaded:  APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture:   64-bit
Server MPM:     prefork
   threaded:     no
   forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_FLOCK_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/usr"
 -D SUEXEC_BIN="/usr/bin/suexec"
 -D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"
</code>```

httpd.conf is configured to allow virtual hosts and nothing has changed in httpd-vhosts.conf file.

```<code>LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
...
# Virtual hosts
Include /private/etc/apache2/extra/httpd-vhosts.conf
</code>```

apachectl configtest returns:

```<code>Syntax OK
</code>```

I've tried running a port scan for 127.0.0.1 and http port 80 does not show. This and the connection being refused makes me think this is where the issue is but I don't know why. The OSX firewall is turned off. I've tried the solution posted here but it did not fix it.

My /etc/hosts file looks like this:

```<code>#
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
#

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
127.0.0.1       site.local
127.0.0.1       othersite.local
...
</code>```

I can ping 127.0.0.1. I previously had homebrew installed to run different PHP versions but I've removed that to try and bring the system back to stock. I really don't know what to try next, any help would be really appreciated.

答: You could check to ensure you have Listen: 80 in your /usr/local/etc/apache2/2.4/httpd.conf configuration file.

Body:
When trying to access sites on my localhost the connection is refused. Two days ago the set up was working without issues with multiple virtual hosts configured. I'm not aware of any changes that could have affected the set up. I spent all day yesterday trying to troubleshoot the issue but have been going around in circles.

OS: OSX 10.11.16

httpd -V returns this:

Server version: Apache/2.4.18 (Unix)
Server built:   Feb 20 2016 20:03:19
Server's Module Magic Number: 20120211:52
Server loaded:  APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture:   64-bit
Server MPM:     prefork
   threaded:     no
   forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_FLOCK_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/usr"
 -D SUEXEC_BIN="/usr/bin/suexec"
 -D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"

httpd.conf is configured to allow virtual hosts and nothing has changed in httpd-vhosts.conf file.

LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
...
# Virtual hosts
Include /private/etc/apache2/extra/httpd-vhosts.conf

apachectl configtest returns:

Syntax OK

I've tried running a port scan for 127.0.0.1 and http port 80 does not show. This and the connection being refused makes me think this is where the issue is but I don't know why. The OSX firewall is turned off. I've tried the solution posted here but it did not fix it.

My /etc/hosts file looks like this:

#
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
#

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
127.0.0.1       site.local
127.0.0.1       othersite.local
...

I can ping 127.0.0.1. I previously had homebrew installed to run different PHP versions but I've removed that to try and bring the system back to stock. I really don't know what to try next, any help would be really appreciated.


问:
Exporting site to WordPress
I've created a site over the last few months, and now I should upload it to a WordPress server.

On my own server, without WordPress, just PHP and ApacheWordPress2, everything works just fine. PHP includes include the CSS content as asked from root as a style.css.

I have all my CSS loaded in <?php include 'include/head.php';?>.

Part of the head.php file:

```<code><link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/normalize.min.css"/>
<link rel="stylesheet" type="text/css" href="js/vendor/slick/slick.css"/>
</code>```

1

But when I upload the site into project/wp-content/themes/project.
suddenly any of the resources won't load.

Everything from JavaScript scripts in /js folders, images in /img and extra CSS in the /css folder or even the style.css in root won't load. It's all just 404 on the inspectors network tab.

I've included the header part in style.css as requested by WordPress, but should I do something more?

The Inspector tab seems to indicate that it's trying to load from correct path, but it still gives 404.

My folder structure is following:

Inside wp-content/themes/project

```<code>pages.php(20 of them, also index.php)
style.css - basic css for site layout
css/ *more css files*
img/ *image files*
include/ *PHP includes*
js/ *js action for site*
</code>```

Octal for theme/project permission is: 2755

I hope this post makes any sense.

答:
You should enqueue your style like this in your function.php:</p>

```<code><?php add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));}

public function enqueue_styles() {
    wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css'); false);
}?>
</code>```

Title: Exporting site to WordPress

Body:
I've created a site over the last few months, and now I should upload it to a WordPress server.

On my own server, without WordPress, just PHP and ApacheWordPress2, everything works just fine. PHP includes include the CSS content as asked from root as a style.css.

I have all my CSS loaded in <?php include 'include/head.php';?>.

Part of the head.php file:

<link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/normalize.min.css"/>
<link rel="stylesheet" type="text/css" href="js/vendor/slick/slick.css"/>

1

But when I upload the site into project/wp-content/themes/project.
suddenly any of the resources won't load.

Everything from JavaScript scripts in /js folders, images in /img and extra CSS in the /css folder or even the style.css in root won't load. It's all just 404 on the inspectors network tab.

I've included the header part in style.css as requested by WordPress, but should I do something more?

The Inspector tab seems to indicate that it's trying to load from correct path, but it still gives 404.

My folder structure is following:

Inside wp-content/themes/project

pages.php(20 of them, also index.php)
style.css - basic css for site layout
css/ *more css files*
img/ *image files*
include/ *PHP includes*
js/ *js action for site*

Octal for theme/project permission is: 2755

I hope this post makes any sense.

Body:
You should enqueue your style like this in your function.php:

<?php add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));}

public function enqueue_styles() {
    wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css'); false);
}?>


问:
selenium - select dropdown. Unable to locate element
I am not able to select dropdown option using below code. This code returns error as element not located. Please assist. Thanks!!

```<code>    WebElement mySelectElement = driver.findElement(By.id("incident.severity"));
    Select dropdown= new Select(mySelectElement);
    dropdown.selectByVisibleText("3 - Medium");
</code>```

Exception in thread "Thread-2"
  org.openqa.selenium.NoSuchElementException: no such element: Unable to
  locate element: {"method":"id","selector":"incident.severity"}

Below is the dropdown screenshot and corresponding code.

Severity

<input name="sys_original.incident.severity"
       id="sys_original.incident.severity" type="hidden" value="4">
<select style="direction:ltr; " id="incident.severity"
      onchange="onChange('incident.severity');" class="form-control" ng-non-
      bindable="true" name="incident.severity" mandatory="false">
        <option value="1">1 - Critical</option>
        <option value="2">2 - High</option>
        <option value="3">3 - Medium</option>
        <option value="4" selected="SELECTED">4 - Low</option>
</select>

```

答:
NoSuchElementException occurs when the driver is not able to find the webelement in the DOM of the webpage.

One of the reason for such error is your page is not completely loaded and you are trying to find that webelement, try to wait for sometime before you search for the webelement. For the Wait you can use "Implicit wait".

Sample code:

```<code>//Initializing a WebDriverWait instance with a wait time of 30 seconds.
WebDriverWait wait = new WebDriverWait(driver,30);

//This code will wait till 30 seconds(Maximum) before throwing the exception.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("incident.severity")));

WebElement mySelectElement = driver.findElement(By.name("incident.severity"));
</code>```

Let me know if this helps.

Body:
I am not able to select dropdown option using below code. This code returns error as element not located. Please assist. Thanks!!

    WebElement mySelectElement = driver.findElement(By.id("incident.severity"));
    Select dropdown= new Select(mySelectElement);
    dropdown.selectByVisibleText("3 - Medium");

Exception in thread "Thread-2"
  org.openqa.selenium.NoSuchElementException: no such element: Unable to
  locate element: {"method":"id","selector":"incident.severity"}

Below is the dropdown screenshot and corresponding code.

Severity

<input name="sys_original.incident.severity"
       id="sys_original.incident.severity" type="hidden" value="4">
<select style="direction:ltr; " id="incident.severity"
      onchange="onChange('incident.severity');" class="form-control" ng-non-
      bindable="true" name="incident.severity" mandatory="false">
        <option value="1">1 - Critical</option>
        <option value="2">2 - High</option>
        <option value="3">3 - Medium</option>
        <option value="4" selected="SELECTED">4 - Low</option>
</select>

Body:
NoSuchElementException occurs when the driver is not able to find the webelement in the DOM of the webpage.

One of the reason for such error is your page is not completely loaded and you are trying to find that webelement, try to wait for sometime before you search for the webelement. For the Wait you can use "Implicit wait".

Sample code:

//Initializing a WebDriverWait instance with a wait time of 30 seconds.
WebDriverWait wait = new WebDriverWait(driver,30);

//This code will wait till 30 seconds(Maximum) before throwing the exception.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("incident.severity")));

WebElement mySelectElement = driver.findElement(By.name("incident.severity"));

Let me know if this helps.


问:
Reset Excel to default borders
Ok, so you know what a spreadsheet looks like when you open a new on in Excel; the borders are a light blue. These are only on the screen though, if you print the sheet it will not have borders. Say you've applied some various formatting to the sheet (background color, etc.) and those "default" borders are gone. My question is how to you get them back? Simply doing a Clear Formats will not always work.

Specifically I am talking about Excel 2007 but I believe all versions do this.

Any ideas?

Thanks,
Ryan

答:
I understand this is an old post. But it is programmable. Otherwise make sure your fill is set to "No Fill" and your boarders are set to "No Boarder" via the user interface shown in the previous posts.</p>

```<code>Sub clear()
Range("A4:G1000").Borders.LineStyle = xlNone
Range("A4:G1000").Interior.ColorIndex = xlNone
End Sub()
</code>```

Title: Reset Excel to default borders

Body:
I understand this is an old post. But it is programmable. Otherwise make sure your fill is set to "No Fill" and your boarders are set to "No Boarder" via the user interface shown in the previous posts.

Sub clear()
Range("A4:G1000").Borders.LineStyle = xlNone
Range("A4:G1000").Interior.ColorIndex = xlNone
End Sub()


问:
Adding hardware Back button to Home for Ionic in android
Ionic has a different navigation when press a function from side menu. When you press a back button from handset, it will straight away exit.

I refer to this tutorial and make the changes to my app.js but it unable to back to home page but exit the app.

The code suppose to (which is what I needed):

1.if not at home page, it will back to previous page if press hardware back button
2.if it is at home page, press hardware back button will show pop up to confirm if user really want to exit.

app.js

```<code>angular.module('myapp', ['ionic', 'myapp.controllers', 'myapp.factories'])
.run(function($ionicPlatform,$state,$ionicHistory,$ionicPopup) {
  $ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }

    $ionicPlatform.registerBackButtonAction(function (event) {
    event.preventDefault();
    if ($state.current.name == "app.home") {
      var confirmPopup = $ionicPopup.confirm({
        title: 'Exit',
        template: 'Confirm Exit'
      });

      confirmPopup.then(function (res) {
        if (res) {
          navigator.app.exitApp();
        }

      });
    } else {
      $ionicHistory.nextViewOptions({ disableBack: true });
      $state.go('app.home');
    }
  }, 100);//registerBackButton

});
})

  $stateProvider
      .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'templates/menu.html',
        controller: 'menuCtrl'
      })
      .state('app.home', {
        url: '/home',
        views: {
          'menuContent': {
            templateUrl: 'templates/home.html',
            controller: 'homeCtrl'
          }
        }
      })
      .state('app.personalitem', {
        url: '/personalitem',
        views: {
          'menuContent': {
            templateUrl: 'templates/personalitem.html',
            controller: 'personalitemCtrl'
          }
        }
      })
      .state('app.pStock', {
        url: '/pStock',
        views: {
          'menuContent': {
            templateUrl: 'templates/pStock.html',
            controller: 'pStockCtrl'
          }
        }
    });
angular.module('myapp.factories', []);
angular.module('myapp.controllers', []);
</code>```

How shall I do with my code so that I can get the hardware back button work?

答:
Can you try:

menu.ts
openPage(page) {
    this.nav.setRoot(page.component);
  }

menu.html
<button class="menuList" menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
          {{p.title}}
        </button>

app.component.ts
pages: any[] = [
    { title: 'Welcome', component: IntroPage },
    { title: 'Home', component: TabsPage },
  ]

Body:
Ionic has a different navigation when press a function from side menu. When you press a back button from handset, it will straight away exit.

I refer to this tutorial and make the changes to my app.js but it unable to back to home page but exit the app.

The code suppose to (which is what I needed):

1.if not at home page, it will back to previous page if press hardware back button
2.if it is at home page, press hardware back button will show pop up to confirm if user really want to exit.

app.js

angular.module('myapp', ['ionic', 'myapp.controllers', 'myapp.factories'])
.run(function($ionicPlatform,$state,$ionicHistory,$ionicPopup) {
  $ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }

    $ionicPlatform.registerBackButtonAction(function (event) {
    event.preventDefault();
    if ($state.current.name == "app.home") {
      var confirmPopup = $ionicPopup.confirm({
        title: 'Exit',
        template: 'Confirm Exit'
      });

      confirmPopup.then(function (res) {
        if (res) {
          navigator.app.exitApp();
        }

      });
    } else {
      $ionicHistory.nextViewOptions({ disableBack: true });
      $state.go('app.home');
    }
  }, 100);//registerBackButton

});
})

  $stateProvider
      .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'templates/menu.html',
        controller: 'menuCtrl'
      })
      .state('app.home', {
        url: '/home',
        views: {
          'menuContent': {
            templateUrl: 'templates/home.html',
            controller: 'homeCtrl'
          }
        }
      })
      .state('app.personalitem', {
        url: '/personalitem',
        views: {
          'menuContent': {
            templateUrl: 'templates/personalitem.html',
            controller: 'personalitemCtrl'
          }
        }
      })
      .state('app.pStock', {
        url: '/pStock',
        views: {
          'menuContent': {
            templateUrl: 'templates/pStock.html',
            controller: 'pStockCtrl'
          }
        }
    });
angular.module('myapp.factories', []);
angular.module('myapp.controllers', []);

How shall I do with my code so that I can get the hardware back button work?


问:
How to implement onBlur/onFocus for a div with nested input fields?
There is a
 and a couple of nested <input>s. onBlur fires every time user clicks on one of the <input>s.

This is a bit frustrating that onBlur happens when I hit something inside the div. After an hour of searching I still wasn't able to find any good solution.

This sample of code shows what I'm talking about:

```<code>class Thing extends React.Component {
  handleBlur(e) {
    console.log('blur');
  }
  handleFocus(e) {
    console.log('focus');
  }
  render() {
    return (
      <div onFocus={this.handleFocus} onBlur={this.handleBlur} tabIndex="1">
        <div>
          <input type="text" value="Hello," />
        </div>
        <div>
          <input type="text" value="Thing" />
        </div>
      </div>
    );
  }
}
</code>```

You may play around with the code over here.

However my ultimate goal is to make this thing working properly.

答:
You may want to ignore extra blur events.</p>

```<code>handleBlur(e) {
   if (e.target.tagName == "INPUT") {
      return;
   }
   console.log('blur');
}
handleFocus(e) {
   console.log('focus');
}
</code>```

Body:
There is a
 and a couple of nested <input>s. onBlur fires every time user clicks on one of the <input>s.

This is a bit frustrating that onBlur happens when I hit something inside the div. After an hour of searching I still wasn't able to find any good solution.

This sample of code shows what I'm talking about:

class Thing extends React.Component {
  handleBlur(e) {
    console.log('blur');
  }
  handleFocus(e) {
    console.log('focus');
  }
  render() {
    return (

          <input type="text" value="Hello," />

          <input type="text" value="Thing" />

    );
  }
}

You may play around with the code over here.

However my ultimate goal is to make this thing working properly.

Body:
You may want to ignore extra blur events.

handleBlur(e) {
   if (e.target.tagName == "INPUT") {
      return;
   }
   console.log('blur');
}
handleFocus(e) {
   console.log('focus');
}


问:
django.db.utils.IntegrityError: NOT NULL constraint failed
i'm trying to build a customised registration to my site, so i'm using a sign Up with Profile Model.

Traceback:

```<code>Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line
 41, in inner
 response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187,
 in _get_response
 response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185,
 in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\dev1\mysite\mysite\core\views.py", line 74, in
 complete_profile
 form.save()
File "C:\Python36\lib\site-packages\django\forms\models.py", line 451, in
 save
 self.instance.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 806, in
 save
force_update=force_update, update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 836, in
 save_base
 updated = self._save_table(raw, cls, force_insert, force_update, using,
 update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 922, in
 _save_table
 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 961, in
 _do_insert
 using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py", line 85,
 in manager_method
 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py", line 1060,
 in _insert
 return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py", line
 1099, in execute_sql
 cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 80,
 in execute
 return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py", line 94, in
 __exit__
 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py", line 685, in
 reraise
 raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py",
 line 328, in execute
 return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed:
core_profile.user_id
</code>```

i'm having this ERROR after submit a form that i made to let user complete profile information just after SignUp's email confirmation.
Look at this diagram

some of my code:

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(null=True, blank=True)
  birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
    Naissance"))
  email_confirmed = models.BooleanField(default=False)
  adress = models.CharField(max_length=80, verbose_name=("Adresse"))
  adress_complement = models.CharField(max_length=80, verbose_name=
    ("Complément d'Adresse"))
  city = models.CharField(max_length=80, verbose_name=("Ville"))
  zip_code = models.IntegerField(null=True, blank=True)
  drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
     Permis de conduire"))
  social_secu_num = models.IntegerField(null=True, blank=True)
  phone_number = models.IntegerField(null=True, blank=True)

  @receiver(post_save, sender=User)
  def update_user_profile(sender, instance, created, **kwargs):
     if created:
     Profile.objects.create(user=instance)
     instance.profile.save()
</code>```

forms.py

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile

class SignUpForm(UserCreationForm):
  email = forms.EmailField(max_length=254, help_text='Required. Inform a
          valid email address.')
  class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'username', 'password1',
                'password2',)

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    fields = ('birth_date','birth_place', 'adress', 'adress_complement',
              'city', 'zip_code', 'drive_licence_num', 'social_secu_num',
              'phone_number')
</code>```

views.py (complete_profile view)

```<code>def complete_profile(request):
  #if email_confirmed == True:
  if request.user.is_authenticated():
      if request.method == 'POST':

          form = ProfileForm(request.POST)
          if form.is_valid():
              form.save()

              return render(request, 'home.html')
      else:
          form = ProfileForm()
          return render(request, 'complete_profile.html', {'form': form})
  else:
      return render(request, 'login.html')
</code>```

答:
You may need to pass instance request.user.profile to the form.

```<code>def complete_profile(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = ProfileForm(request.POST, instance=request.user.profile)
            if form.is_valid():
                #form.instance.user = request.user
                form.save()
            return render(request, 'home.html')
        else:
            form = ProfileForm()
            return render(request, 'complete_profile.html', {'form': form})
    else:
        return render(request, 'login.html')
</code>```

Body:
i'm trying to build a customised registration to my site, so i'm using a sign Up with Profile Model.

Traceback:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line
 41, in inner
 response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187,
 in _get_response
 response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185,
 in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\dev1\mysite\mysite\core\views.py", line 74, in
 complete_profile
 form.save()
File "C:\Python36\lib\site-packages\django\forms\models.py", line 451, in
 save
 self.instance.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 806, in
 save
force_update=force_update, update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 836, in
 save_base
 updated = self._save_table(raw, cls, force_insert, force_update, using,
 update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 922, in
 _save_table
 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 961, in
 _do_insert
 using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py", line 85,
 in manager_method
 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py", line 1060,
 in _insert
 return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py", line
 1099, in execute_sql
 cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 80,
 in execute
 return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py", line 94, in
 __exit__
 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py", line 685, in
 reraise
 raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py",
 line 328, in execute
 return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed:
core_profile.user_id

i'm having this ERROR after submit a form that i made to let user complete profile information just after SignUp's email confirmation.
Look at this diagram

some of my code:

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(null=True, blank=True)
  birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
    Naissance"))
  email_confirmed = models.BooleanField(default=False)
  adress = models.CharField(max_length=80, verbose_name=("Adresse"))
  adress_complement = models.CharField(max_length=80, verbose_name=
    ("Complément d'Adresse"))
  city = models.CharField(max_length=80, verbose_name=("Ville"))
  zip_code = models.IntegerField(null=True, blank=True)
  drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
     Permis de conduire"))
  social_secu_num = models.IntegerField(null=True, blank=True)
  phone_number = models.IntegerField(null=True, blank=True)

  @receiver(post_save, sender=User)
  def update_user_profile(sender, instance, created, **kwargs):
     if created:
     Profile.objects.create(user=instance)
     instance.profile.save()

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile

class SignUpForm(UserCreationForm):
  email = forms.EmailField(max_length=254, help_text='Required. Inform a
          valid email address.')
  class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'username', 'password1',
                'password2',)

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    fields = ('birth_date','birth_place', 'adress', 'adress_complement',
              'city', 'zip_code', 'drive_licence_num', 'social_secu_num',
              'phone_number')

views.py (complete_profile view)

def complete_profile(request):
  #if email_confirmed == True:
  if request.user.is_authenticated():
      if request.method == 'POST':

          form = ProfileForm(request.POST)
          if form.is_valid():
              form.save()

              return render(request, 'home.html')
      else:
          form = ProfileForm()
          return render(request, 'complete_profile.html', {'form': form})
  else:
      return render(request, 'login.html')

Body:
You may need to pass instance request.user.profile to the form.

def complete_profile(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = ProfileForm(request.POST, instance=request.user.profile)
            if form.is_valid():
                #form.instance.user = request.user
                form.save()
            return render(request, 'home.html')
        else:
            form = ProfileForm()
            return render(request, 'complete_profile.html', {'form': form})
    else:
        return render(request, 'login.html')


问:
Calling gradle resValue from another file results in "Error:Gradle DSL method not found: 'resValue()'"
I have the following problem.

I have one main file app.gradle where I call

```<code>defaultConfig {
    resValue "string", "hello world", "1234567890"
}
</code>```

This works ok.
Now I'm trying to move that functionality to another file imported on the header with

```<code>apply from: "gradle_tasks.gradle"
</code>```

With the following content:

```<code>ext.AddResourcesVariables = { ->
    resValue "string", "hello world", "1234567890"
}
</code>```

And call it from the main gradle with

```<code>defaultConfig {
   AddResourcesVariables()
}
</code>```

Then I've got the following error:

```<code>Error:Gradle DSL method not found: 'resValue()'
</code>```

Am I missing some import?

Thank you!

答:
resValue() is a dsl method from defaultConfig. You can't import it.

You could define a map of [type][name][value] in a different file

```<code>ext.valueMap = [
   [type: "string", name: "hello world", value: "1234567890"],
   [type: "string", name: "hello world", value: "1234567890"],
]
</code>```

And then in the script, you iterate over it

```<code>defaultConfig{
  valueMap.each {
    resValue it.type, it.name, it.value
  }
}
</code>```

Haven't compile it, but should be close.

Body:
I have the following problem.

I have one main file app.gradle where I call

defaultConfig {
    resValue "string", "hello world", "1234567890"
}

This works ok.
Now I'm trying to move that functionality to another file imported on the header with

apply from: "gradle_tasks.gradle"

With the following content:

ext.AddResourcesVariables = { ->
    resValue "string", "hello world", "1234567890"
}

And call it from the main gradle with

defaultConfig {
   AddResourcesVariables()
}

Then I've got the following error:

Error:Gradle DSL method not found: 'resValue()'

Am I missing some import?

Thank you!

Body:
resValue() is a dsl method from defaultConfig. You can't import it.

You could define a map of [type][name][value] in a different file

ext.valueMap = [
   [type: "string", name: "hello world", value: "1234567890"],
   [type: "string", name: "hello world", value: "1234567890"],
]

And then in the script, you iterate over it

defaultConfig{
  valueMap.each {
    resValue it.type, it.name, it.value
  }
}

Haven't compile it, but should be close.


问:
How to create N list with a funtion(Not by writing it) that holds a dynamic name such as list1, list2, list3,... listn?
I'm a rookie at Python so I don't know much about the limits of the language, but it seems that you can't write a function or a program that creates a list on its own.

I'm working with binary lists. I'm working with 7 bits so, as you can guess, I need 128 different lists to store all possibilities.
Let me know if its possible, or if not please let me know why and what else could work for my needs.

```<code>    def list_creator:
        n=128
        "create a new_list n times with 7 of length"
        "Should display something like this"
        list1=[None]*7
        list2=[None]*7
        list(n)=[None]*7
</code>```

答: You should make a list containing 128 empty lists and add to those.</p>

Body:
I'm a rookie at Python so I don't know much about the limits of the language, but it seems that you can't write a function or a program that creates a list on its own.

I'm working with binary lists. I'm working with 7 bits so, as you can guess, I need 128 different lists to store all possibilities.
Let me know if its possible, or if not please let me know why and what else could work for my needs.

    def list_creator:
        n=128
        "create a new_list n times with 7 of length"
        "Should display something like this"
        list1=[None]*7
        list2=[None]*7
        list(n)=[None]*7


问:
Vectorising a code using xor in Matlab
I have an mxn array r in Matlab with elements that are zeros or ones.

I want to construct a vector p of dimension mxn such that for i=1,...,m

p(i,1)=r(i,1)

p(i,2)=r(i,2)XOR r(i,1)

p(i,3)=r(i,3) XOR r(i,2)

...

p(i,n)=r(i,n) XOR r(i,n-1)

This code does what I want but it is slow for m,n large. Could you suggest something faster?

```<code>m=4;
n=5;
r=[1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 0];

p=zeros(m,n);

for i=1:m
    p(i,1)=r(i,1);
    for j=2:n
        p(i,j)=xor(r(i,j),r(i,j-1));
    end
end
</code>```

答:
Sure:

```<code>p            = zeros(m,n);
p(:,1)       = r(:,1);
p(:,2:end)   = xor(  r(:,1:(end-1)),   r(:,2:n)   );
</code>```

What we're doing here is:

Pre-allocating the array. Same as your code.

Fill in the first column of p with the first column of r

Fill in the 2nd - last columns of p with the desired XOR operation. As inputs to the XOR we are using two large sections of r. The first is the 1st - (last-1)th columns. The second is the 2nd through last columns.

Title: Vectorising a code using xor in Matlab

Body:
I have an mxn array r in Matlab with elements that are zeros or ones.

I want to construct a vector p of dimension mxn such that for i=1,...,m

p(i,1)=r(i,1)

p(i,2)=r(i,2)XOR r(i,1)

p(i,3)=r(i,3) XOR r(i,2)

...

p(i,n)=r(i,n) XOR r(i,n-1)

This code does what I want but it is slow for m,n large. Could you suggest something faster?

m=4;
n=5;
r=[1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 0];

p=zeros(m,n);

for i=1:m
    p(i,1)=r(i,1);
    for j=2:n
        p(i,j)=xor(r(i,j),r(i,j-1));
    end
end

Body:
Sure:

p            = zeros(m,n);
p(:,1)       = r(:,1);
p(:,2:end)   = xor(  r(:,1:(end-1)),   r(:,2:n)   );

What we're doing here is:

Pre-allocating the array. Same as your code.

Fill in the first column of p with the first column of r

Fill in the 2nd - last columns of p with the desired XOR operation. As inputs to the XOR we are using two large sections of r. The first is the 1st - (last-1)th columns. The second is the 2nd through last columns.


问:
Spock fails when PostConstruct calls a injected service
Can any one tell me how to solve the issue of PostConstruct get called before mocking:

Service:

```<code>class MyService {
    SecondService secondService // injected

    @PostConstruct
    void init() {
        myFunction()
    }

    void myFunction() {
        secondService.doSomething()
    }

}
</code>```

Test:

```<code>@TestFor(MyService)
class MyServiceSpec extends Specification {
   void "testing my service"() {
      given:
         MyService service = GroovySpy(MyService) {
             myFunction() >> null
         }
      then:
         true
   }
}
</code>```

Gives following error:

```<code>Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke method doSomething() on null object
</code>```

答:
If you have @TestFor(MyService) - MyService instance will be created automatically and you can use it as 'service'. And you don't need to create MyService manually.

So you can only delete @TestFor(MyService) or use it and remove MyService service.

But you also need to correctly mock 'secondService'

```<code>@FreshRuntime
@TestFor(MyService)
class MyServiceSpec extends Specification {

    def secondService = GroovyMock(SecondService)

    def doWithSpring = {
        secondService(InstanceFactoryBean, secondService, SecondService)
    }

    void "testing my service"() {
        when:
        service.myFunction()
        then:
        1 * secondService.doSomething()
    }
}
</code>```

Body:
Can any one tell me how to solve the issue of PostConstruct get called before mocking:

Service:

class MyService {
    SecondService secondService // injected

    @PostConstruct
    void init() {
        myFunction()
    }

    void myFunction() {
        secondService.doSomething()
    }

}

Test:

@TestFor(MyService)
class MyServiceSpec extends Specification {
   void "testing my service"() {
      given:
         MyService service = GroovySpy(MyService) {
             myFunction() >> null
         }
      then:
         true
   }
}

Gives following error:

Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke method doSomething() on null object

Body:
If you have @TestFor(MyService) - MyService instance will be created automatically and you can use it as 'service'. And you don't need to create MyService manually.

So you can only delete @TestFor(MyService) or use it and remove MyService service.

But you also need to correctly mock 'secondService'

@FreshRuntime
@TestFor(MyService)
class MyServiceSpec extends Specification {

    def secondService = GroovyMock(SecondService)

    def doWithSpring = {
        secondService(InstanceFactoryBean, secondService, SecondService)
    }

    void "testing my service"() {
        when:
        service.myFunction()
        then:
        1 * secondService.doSomething()
    }
}


问:
Working with two databases from different domains within a same server
I have two domains.

In domain A, I have a PHP web site and in domain B, I have Java Website.

Now I want to use both database from both site.

How can I do that? I am using MySql 5.7.17

答:
You can open and close a mysql connection any time.

```<code>mysql_connect(server, username, password);
</code>```

Do some stuff with one database, then you can use:

```<code>mysql_close();
mysql_connect(server2, username2, password2);
</code>```

as many times as you like.

Or you can use resource links:

```<code>$db1 = mysql_connect(server1, user1, passwd1);
$db2 = mysql_connect(server2, user2, passwd2);
</code>```

But in this case, each mysql command needs to be referenced with the resource link:

```<code>mysql_query(query, $db1);
</code>```

Body:
You can open and close a mysql connection any time.

mysql_connect(server, username, password);

Do some stuff with one database, then you can use:

mysql_close();
mysql_connect(server2, username2, password2);

as many times as you like.

Or you can use resource links:

$db1 = mysql_connect(server1, user1, passwd1);
$db2 = mysql_connect(server2, user2, passwd2);

But in this case, each mysql command needs to be referenced with the resource link:

mysql_query(query, $db1);


问:
Get first record change timestamp when grouped by two columns SQL Server
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

```<code>id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')
</code>```

Expected output

```<code>id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')
</code>```

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

```<code>create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version
</code>```

答:
You can use a window function with a sub-query or CTE. Note that in your expected output, for ID 123 you didn't select the first instance... just the one with the minimum TIME, without consideration to the date. If that's what you really want, then you just need to use the time portion in the order by. i.e. (partition by id order by cast(timestamp as time))

```<code>select t.id, t.version, t.timestamp
from
YourTable t
inner join
(select
    id,
    version,
    timestamp,
    row_number() over (partition by id order by timestamp) as rn
from YourTable) x on x.id = t.id and x.timestamp = t.timestamp and x.version = t.version
where x.rn = 1
</code>```

Body:
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')

Expected output

id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version

Body:
You can use a window function with a sub-query or CTE. Note that in your expected output, for ID 123 you didn't select the first instance... just the one with the minimum TIME, without consideration to the date. If that's what you really want, then you just need to use the time portion in the order by. i.e. (partition by id order by cast(timestamp as time))

select t.id, t.version, t.timestamp
from
YourTable t
inner join
(select
    id,
    version,
    timestamp,
    row_number() over (partition by id order by timestamp) as rn
from YourTable) x on x.id = t.id and x.timestamp = t.timestamp and x.version = t.version
where x.rn = 1


问:
VBA Function Not Storing String
I am reposting this question, because I haven't gotten an answer and I still can't figure out what I'm doing wrong. My latest efforts to resolve the problem on my own are detailed below the code.

Original post: VBA Function not storing variable

I have included the code of my function. I mostly scrapped this together from things I found online, because I am very much an amateur coder. I am trying to take the trendline of a graph and use it for a mathematical calculation. When I step through this code, it works great. However, when I call the function from another sub, it gives me an error. Error 9: Subscript out of range. When I debug, it shows me the line a = spl(0). The real problem is that the variable "s" remains empty. Why?

```<code>Function TrendLineLog() As Double
Dim ch As Chart
Dim t As Trendline
Dim s As String
Dim Value As Double

' Get the trend line object
Set ch = ActiveSheet.ChartObjects(1).Chart
Set t = ch.SeriesCollection(1).Trendlines(1)

' make sure equation is displayed
t.DisplayRSquared = False
t.DisplayEquation = True

' set number format to ensure accuracy
t.DataLabel.NumberFormat = "0.000000E+00"

' get the equation
s = t.DataLabel.Text '<--------- ACTUAL PROBLEM HERE

' massage the equation string into form that will evaluate

s = Replace(s, "y = ", "")
s = Replace(s, "ln", " *LOG")
s = Replace(s, " +", "")
s = Replace(s, " - ", " -")
spl = Split(s, " ")
a = spl(0) '<----------- DEBUG SAYS HERE
b = spl(1)
c = spl(2)
y = 0.5

..... Math stuff

End Function
</code>```

I have tried adding the creation of the chart to the function to avoid an error with "Active Sheet". I also tried pasting this code into my sub instead of calling a separate function. Still nothing. When I debug and highlight the t.DataLabel.Text, it shows me the correct value, but for some reason s is not saving that value. In the Locals window, t has value, but s is blank (" ").

答:
Yes, of course you will get an error on the line you pointed out.  You are calling spl(0) as though it is its own function, though you did not define spl() as a sub (function) anywhere in this code.  Or, alternatively (more likely) you are calling it as an array, which also throws up some flags.

Make sure you are defining spl in your code.  You never do this.  Add line:

```<code>Dim spl(1 to 3) As String
</code>```

Then you should find that spl(1), spl(2), and spl(3) are what you desire.

Title: VBA Function Not Storing String

Body:
I am reposting this question, because I haven't gotten an answer and I still can't figure out what I'm doing wrong. My latest efforts to resolve the problem on my own are detailed below the code.

Original post: VBA Function not storing variable

I have included the code of my function. I mostly scrapped this together from things I found online, because I am very much an amateur coder. I am trying to take the trendline of a graph and use it for a mathematical calculation. When I step through this code, it works great. However, when I call the function from another sub, it gives me an error. Error 9: Subscript out of range. When I debug, it shows me the line a = spl(0). The real problem is that the variable "s" remains empty. Why?

Function TrendLineLog() As Double
Dim ch As Chart
Dim t As Trendline
Dim s As String
Dim Value As Double

' Get the trend line object
Set ch = ActiveSheet.ChartObjects(1).Chart
Set t = ch.SeriesCollection(1).Trendlines(1)

' make sure equation is displayed
t.DisplayRSquared = False
t.DisplayEquation = True

' set number format to ensure accuracy
t.DataLabel.NumberFormat = "0.000000E+00"

' get the equation
s = t.DataLabel.Text '<--------- ACTUAL PROBLEM HERE

' massage the equation string into form that will evaluate

s = Replace(s, "y = ", "")
s = Replace(s, "ln", " *LOG")
s = Replace(s, " +", "")
s = Replace(s, " - ", " -")
spl = Split(s, " ")
a = spl(0) '<----------- DEBUG SAYS HERE
b = spl(1)
c = spl(2)
y = 0.5

..... Math stuff

End Function

I have tried adding the creation of the chart to the function to avoid an error with "Active Sheet". I also tried pasting this code into my sub instead of calling a separate function. Still nothing. When I debug and highlight the t.DataLabel.Text, it shows me the correct value, but for some reason s is not saving that value. In the Locals window, t has value, but s is blank (" ").

Body:
Yes, of course you will get an error on the line you pointed out.  You are calling spl(0) as though it is its own function, though you did not define spl() as a sub (function) anywhere in this code.  Or, alternatively (more likely) you are calling it as an array, which also throws up some flags.

Make sure you are defining spl in your code.  You never do this.  Add line:

Dim spl(1 to 3) As String

Then you should find that spl(1), spl(2), and spl(3) are what you desire.


问:
Count how many occurrences of substrings within a string without counting duplicates
For example, I have a list of terms and a string:

```<code>var terms = { "programming language", "programming", "language" };

var content = "A programming language is a formal language that "
    + "specifies a set of instructions that can be used to "
    + "produce various kinds of output.";
</code>```

I can use Regex.Matches(content, term).Count to count that there are 4 times the list appear in the string:

"programming language": 1 time

"programming": 1 time

"language": 2 times

But there are duplicates, there should be only 2 occurrences.

My current solution is to save the begin index and end index of each occurrence, then compare to the saved occurences wherever it is in range and has already been count. Is there a better way without using start and end indexes?

答:
After suggestions from comments, I have a simple solution using regex, it should work with exact whole word, i.e. programming language can be counted but programming languages cannot:

```<code>var pattern = @"(?<!\S)programming language(?![^\s])|(?<!\S)programming(?![^\s])|(?<!\S)language(?![^\s])";
var count = Regex.Matches(content, pattern).Count;
</code>```

Note: this pattern can only be used when programming language is placed before programming and language terms. If anyone can contribute a better solution, please do so.

Body:
For example, I have a list of terms and a string:

var terms = { "programming language", "programming", "language" };

var content = "A programming language is a formal language that "
    + "specifies a set of instructions that can be used to "
    + "produce various kinds of output.";

I can use Regex.Matches(content, term).Count to count that there are 4 times the list appear in the string:

"programming language": 1 time

"programming": 1 time

"language": 2 times

But there are duplicates, there should be only 2 occurrences.

My current solution is to save the begin index and end index of each occurrence, then compare to the saved occurences wherever it is in range and has already been count. Is there a better way without using start and end indexes?

Body:
After suggestions from comments, I have a simple solution using regex, it should work with exact whole word, i.e. programming language can be counted but programming languages cannot:

var pattern = @"(?<!\S)programming language(?![^\s])|(?<!\S)programming(?![^\s])|(?<!\S)language(?![^\s])";
var count = Regex.Matches(content, pattern).Count;

Note: this pattern can only be used when programming language is placed before programming and language terms. If anyone can contribute a better solution, please do so.


问:
PHP Authentication
Currently my authentication looks like this:

User enters username/password combination
 Sent to the server, the username and password are salted and hashed (md5) and checked against the database.

If correct, and the user has specified, a month long cookie is set.

If the user does not specify to set a cookie, they are automatically signed out after five minutes of inactivity.

My question is simply if I need to, and how to, make this more secure. I'm pretty fluent in PHP, but I'm not as well off in security. Any help, pointers, leads, and general assistance would be appreciated.

Thanks. :)

答:
Here are some ideas:

Most important is to use SSL.
Password is sent over clear text
which means anybody can see it.

What is the cookie you are setting?
Can I copy that cookie and then be
authorized as you? Maybe think about
creating a random token and set that

Are you protecting against cross
site forgery and cross site
scripting?

That's all I can think of.

Title: PHP Authentication


问:
dojo dstore insert row
Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.</p>

```<code>// Clone a row

theTable = tmxdijit.registry.byId(tableName);

firstRow = theTable.collection.data[theTable.collection.data.length-1];

firstRowDom = theTable.row(firstRow.id);

var cloneRow = json.stringify(firstRow);

cloneRow = json.parse(cloneRow);

// Get the row I want to add before

var theSelected = Object.keys(theTable.selection)[0];

if(theSelected.length > 0) {

    var theRowID = theSelected[0];

}

theTable.collection.add(cloneRow, {beforeId: theRowID});

theTable.renderArray([cloneRow]);
</code>```

答:
Instead of this, why don't you add the data directly to the grid store? See if this helps

```<code>https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
</code>```

Adding and Deleting data

If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.

```<code>dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
</code>```

.

```<code><div>
    This example shows, how to add/remove rows
</div>

<table data-dojo-type="dojox.grid.DataGrid"
    data-dojo-id="grid5"
    data-dojo-props="store:store3,
    query:{ name: '*' },
    rowsPerPage:20,
    clientSort:true,
    rowSelector:'20px'
    style="width: 400px; height: 200px;">
    <thead>
        <tr>
            <th width="200px"
                field="name">Country/Continent Name</th>
            <th width="auto"
                field="type"
                cellType="dojox.grid.cells.Select"
                options="country,city,continent"
                editable="true">Type</th>
        </tr>
    </thead>
</table>

<div data-dojo-type="dijit.form.Button">
    Add Row
    <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
        // set the properties for the new item:
        var myNewItem = {type: "country", name: "Fill this country name"};
        // Insert the new item into the store:
        // (we use store3 from the example above in this example)
        store3.newItem(myNewItem);
    </script>
</div>

<div data-dojo-type="dijit.form.Button">
    Remove Selected Rows
    <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
        // Get all selected items from the Grid:
        var items = grid5.selection.getSelected();
        if(items.length){
            // Iterate through the list of selected items.
            // The current item is available in the variable
            // "selectedItem" within the following function:
            dojo.forEach(items, function(selectedItem){
                if(selectedItem !== null){
                    // Delete the item from the data store:
                    store3.deleteItem(selectedItem);
                } // end if
            }); // end forEach
        } // end if
    </script>
</div>
</code>```

.

```<code>@import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
@import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";
</code>```

Title: dojo dstore insert row

Body:
Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.

// Clone a row

theTable = tmxdijit.registry.byId(tableName);

firstRow = theTable.collection.data[theTable.collection.data.length-1];

firstRowDom = theTable.row(firstRow.id);

var cloneRow = json.stringify(firstRow);

cloneRow = json.parse(cloneRow);

// Get the row I want to add before

var theSelected = Object.keys(theTable.selection)[0];

if(theSelected.length > 0) {

    var theRowID = theSelected[0];

}

theTable.collection.add(cloneRow, {beforeId: theRowID});

theTable.renderArray([cloneRow]);

Body:
Instead of this, why don't you add the data directly to the grid store? See if this helps

https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html

Adding and Deleting data

If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.

dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");

.

<div>
    This example shows, how to add/remove rows
</div>

<table data-dojo-type="dojox.grid.DataGrid"
    data-dojo-id="grid5"
    data-dojo-props="store:store3,
    query:{ name: '*' },
    rowsPerPage:20,
    clientSort:true,
    rowSelector:'20px'
    style="width: 400px; height: 200px;">
    <thead>
        <tr>
            <th width="200px"
                field="name">Country/Continent Name</th>
            <th width="auto"
                field="type"
                cellType="dojox.grid.cells.Select"
                options="country,city,continent"
                editable="true">Type</th>
        </tr>
    </thead>
</table>

<div data-dojo-type="dijit.form.Button">
    Add Row
    <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
        // set the properties for the new item:
        var myNewItem = {type: "country", name: "Fill this country name"};
        // Insert the new item into the store:
        // (we use store3 from the example above in this example)
        store3.newItem(myNewItem);
    </script>
</div>

<div data-dojo-type="dijit.form.Button">
    Remove Selected Rows
    <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
        // Get all selected items from the Grid:
        var items = grid5.selection.getSelected();
        if(items.length){
            // Iterate through the list of selected items.
            // The current item is available in the variable
            // "selectedItem" within the following function:
            dojo.forEach(items, function(selectedItem){
                if(selectedItem !== null){
                    // Delete the item from the data store:
                    store3.deleteItem(selectedItem);
                } // end if
            }); // end forEach
        } // end if
    </script>
</div>

.

@import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
@import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";


问:
Virtually turn vector of struct into vector of struct members
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

```<code>#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}
</code>```

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

```<code>#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}
</code>```

答:
```<code>template<class F>
struct index_fake_t{
  F f;
  decltype(auto) operator[](std::size_t i)const{
    return f(i);
  }
};
template<class F>
index_fake_t<F> index_fake( F f ){
  return{std::move(f)};
}
template<class F>
auto reindexer(F f){
  return [f=std::move(f)](auto&& v)mutable{
    return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
      return v[f(i)];
    });
  };
}
template<class F>
auto indexer_mapper(F f){
  return [f=std::move(f)](auto&& v)mutable{
    return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
      return f(v[i]);
    });
  };
}
</code>```

Now, print in order can be rewritten as:

```<code>template <typename vectorlike>
void print(vectorlike const & printme) {
  for (auto&& x:printme)
    std::cout << x << std::endl;
}
template <typename vectorlike>
void print_in_order(std::vector<int> const& reorder, vectorlike const & printme) {
  print(reindexer([&](auto i){return reorder[i];})(printme));
}
</code>```

and printing .a as:

```<code>print_in_order( reorder, indexer_mapper([](auto&&x){return x.a;})(printme) );
</code>```

there may be some typos.

Body:
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}

Body:
template<class F>
struct index_fake_t{
  F f;
  decltype(auto) operator[](std::size_t i)const{
    return f(i);
  }
};
template<class F>
index_fake_t<F> index_fake( F f ){
  return{std::move(f)};
}
template<class F>
auto reindexer(F f){
  return [f=std::move(f)](auto&& v)mutable{
    return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
      return v[f(i)];
    });
  };
}
template<class F>
auto indexer_mapper(F f){
  return [f=std::move(f)](auto&& v)mutable{
    return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
      return f(v[i]);
    });
  };
}

Now, print in order can be rewritten as:

template <typename vectorlike>
void print(vectorlike const & printme) {
  for (auto&& x:printme)
    std::cout << x << std::endl;
}
template <typename vectorlike>
void print_in_order(std::vector<int> const& reorder, vectorlike const & printme) {
  print(reindexer([&](auto i){return reorder[i];})(printme));
}

and printing .a as:

print_in_order( reorder, indexer_mapper([](auto&&x){return x.a;})(printme) );

there may be some typos.


问:
Check first element of the array needs to be unique
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

```<code>public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}
</code>```

答:
```<code>// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);
</code>```

Initializing the String[59] isn't helping you; the split method is just returning something that overwrites it immediately afterwards.

If you needed to check for any duplicates, using a HashSet would help here.

If you only need to make sure the first element isn't duplicated, you can just do it in a loop.  You've already got one, so...

```<code>// print array
for(int j = 0; j < stringArray.length; j++) {
        if (stringArray[0].equals(stringArray(j)) {
            System.out.println("Duplicate!");
        }
        System.out.println(j + " " + stringArray[j]);
    }
}
</code>```

Body:
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}

Body:
// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

Initializing the String[59] isn't helping you; the split method is just returning something that overwrites it immediately afterwards.

If you needed to check for any duplicates, using a HashSet would help here.

If you only need to make sure the first element isn't duplicated, you can just do it in a loop.  You've already got one, so...

// print array
for(int j = 0; j < stringArray.length; j++) {
        if (stringArray[0].equals(stringArray(j)) {
            System.out.println("Duplicate!");
        }
        System.out.println(j + " " + stringArray[j]);
    }
}


问:
Return an array from VB Script to JQuery in classic ASP for Autocomplete text box
I am a beginner for web development and currently adding an autocomplete text box which retrieved data from MS SQL server based on user input.

I declared an array called CodeList in JQuery and casting the return code from VB script function called getListOfCode. It is throwing an error that array: CodeList cannot be casted into function: getListOfCode.
(Error code: ASP_0106_:_80020005|Type_Mismatch)

I tried to Redim Function getListOfCode() as an array in VB script but it did not work. Could anyone please provide me some advice?

VB Script part

```<code><%
Function getListOfCode()

    Set objRec = Server.CreateObject("ADODB.Recordset")

    strSQL = "Select distinct Code_A, Code_A + " & " ' : ' " & _
                " + Long_Name AS Code_Name " & _
                 "FROM  CodeMaster " & _
                 "Where Type = 'A' "

    objrec.Open  strSQL, objConnect

    Dim CodeList(), i
    Redim CodeList(objrec.Fields.Count - 1)
    i = 0

    Do Until i < objrec.Fields.Count - 1

        CodeList(i) = objrec.Fields("Code_Name")

        i = i + 1
        objrec.MoveNext

    Loop

    getListOfCode = CodeList
    >> To return an array to Java Script with casting.
    If I write CodeList(i), it does not throw an error
    which means getListOfCode is being recognized as a string

    objRec.Close
    Set objRec = Nothing

End Function
%>
</code>```

JQuery part

```<code>  $(function() {
var CodeList = [
  <%= getListOfCode() %>
];
$( "#frmCode" ).autocomplete({
  source: CodeList
});
});
</code>```

Any advice would be appreciated. Thank you in advance.

答:
Just change this line:

getListOfCode = CodeList

to:

```<code>getListOfCode = String.Join(",", CodeList)
</code>```

And that should do it!  The string will be rendered as a raw JSON array in the ASP file.

Also, change this line:

```<code>CodeList(i) = objrec.Fields("Code_Name")
</code>```

to include quotes such that the JS interprets your strings as actual JS strings:

```<code>CodeList(i) = """" & objrec.Fields("Code_Name") & """"
</code>```

Body:
I am a beginner for web development and currently adding an autocomplete text box which retrieved data from MS SQL server based on user input.

I declared an array called CodeList in JQuery and casting the return code from VB script function called getListOfCode. It is throwing an error that array: CodeList cannot be casted into function: getListOfCode.
(Error code: ASP_0106_:_80020005|Type_Mismatch)

I tried to Redim Function getListOfCode() as an array in VB script but it did not work. Could anyone please provide me some advice?

VB Script part

<%
Function getListOfCode()

    Set objRec = Server.CreateObject("ADODB.Recordset")

    strSQL = "Select distinct Code_A, Code_A + " & " ' : ' " & _
                " + Long_Name AS Code_Name " & _
                 "FROM  CodeMaster " & _
                 "Where Type = 'A' "

    objrec.Open  strSQL, objConnect

    Dim CodeList(), i
    Redim CodeList(objrec.Fields.Count - 1)
    i = 0

    Do Until i < objrec.Fields.Count - 1

        CodeList(i) = objrec.Fields("Code_Name")

        i = i + 1
        objrec.MoveNext

    Loop

    getListOfCode = CodeList
    >> To return an array to Java Script with casting.
    If I write CodeList(i), it does not throw an error
    which means getListOfCode is being recognized as a string

    objRec.Close
    Set objRec = Nothing

End Function
%>

JQuery part

  $(function() {
var CodeList = [
  <%= getListOfCode() %>
];
$( "#frmCode" ).autocomplete({
  source: CodeList
});
});

Any advice would be appreciated. Thank you in advance.

Body:
Just change this line:

getListOfCode = CodeList

to:

getListOfCode = String.Join(",", CodeList)

And that should do it!  The string will be rendered as a raw JSON array in the ASP file.

Also, change this line:

CodeList(i) = objrec.Fields("Code_Name")

to include quotes such that the JS interprets your strings as actual JS strings:

CodeList(i) = """" & objrec.Fields("Code_Name") & """"


问:
TensorFlow / TFLearn LinearRegressor stops with a very high loss
I am using Tensorflow 1.2, here's the code:

```<code>import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np
import tensorflow.contrib.learn as tflearn

tf.logging.set_verbosity(tf.logging.INFO)

# Naturally this is a very simple straight line
# of y = -x + 10
train_x = np.asarray([0., 1., 2., 3., 4., 5.])
train_y = np.asarray([10., 9., 8., 7., 6., 5.])

test_x = np.asarray([10., 11., 12.])
test_y = np.asarray([0., -1., -2.])

input_fn_train = tflearn.io.numpy_input_fn({"x": train_x}, train_y, num_epochs=1000)
input_fn_test = tflearn.io.numpy_input_fn({"x": test_x}, test_y, num_epochs=1000)

validation_monitor = tflearn.monitors.ValidationMonitor(
    input_fn=input_fn_test,
    every_n_steps=10)

fts = [layers.real_valued_column('x')]

estimator = tflearn.LinearRegressor(feature_columns=fts)
estimator.fit(input_fn=input_fn_train,
              steps=1000,
              monitors=[validation_monitor])

print(estimator.evaluate(input_fn=input_fn_test))
</code>```

It runs as expected. What's happening is that the training stops at step 47 with a very high loss value:

```<code>INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Saving dict for global step 1: global_step = 1, loss = 12.5318
INFO:tensorflow:Validation (step 10): global_step = 1, loss = 12.5318
INFO:tensorflow:Saving checkpoints for 47 into
INFO:tensorflow:Loss for final step: 19.3527.
INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Restoring parameters from
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Saving dict for global step 47: global_step = 47, loss = 271.831

{'global_step': 47, 'loss': 271.83133}
</code>```

Few things I completely don't understand (admittedly I'm a complete noob in TF):

Why the loss on step 10 is smaller than loss on step 47?

Why TF decides to stop the training anyway after?

Why "INFO:tensorflow:Loss for final step: 19.3527." and the loss at step 47 do not match each other?

I have imlemented this very algorithm using vanilla TensorFlow and it works as expected, but I really can't get the grasp of what LinearRegressor wants from me here.

答:
here are some (partial) answers to your questions. Might not address all your questions but hopefully will give you some more insights.

Why TF decides to stop the training anyway after?
This has to do with the fact that you have set num_epochs=1000 and the default batch_size of numpy_input_fn is 128 (see https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/learn_io/numpy_io.py).
num_epochs=1000 means that fit method will go through the data at most 1000 times (or 1000 steps, whichever occurs first). That's why fit runs for ceiling(1000 * 6 /128)=47 steps. Setting batch_size to 6 (the size of your training dataset) or num_epochs=None will give you more reasonable results (I suggest setting batch_size to at most 6 since using your training samples cyclically more than once in a single step might not make much sense)

Why the loss on step 10 is smaller than loss on step 47?
There are a few different reasons the loss might not decrease.
a. not computing the loss on the exact same data at each step. For instance if you sample has size 100 and your batch_size is 32, every step you will compute loss on the next batch of size 32 (this continues cyclically)
b. Your learning rate is too high so the loss bounces. To fix this, maybe try to reduce the learning rate or even experiment with different optimizers. I believe by default, the optimizer used in LinearRegressor is FtrlOptimizer. You can change its default learning rate using the following command when you construct LinearRegressor:

estimator =tflearn.LinearRegressor(
    feature_columns=fts,
    optimizer=tf.train.FtrlOptimizer(learning_rate=...))

Alternatively, you can try a different optimizer altogether.
estimator = tflearn.LinearRegressor(
    feature_columns=fts,
    optimizer=tf.train.GradientDescentOptimizer(learning_rate=...))

Body:
I am using Tensorflow 1.2, here's the code:

import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np
import tensorflow.contrib.learn as tflearn

tf.logging.set_verbosity(tf.logging.INFO)

# Naturally this is a very simple straight line
# of y = -x + 10
train_x = np.asarray([0., 1., 2., 3., 4., 5.])
train_y = np.asarray([10., 9., 8., 7., 6., 5.])

test_x = np.asarray([10., 11., 12.])
test_y = np.asarray([0., -1., -2.])

input_fn_train = tflearn.io.numpy_input_fn({"x": train_x}, train_y, num_epochs=1000)
input_fn_test = tflearn.io.numpy_input_fn({"x": test_x}, test_y, num_epochs=1000)

validation_monitor = tflearn.monitors.ValidationMonitor(
    input_fn=input_fn_test,
    every_n_steps=10)

fts = [layers.real_valued_column('x')]

estimator = tflearn.LinearRegressor(feature_columns=fts)
estimator.fit(input_fn=input_fn_train,
              steps=1000,
              monitors=[validation_monitor])

print(estimator.evaluate(input_fn=input_fn_test))

It runs as expected. What's happening is that the training stops at step 47 with a very high loss value:

INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Saving dict for global step 1: global_step = 1, loss = 12.5318
INFO:tensorflow:Validation (step 10): global_step = 1, loss = 12.5318
INFO:tensorflow:Saving checkpoints for 47 into
INFO:tensorflow:Loss for final step: 19.3527.
INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Restoring parameters from
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Saving dict for global step 47: global_step = 47, loss = 271.831

{'global_step': 47, 'loss': 271.83133}

Few things I completely don't understand (admittedly I'm a complete noob in TF):

Why the loss on step 10 is smaller than loss on step 47?

Why TF decides to stop the training anyway after?

Why "INFO:tensorflow:Loss for final step: 19.3527." and the loss at step 47 do not match each other?

I have imlemented this very algorithm using vanilla TensorFlow and it works as expected, but I really can't get the grasp of what LinearRegressor wants from me here.


问:
Content script loading images from an extension ( CSP )
I'm developing a browser extension both for chrome & firefox.

My content script injects (only in twitter) some new images hosted from another server.

Here is a basic example of what am I doing :

```<code>fetch('mysite.com')
    .then(data => {
         let imgTag = document.createElement('img');
         imgTag.src = data.url; // (https://example.com/image.jpg)
         div.appendChild(imgTag);
    });
</code>```

It works on chrome but not in firefox, the console is showing a Content Security Policy related error, it simply says that the CSP rules that are applied on twitter doesn't allow for my hosted images to load.

What bugs me is why it is working on chrome just fine ?

答:
Bundle the images with your extension. Extension URLs (moz-extension://) are exempt from CSP.

If you need dynamic content then you'll have to wait until issue 1294996 or 1267027 gets implemented.

Body:
I'm developing a browser extension both for chrome & firefox.

My content script injects (only in twitter) some new images hosted from another server.

Here is a basic example of what am I doing :

fetch('mysite.com')
    .then(data => {
         let imgTag = document.createElement('img');
         imgTag.src = data.url; // (https://example.com/image.jpg)
         div.appendChild(imgTag);
    });

It works on chrome but not in firefox, the console is showing a Content Security Policy related error, it simply says that the CSP rules that are applied on twitter doesn't allow for my hosted images to load.

What bugs me is why it is working on chrome just fine ?


问:
Dagger 2 components not generated when using Jack
When I enable the Jack compiler in Android Studio 2.2 the Dagger 2 component is not generated. Can Dagger 2 be used with Jack? If so, how would I go about configuring my application?

From my application's build.gradle:

```<code>jackOptions {
     enabled true
   }

 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
</code>```

答:
Jack is now deprecated, see this post.

You have to upgrade your Android Studio to 3.0 preview 1, to be able to use Java 8.

If you can't upgrade it (conflict with other lib), or you want to wait for a release version, you can try this workaround solution :

Add the retrolamba lib, follow instructions here.

Body:
When I enable the Jack compiler in Android Studio 2.2 the Dagger 2 component is not generated. Can Dagger 2 be used with Jack? If so, how would I go about configuring my application?

From my application's build.gradle:

jackOptions {
     enabled true
   }

 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}


问:
Update array object by specific index
How can I update groceries item(set completed to True) in my toggleGroceryCompleteness method?

I tried this.setState({groceries[groceryIndex]:{completed:true});

```<code>   constructor(props) {
    super(props);
    this.state = {
      groceries: [
        {
          name: "Apples",
          completed: false
        }
      ],
      newGroceryName: ""
    };

  toggleGroceryCompleteness(groceryIndex) {
    console.log(groceryIndex);
    console.log(this.state.groceries[groceryIndex]);
  }
</code>```

答:
Since you're editing the value of a previously set state, you should use this definition of setState

```<code>this.setState((prevState, props) => {
    const newGroceries = prevState.groceries.slice()
    newGroceries[groceryIndex].completed = true

    return { ...prevState, groceries: newGroceries }
})
</code>```

This takes the value of the groceries state array from before the setState call and assigns it to a new variable to be modified, accessing the given index and sets the completed property to true. Then returns a new object/state containing everything from the previous state value but a modified groceries property which is the new modified version.

Title: Update array object by specific index

Body:
How can I update groceries item(set completed to True) in my toggleGroceryCompleteness method?

I tried this.setState({groceries[groceryIndex]:{completed:true});

   constructor(props) {
    super(props);
    this.state = {
      groceries: [
        {
          name: "Apples",
          completed: false
        }
      ],
      newGroceryName: ""
    };

  toggleGroceryCompleteness(groceryIndex) {
    console.log(groceryIndex);
    console.log(this.state.groceries[groceryIndex]);
  }

Body:
Since you're editing the value of a previously set state, you should use this definition of setState

this.setState((prevState, props) => {
    const newGroceries = prevState.groceries.slice()
    newGroceries[groceryIndex].completed = true

    return { ...prevState, groceries: newGroceries }
})

This takes the value of the groceries state array from before the setState call and assigns it to a new variable to be modified, accessing the given index and sets the completed property to true. Then returns a new object/state containing everything from the previous state value but a modified groceries property which is the new modified version.