问:
How do I select from tables with a specifically named column when that column contains a specific value?
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

```<code>    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'
</code>```

but then I have no clue how to continue. Any help is appreciated :)

答:
This code is tested and it works:

Create a cursor that selects all of the table/column names where column = ID (we didn't need a column variable since you are only targeting 'ID', but I included it in case you or someone else needs more functionality).

Once you have that information stored, you can loop through the cursor and execute the dynamic SQL.  Note that this is susceptible to SQL-injection, as is the case with practically all dynamic SQL.

This approach will give you a separate datatable for each table that has a column ID - even if there are no ID columns that meet your conditions (you'll just get a blank datatable for those).

Also, you can change the size of the variables as needed.

Please let me know if you need any clarification or modifications.

```<code> DECLARE @TableName varchar(255), @ColumnName varchar(255), @SQL varchar(1000)

 DECLARE TempCursor CURSOR FOR
 SELECT T.[name] AS [TableName], C.[name] AS [ColumnName]
 FROM sys.tables T
 JOIN sys.columns C
    ON T.object_id = C.object_id
 WHERE C.[name] = 'ID'

 OPEN TempCursor
 FETCH NEXT FROM TempCursor INTO @TableName, @ColumnName
 WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @SQL = 'SELECT * FROM ' + @TableName
        SET @SQL = @SQL + ' WHERE ' + @ColumnName + ' like ''a%'''
        EXECUTE (@SQL)

        FETCH NEXT FROM TempCursor INTO @TableName, @ColumnName

    END

CLOSE TempCursor
DEALLOCATE TempCursor
</code>```

Body:
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'

but then I have no clue how to continue. Any help is appreciated :)

Body:
This code is tested and it works:

Create a cursor that selects all of the table/column names where column = ID (we didn't need a column variable since you are only targeting 'ID', but I included it in case you or someone else needs more functionality).

Once you have that information stored, you can loop through the cursor and execute the dynamic SQL.  Note that this is susceptible to SQL-injection, as is the case with practically all dynamic SQL.

This approach will give you a separate datatable for each table that has a column ID - even if there are no ID columns that meet your conditions (you'll just get a blank datatable for those).

Also, you can change the size of the variables as needed.

Please let me know if you need any clarification or modifications.

 DECLARE @TableName varchar(255), @ColumnName varchar(255), @SQL varchar(1000)

 DECLARE TempCursor CURSOR FOR
 SELECT T.[name] AS [TableName], C.[name] AS [ColumnName]
 FROM sys.tables T
 JOIN sys.columns C
    ON T.object_id = C.object_id
 WHERE C.[name] = 'ID'

 OPEN TempCursor
 FETCH NEXT FROM TempCursor INTO @TableName, @ColumnName
 WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @SQL = 'SELECT * FROM ' + @TableName
        SET @SQL = @SQL + ' WHERE ' + @ColumnName + ' like ''a%'''
        EXECUTE (@SQL)

        FETCH NEXT FROM TempCursor INTO @TableName, @ColumnName

    END

CLOSE TempCursor
DEALLOCATE TempCursor


来源: stackexchange

问:
Python - appended character gets lost
Hey I´m quite new to python and i´m writing a script to sort through a file in for some keywords, and everything works fine except a small reading/printing miss that i don´t understand... This is my problem code and the file im scanning through:

```<code>File:
    SEND TEST
    Tester -> 1FFF 19 02 0F :\user\log
    SEND TEST
    Tester -> 1FFF 18 00 0F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 12 11 5F :\user\log
    SEND TEST
    Tester -> 1FFF 12 55 1F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 19 03 2F :\user\log
code:
      if line.startswith('Tester ->'):
         start = 'Tester -> '  # take string from
         end = ':\ ' # end at
         data.append(line[line.find(start) + 9 :line.find(end)].strip('[Channel 1]'))
</code>```

this prints

```<code>1FFF 19 02 0F
1FFF 18 00 0F [Channel 1]
1FFF 12 11 5F
1FFF 12 55 1F [Channel 1]
1FFF 19 03 2F
</code>```

The data.append string has the problem, as shown in the print i works, but i want to extract the code ex 1FFF 12 55 1F but not [Channel 1] aslo... so i used .strip to remove it, but then i get this print:

```<code>1FFF 19 02 0F
FFF 18 00 0F
1FFF 12 11 5F
FFF 12 55 1F
1FFF 19 03 2F
</code>```

All strings that has [Channel 1] loses the first character and if i put a 8 instead of a 9 in data.apped it prints:

```<code>1FFF 19 02 0F
> 1FFF 18 00 0F
1FFF 12 11 5F
> 1FFF 12 55 1F
1FFF 19 03 2F
</code>```

Then it takes the > from the Tester -> and I don´t understand why? it skips the character in between for some reason? It´s like when I have a 9 it counts every character including spaces and when I have a 8 it counts characters but not including spaces... how is that possible? someone who knows how to fix this, thanks!

```<code># Sending Request: Tester -> 1631 11 33 F5 :\ APP_3130 \ Read Identifier \
Tester -> 1631 22 F1 2E :\ APP_3138 \ Read Identifier \
Tester -> 1FFF 19 02 0F [Channel 1]
</code>```

答:
The problem is that strip('chars') removes all combinations of 'chars' as noted here: https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip

So what you're really saying is remove the characters [, C, h, a, , n, e, l, 1, and ] from my string.

If you just want to remove [Channel 1] I would do the following:

```<code>import re

line = re.sub(r"\[Channel 1\]$", "", line)
</code>```

This regex pattern will only match the text [Channel 1] if it is as the end of the line.

or alternatively if you don't want to include the regex module you could use

```<code>line = line.replace("[Channel 1]", "")
</code>```

This solution will replace [Channel 1] regardless of where it shows up in the line.

=================

The best solution here is to use regex and skip the entire start and end thing. You can do the following:

```<code>import re

pattern = re.compile(r"Tester ->\s((?:(?:\w+)+\s)+)(?:\[Channel \d\])?\s?[:]")
if line.startswith('Tester ->'):
    m = pattern.match(line)
    if m is not None:
        data.append(m.group(1).strip())
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python - appended character gets lost

Body:
Hey I´m quite new to python and i´m writing a script to sort through a file in for some keywords, and everything works fine except a small reading/printing miss that i don´t understand... This is my problem code and the file im scanning through:

File:
    SEND TEST
    Tester -> 1FFF 19 02 0F :\user\log
    SEND TEST
    Tester -> 1FFF 18 00 0F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 12 11 5F :\user\log
    SEND TEST
    Tester -> 1FFF 12 55 1F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 19 03 2F :\user\log
code:
      if line.startswith('Tester ->'):
         start = 'Tester -> '  # take string from
         end = ':\ ' # end at
         data.append(line[line.find(start) + 9 :line.find(end)].strip('[Channel 1]'))

this prints

1FFF 19 02 0F
1FFF 18 00 0F [Channel 1]
1FFF 12 11 5F
1FFF 12 55 1F [Channel 1]
1FFF 19 03 2F

The data.append string has the problem, as shown in the print i works, but i want to extract the code ex 1FFF 12 55 1F but not [Channel 1] aslo... so i used .strip to remove it, but then i get this print:

1FFF 19 02 0F
FFF 18 00 0F
1FFF 12 11 5F
FFF 12 55 1F
1FFF 19 03 2F

All strings that has [Channel 1] loses the first character and if i put a 8 instead of a 9 in data.apped it prints:

1FFF 19 02 0F
> 1FFF 18 00 0F
1FFF 12 11 5F
> 1FFF 12 55 1F
1FFF 19 03 2F

Then it takes the > from the Tester -> and I don´t understand why? it skips the character in between for some reason? It´s like when I have a 9 it counts every character including spaces and when I have a 8 it counts characters but not including spaces... how is that possible? someone who knows how to fix this, thanks!

# Sending Request: Tester -> 1631 11 33 F5 :\ APP_3130 \ Read Identifier \
Tester -> 1631 22 F1 2E :\ APP_3138 \ Read Identifier \
Tester -> 1FFF 19 02 0F [Channel 1]

Body:
The problem is that strip('chars') removes all combinations of 'chars' as noted here: https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip

So what you're really saying is remove the characters [, C, h, a, , n, e, l, 1, and ] from my string.

If you just want to remove [Channel 1] I would do the following:

import re

line = re.sub(r"\[Channel 1\]$", "", line)

This regex pattern will only match the text [Channel 1] if it is as the end of the line.

or alternatively if you don't want to include the regex module you could use

line = line.replace("[Channel 1]", "")

This solution will replace [Channel 1] regardless of where it shows up in the line.

=================

The best solution here is to use regex and skip the entire start and end thing. You can do the following:

import re

pattern = re.compile(r"Tester ->\s((?:(?:\w+)+\s)+)(?:\[Channel \d\])?\s?[:]")
if line.startswith('Tester ->'):
    m = pattern.match(line)
    if m is not None:
        data.append(m.group(1).strip())


问:
With regards to urllib AttributeError: 'module' object has no attribute 'urlopen'
```<code>import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()
</code>```

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

```<code>import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()
</code>```

答:
it appears that the urlopen method is available in the urllib.request module and not in the urllib module as you're expecting.

rule of thumb - if you're getting an AttributeError, that field/operation is not present in the particular module.

EDIT - Thanks to AndiDog for pointing out - this is a solution valid for Py 3.x, and not applicable to Py2.x!

ContentLicense: CC BY-SA 2.5

Body:
import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[$][0-9][0-9][0-9][.][0-9][0-9][

]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()


问:
Ionicframework photo editor
I am trying to add a photo editor functionality to my ionic framework application. How ever I couldn't find a decent sdk that goes with it. I'd like add
aviary/creative
 sdk but there is not an obvious way to do it. I tried angular-aviary plugin for cordova but that is not working anymore. Please help me find a good photo editor sdk that works with cordova/ionic framework. Any help would be appreciated, thanks...

答:
Have a look at the PhotoEditor SDK Cordova Plugin Demo and the guide for integrating the editor under Ionic and Cordova to get an idea of how to get the editor working under Ionic. Basically, it works like this:

The idea is to create a Cordova app that allows the user to open an image from their photo library and edit this image using the PhotoEditor SDK on iOS and Android. This is done by using an existing library to access native photo pickers on both platforms and passing the path to the found image to a plugin. The plugin manages the configuration and opening of the PhotoEditor SDK’s editor and passes the edited image back to Cordova.

Title: Ionicframework photo editor


问:
How to install certain node version from command line
I want to install node 6.9.4.

In windows console I try with this:

```<code>npm install node@v6.9.4
</code>```

And it throws this error:

```<code>npm ERR! No compatible version found: node@v6.9.4
npm ERR! Valid install targets:
npm ERR! 0.0.0
</code>```

In linux the result is similar. I try with

```<code>sudo npm install node@v6.9.4
</code>```

and the output is:

```<code>npm ERR! version not found: node@6.9.4-cls
</code>```

Is there a way to install certain node version with npm?

答:
You should use nvm to install and manage node versions and not npm

NPM is the package manager for node and not a version manager.

To install a particular version of node using nvm, just do

nvm install v0.10.32

NPM should be used to install packages/modules.
So say you need to use request module for a particular project
You can do

npm install request

Both these support tons of options which could be found over the documentations

Body:
I want to install node 6.9.4.

In windows console I try with this:

npm install node@v6.9.4

And it throws this error:

npm ERR! No compatible version found: node@v6.9.4
npm ERR! Valid install targets:
npm ERR! 0.0.0

In linux the result is similar. I try with

sudo npm install node@v6.9.4

and the output is:

npm ERR! version not found: node@6.9.4-cls

Is there a way to install certain node version with npm?


问:
Why I don't see all items in Kentico Administration applications?
I don't see all application in Kentico. Please help me.
Currently I am Global System Administrator. This is my new website.

Current situation with applications looks like this:

Can someone help me ?
Thanks in Advance.

答:
I had the similar problem when I created my first site. All license, user and domain were rightly setup. I even checked all the settings for pages module which looked right. The only noticeable thing was that the site was not showing on top ribon as shown in solution 3.

I just did a log off and log on which resolved the issue. :)

Thanks a lot Brenden for directing towards solution.


问:
Browser-Sync does not Sync HTML and CSS files at once
I have a HTML file named index.html and a CSS file named style.cssin a directory named CSS3 for everybody like so.

C:\Users\a\Desktop\Web-Design for everybody specialization\CSS3 for everybody

I am trying to make Browser-Sync recognize that there is a .html and a .css file by running browser-sync start --server 'CSS3 for everybody' --files 'CSS3 for everybody' but nothing happens. It says "Connected to Browser Sync" and the page remains the same.

答:
in the index.html file u should specify to load the style.css file using the import rule like so </p>

```<code><style media="screen" type="text/css">
@import "style.css";
</style>
</code>```

Body:
in the index.html file u should specify to load the style.css file using the import rule like so

<style media="screen" type="text/css">
@import "style.css";
</style>


问:
Two-key encryption/decryption?
I'm looking to store some fairly sensitive data using PHP and MySQL and will be using some form of reversible encryption to do so since I need to get the data back out in plain text for it to be of any use.

I'll be deriving the encryption key from the users' username/password combination but I'm stumped for what to do in the (inevitable) event of a password being forgotten. I realise that the purpose of encryption is that it can only be undone using the correct key but this must have been addressed before..

I'm trying to get my head around whether or not public key cryptography would apply to the problem but all I can think of is that the private key will still need to be correct to decrypt the data..

Any ideas?

答:
Generate a random session key.

Use the session key to encrypt the data.

Encrypt the random key with any number of user passwords that you need.

This way you can use any user password to decrypt the data.

Title: Two-key encryption/decryption?


问:
Ionic 3 block backbutton Event
I would like to intercept the back button event.
As soon as the listener is called, the back signal is already triggered.

This is what i tried:

```<code> document.addEventListener("backbutton", () => {
       console.log("[WARN] BackBtn pushed");
       console.log("TextboxVal: " + this.inputValue);
       this.showConfirm();
       document.removeEventListener("backbutton");
     });
</code>```

I dont want to lose the "this.inputValue" value.
But in the most cases its gone already.

答:
Thats how i done it by myself:

```<code>constructor(public plt: Platform) {
    //Catch BackBTN Event
        plt.ready().then( ()=> {
          plt.registerBackButtonAction( ()=> {
            this.showConfirm();
          })
        });
}

showConfirm() {
      let confirm = this.alertCtrl.create({
        title: this.confirm,
        message: this.confirm_msg,
        buttons: [
          {
            text: this.disagree,
            handler: () => {
              console.log("Saved changes");
              this.dismiss();
            }
          },
          {
            text: this.agree,
            handler: () => {
              console.log("Discard changes");
              this.viewCtrl.dismiss();
            }
          }
        ]
      });
      confirm.present();
    }
  }
</code>```

With this i can set my own custom BackBTN method.

Title: Ionic 3 block backbutton Event

Body:
I would like to intercept the back button event.
As soon as the listener is called, the back signal is already triggered.

This is what i tried:

 document.addEventListener("backbutton", () => {
       console.log("[WARN] BackBtn pushed");
       console.log("TextboxVal: " + this.inputValue);
       this.showConfirm();
       document.removeEventListener("backbutton");
     });

I dont want to lose the "this.inputValue" value.
But in the most cases its gone already.

Body:
Thats how i done it by myself:

constructor(public plt: Platform) {
    //Catch BackBTN Event
        plt.ready().then( ()=> {
          plt.registerBackButtonAction( ()=> {
            this.showConfirm();
          })
        });
}

showConfirm() {
      let confirm = this.alertCtrl.create({
        title: this.confirm,
        message: this.confirm_msg,
        buttons: [
          {
            text: this.disagree,
            handler: () => {
              console.log("Saved changes");
              this.dismiss();
            }
          },
          {
            text: this.agree,
            handler: () => {
              console.log("Discard changes");
              this.viewCtrl.dismiss();
            }
          }
        ]
      });
      confirm.present();
    }
  }

With this i can set my own custom BackBTN method.


问:
Get is working but post is not working in spring boot
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

```<code><form id="forgotpassForm" action="anonymous/forgot_password"
method="post">
</code>```

Here is the error:

```<code>17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported
</code>```

Thanks is advance for your responses.

答:
Have you added an handler for POST?</p>

```<code>@RequestMapping(method = RequestMethod.POST)
</code>```

Body:
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

<form id="forgotpassForm" action="anonymous/forgot_password"
method="post">

Here is the error:

17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported

Thanks is advance for your responses.

Body:
Have you added an handler for POST?

@RequestMapping(method = RequestMethod.POST)


问:
ionic 2 storage does not work properly
I am using ionic 2 with storage.

I developed an E-commerce app.

If any product adds to cart I will store the product using storage.

Here is my function

```<code>//Add to cart

   addItemToCarts(item)
   {

      this.items.push(item);
      this.storage.set('products',this.items);

   }
</code>```

It's work and also I display the badge count Which means products   length.

Get storage(products) length .Here is my code

```<code>//Get cart Count

    this.storage.get('products').then((data) => {
     if(data != null)
     {
       this.badge='';
       this.badge=data.length;
       this.Cartproducts=data;
       console.log("data");
       console.log(data);
     }
    });
</code>```

If I remove any product in the cart.Using this code and again set to Storage.

Here is my code

```<code>cancel(i)
  {
    console.log(i);
    this.Cartproducts.splice(i, 1);
    var item=this.Cartproducts;
    this.length=this.Cartproducts.length;
    console.log(this.Cartproducts);
    this.storage.remove('products');
    this.storage.set('products',item);
  }
</code>```

Example My cart page products length is 3.If I remove any one product and the length is 2.and badge count also 2.

If again I add any one product.The storage products length is 4 why?.

But actually, the Storage products length is 3.Is right?

I don't have any idea.

Kindly advice me,

Thanks.

答:
I think addItemToCarts has some problem. You are pushing data in this.items in addItemToCarts function and you are removing item from Cartproducts array in Cancel function and storing. Ideally your function 'addItemToCarts' should look like below.

```<code>//Add to cart
addItemToCarts(item)
{
  this.Cartproducts.push(item);
  this.storage.set('products',this.Cartproducts);
}
</code>```

Title: ionic 2 storage does not work properly

Body:
I am using ionic 2 with storage.

I developed an E-commerce app.

If any product adds to cart I will store the product using storage.

Here is my function

//Add to cart

   addItemToCarts(item)
   {

      this.items.push(item);
      this.storage.set('products',this.items);

   }

It's work and also I display the badge count Which means products   length.

Get storage(products) length .Here is my code

//Get cart Count

    this.storage.get('products').then((data) => {
     if(data != null)
     {
       this.badge='';
       this.badge=data.length;
       this.Cartproducts=data;
       console.log("data");
       console.log(data);
     }
    });

If I remove any product in the cart.Using this code and again set to Storage.

Here is my code

cancel(i)
  {
    console.log(i);
    this.Cartproducts.splice(i, 1);
    var item=this.Cartproducts;
    this.length=this.Cartproducts.length;
    console.log(this.Cartproducts);
    this.storage.remove('products');
    this.storage.set('products',item);
  }

Example My cart page products length is 3.If I remove any one product and the length is 2.and badge count also 2.

If again I add any one product.The storage products length is 4 why?.

But actually, the Storage products length is 3.Is right?

I don't have any idea.

Kindly advice me,

Thanks.

Body:
I think addItemToCarts has some problem. You are pushing data in this.items in addItemToCarts function and you are removing item from Cartproducts array in Cancel function and storing. Ideally your function 'addItemToCarts' should look like below.

//Add to cart
addItemToCarts(item)
{
  this.Cartproducts.push(item);
  this.storage.set('products',this.Cartproducts);
}


问:
PHPUnit Class unable to find itself
New to PHPUnit and testing and have been following Teamtree House's Guide on it. But I'm stuck at this point and wonder if anyone can help. Here are the details from my files:

phpunit.xml --- in root

```<code><phpunit backupGlobals="true" bootstrap="tests/bootstrap.php">
  <!-- Blacklist the vendor folder -->
  <filter>
    <blacklist>
      <directory>vendor</directory>
    </blacklist>
  </filter>
  <!-- Add the main testsuite -->
  <testsuite>
    <directory>tests</directory>
  </testsuite>
</phpunit>
</code>```

bootstrap.php --- in ./tests/bootstrap.php

```<code><?php
// Get autoloader
require './vendor/autoload.php';

// Get tests
require './tests/PigLatinTest.php';

// Initialise twig
$loader = new Twig_Loader_Filesystem('./src');
$twig = new Twig_Environment($loader);
</code>```

PigLatinTest.php --- in ./tests/PigLatinTest.php

```<code><?php
require 'vendor/autoload.php';
require 'src/PigLatin.php';

class PigLatinTest extends PHPUnit\Framework\TestCase
{
  /**
   * @test PigLatin
   */
  public function englishToPigLatinWorksCorrectly()
  {
    /**
     * Given I have an english word
     * If I pass that word to my PigLatin converter
     * I get back the correctly transformed version
     */
     $word = 'test';
     $expectedResult = 'esttay';

     $pigLatin = new PigLatin();
     $result = $pigLatin->convert($word);

     $this->assertEquals(
        $expectedResult,
        $result,
        "PigLatin conversion did not work correctly"
     );
  }
}
</code>```

PigLatin.php --- in ./src/PigLatin.php

```<code><?php

class PigLatin
{
  public function convert($word)
  {
    // Remove first letter of the word
    $first_letter = substr($word, 0, 1);
    $new_word = substr($word, 1, strlen($word) - 1);
    $new_word .= $first_letter . 'ay';

    return $new_word;
  }
}
</code>```

When I run the command phpunit in my terminal I get the following output:

```<code>PHPUnit 6.2.3 by Sebastian Bergmann and contributors.

Time: 68 ms, Memory: 10.00MB

No tests executed!
</code>```

But when I run phpunit PigLatinTest.php I get the following error:

```<code>PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'PigLatinTest' could not be found in 'PigLatinTest.php'. in phar:///usr/local/bin/phpunit/phpunit/Runner/StandardTestSuiteLoader.php:101
</code>```

This is really confusing me, and I can't find a solution on SO at all. If anyone has some insight that would be appreciated!

答:
Your issue is with all the includes. They are trying to include the wrong files.

tests/bootstrap.php

```<code><?php
// Let's use absolute paths instead with the help of __DIR__ which
// will give us the path to the current folder.
require __DIR__ . '/../vendor/autoload.php'; // Up one folder where the vendor is

// Removed the include for PigLatinTest since PHPUnit will handle that.

// Again, let's use __DIR__ to solve the path issues.
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../src');

$twig = new Twig_Environment($loader);

// If your PigLatin-class isn't loaded with autoloading (in your composer.json),
// let's include it in here. Again, with the help of __DIR__
require __DIR__ . '/../src/PigLatin.php';
</code>```

tests/PigLatinTest.php

In your test class, we can remove all include's. The bootstrap have already taken care of that.

Conclusion

It's important to remember that if you include/require a file that includes/requires other files, all relative paths will be relative from the file that does the including, not the file itself. The best way is to do: require __DIR__ . '/relative/from/this/file.php. The magic constant __DIR__ gives you the absolute path from the file it's written in.

Once you have included a file into your project once, all classes and functions in it it will be accessible in the rest of the request. No need to include it more than once.

Title: PHPUnit Class unable to find itself

Body:
New to PHPUnit and testing and have been following Teamtree House's Guide on it. But I'm stuck at this point and wonder if anyone can help. Here are the details from my files:

phpunit.xml --- in root

<phpunit backupGlobals="true" bootstrap="tests/bootstrap.php">

  <filter>
    <blacklist>
      <directory>vendor</directory>
    </blacklist>
  </filter>

  <testsuite>
    <directory>tests</directory>
  </testsuite>
</phpunit>

bootstrap.php --- in ./tests/bootstrap.php

<?php
// Get autoloader
require './vendor/autoload.php';

// Get tests
require './tests/PigLatinTest.php';

// Initialise twig
$loader = new Twig_Loader_Filesystem('./src');
$twig = new Twig_Environment($loader);

PigLatinTest.php --- in ./tests/PigLatinTest.php

<?php
require 'vendor/autoload.php';
require 'src/PigLatin.php';

class PigLatinTest extends PHPUnit\Framework\TestCase
{
  /**
   * @test PigLatin
   */
  public function englishToPigLatinWorksCorrectly()
  {
    /**
     * Given I have an english word
     * If I pass that word to my PigLatin converter
     * I get back the correctly transformed version
     */
     $word = 'test';
     $expectedResult = 'esttay';

     $pigLatin = new PigLatin();
     $result = $pigLatin->convert($word);

     $this->assertEquals(
        $expectedResult,
        $result,
        "PigLatin conversion did not work correctly"
     );
  }
}

PigLatin.php --- in ./src/PigLatin.php

<?php

class PigLatin
{
  public function convert($word)
  {
    // Remove first letter of the word
    $first_letter = substr($word, 0, 1);
    $new_word = substr($word, 1, strlen($word) - 1);
    $new_word .= $first_letter . 'ay';

    return $new_word;
  }
}

When I run the command phpunit in my terminal I get the following output:

PHPUnit 6.2.3 by Sebastian Bergmann and contributors.

Time: 68 ms, Memory: 10.00MB

No tests executed!

But when I run phpunit PigLatinTest.php I get the following error:

PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'PigLatinTest' could not be found in 'PigLatinTest.php'. in phar:///usr/local/bin/phpunit/phpunit/Runner/StandardTestSuiteLoader.php:101

This is really confusing me, and I can't find a solution on SO at all. If anyone has some insight that would be appreciated!

Body:
Your issue is with all the includes. They are trying to include the wrong files.

tests/bootstrap.php

<?php
// Let's use absolute paths instead with the help of __DIR__ which
// will give us the path to the current folder.
require __DIR__ . '/../vendor/autoload.php'; // Up one folder where the vendor is

// Removed the include for PigLatinTest since PHPUnit will handle that.

// Again, let's use __DIR__ to solve the path issues.
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../src');

$twig = new Twig_Environment($loader);

// If your PigLatin-class isn't loaded with autoloading (in your composer.json),
// let's include it in here. Again, with the help of __DIR__
require __DIR__ . '/../src/PigLatin.php';

tests/PigLatinTest.php

In your test class, we can remove all include's. The bootstrap have already taken care of that.

Conclusion

It's important to remember that if you include/require a file that includes/requires other files, all relative paths will be relative from the file that does the including, not the file itself. The best way is to do: require __DIR__ . '/relative/from/this/file.php. The magic constant __DIR__ gives you the absolute path from the file it's written in.

Once you have included a file into your project once, all classes and functions in it it will be accessible in the rest of the request. No need to include it more than once.

ContentLicense: CC BY-SA 4.0


问:
How to set a static property on a class in Kotlin for Javascript
I have a situation where I need to define a static property on a class in Kotlin and when its compiled to Javascript have it become a true static field on that class. In this situation companion objects do not work.

For example, if I have an abstract class and its implementing class like below:

```<code>abstract class MyAbstractClass{
  abstract val id: Int
}

class MyClass: MyAbstractClass(){
  override val id: Int = 1 //I want this to actually be "static" on the MyClass
}
</code>```

The Javascript that this compiles down to is this:

```<code>function MyAbstractClass() {
}

function MyClass() {
  MyAbstractClass.call(this);
  this.id_jz5fma$_0 = 1;
}

Object.defineProperty(MyClass.prototype, 'id', {
  get: function () {
    return this.id_jz5fma$_0;
  }
});
</code>```

But what I need it to compile down to is this:

```<code>function MyAbstractClass() {
}

function MyClass() {
  MyAbstractClass.call(this);
}

MyClass.id = 1;
</code>```

So that the id field does actually statically exist on MyClass without having to make a new instance of MyClass.

I've tried using a companion object but that creates a separate object/function called MyClass$Companion and then assigns the id field to that and never actually assigns it statically to MyClass.

How can I go about setting true static fields like this in Kotlin?

答:
Right now we don’t have a direct way to do it, so I’ve created issue https://youtrack.jetbrains.com/issue/KT-18891

As a workaround, you can write a function like that:

```<code>inline fun <reified T : Any> addStaticMembersTo(source: Any) {
    val c = T::class.js.asDynamic()
    val ownNames = js("Object").getOwnPropertyNames(source) as Array<String>
    val protoNames = js("Object").getOwnPropertyNames(source.asDynamic().constructor.prototype) as Array<String>

    for (name in ownNames + protoNames) {
        c[name] = source.asDynamic()[name]
    }
}
</code>```

And use like:

```<code>class A {
    companion object {
        init {
            addStaticMembersTo<A>(object {
                val bar = 1
                fun foo() {}
            })
        }
    }
}
</code>```

or even make companion object's members available as a static member of class:

```<code>class B {
    companion object {
        val bar = 1
        fun foo() {}

        // should be at the end of companion object
        init {
            addStaticMembersTo<B>(this)
        }
    }
}
</code>```

The full example available here:
https://try.kotl.in/#/UserProjects/uube1qikg3vsegtnefo0ad0jag/30f1qf87dt5k5vjhciirt4t108

Body:
I have a situation where I need to define a static property on a class in Kotlin and when its compiled to Javascript have it become a true static field on that class. In this situation companion objects do not work.

For example, if I have an abstract class and its implementing class like below:

abstract class MyAbstractClass{
  abstract val id: Int
}

class MyClass: MyAbstractClass(){
  override val id: Int = 1 //I want this to actually be "static" on the MyClass
}

The Javascript that this compiles down to is this:

function MyAbstractClass() {
}

function MyClass() {
  MyAbstractClass.call(this);
  this.id_jz5fma$_0 = 1;
}

Object.defineProperty(MyClass.prototype, 'id', {
  get: function () {
    return this.id_jz5fma$_0;
  }
});

But what I need it to compile down to is this:

function MyAbstractClass() {
}

function MyClass() {
  MyAbstractClass.call(this);
}

MyClass.id = 1;

So that the id field does actually statically exist on MyClass without having to make a new instance of MyClass.

I've tried using a companion object but that creates a separate object/function called MyClass$Companion and then assigns the id field to that and never actually assigns it statically to MyClass.

How can I go about setting true static fields like this in Kotlin?

Body:
Right now we don’t have a direct way to do it, so I’ve created issue https://youtrack.jetbrains.com/issue/KT-18891

As a workaround, you can write a function like that:

inline fun <reified T : Any> addStaticMembersTo(source: Any) {
    val c = T::class.js.asDynamic()
    val ownNames = js("Object").getOwnPropertyNames(source) as Array<String>
    val protoNames = js("Object").getOwnPropertyNames(source.asDynamic().constructor.prototype) as Array<String>

    for (name in ownNames + protoNames) {
        c[name] = source.asDynamic()[name]
    }
}

And use like:

class A {
    companion object {
        init {
            addStaticMembersTo<A>(object {
                val bar = 1
                fun foo() {}
            })
        }
    }
}

or even make companion object's members available as a static member of class:

class B {
    companion object {
        val bar = 1
        fun foo() {}

        // should be at the end of companion object
        init {
            addStaticMembersTo<B>(this)
        }
    }
}

The full example available here:
https://try.kotl.in/#/UserProjects/uube1qikg3vsegtnefo0ad0jag/30f1qf87dt5k5vjhciirt4t108


问:
How many address fields would you use for a UK database?
Address records are probably used in most database, but I've seen a number of slightly different sets of fields used to store them. The number of fields seems to vary from 3-7, and sometimes all fields are simple labelled address1..addressN, other times given specific meaning (town, city, etc).

This is UK specific, though I'm open to comments about the rest of the world too. Here you need the first line of the address (actually just the number) and the post code to identify the address - everything else is mostly an added bonus.

I'm currently favouring:

Address 1

Address 2

Address 3

Town

County

Post Code

We could add Country if we ever needed it (unlikely).

What do you think? Is this too little, too much?

答:
Premises elements

Sub Building Name

Building Name

Building Number

Organisation Name

Department Name

PO Box Number

Thoroughfare elements

Dependent Thoroughfare Name

Dependent Thoroughfare Descriptor

Thoroughfare Name

Thoroughfare Descriptor

Locality elements

Double Dependent Locality

Dependent Locality

Post Town

Postcode element

Postcode

This answer may be a few years late, but it's aimed at those like myself looking for guidance on how to correctly format postal addresses for both storing in a database (or the likes of it) and for printing purposes.

Taken from Royal Mail Doc, link below - conveniently titled the 'Programmers Guide'

Technical specififcation for users of PAF

Page 27 - 42 was most helpful for me.

OwnerDisplayName: Draemon

LastEditorDisplayName: Jonathan Leffler


问:
spawn ls ENOENT when watched file is modified
I am learning Node.js via the book Node.js the Right Way. I am trying to run the following example to watch changes to a file called target.txt that resides in the the same directory as the .js file.

```<code>"use strict";
const
    fs = require('fs'),
    spawn = require('child_process').spawn,
    filename = process.argv[2];
if (!filename) {
    throw Error("A file to watch must be specified!");
}
fs.watch(filename, function () {
    let ls = spawn('ls', ['-lh', filename]);
    ls.stdout.pipe(process.stdout);
});
console.log("Now watching " + filename + " for changes...");
</code>```

I get the following error when I change the text file and save it:

events.js:160
        throw er; // Unhandled 'error' event
        ^

Error: spawn ls ENOENT
      at exports._errnoException (util.js:1018:11)
      at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
      at onErrorNT (internal/child_process.js:367:16)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

Node.js version: v6.11.0

IDE: Visual Studio Code 1.13.1

OS: Windows 10 64x

答:
There's no ls on Windows, you should use dir instead.

However, that's not an executable. To run .bat and .cmd files you can:

Spawn cmd.exe and pass those files as arguments:

```<code>require('child_process').spawn('cmd', ['/c', 'dir']);
</code>```

Use spawn with the shell option set to true:

```<code>require('child_process').spawn('dir', [], { shell: true });
</code>```

Use exec instead of spawn:

```<code>require('child_process').exec('dir', (err, stdout, stderr) => { ... });
</code>```

For more on that, take a look at this section in the official docs.

EDIT:

I'm not sure I understood you question in the comment correctly, but if you go for the second option, for example, you code will look like this:

```<code>...

fs.watch(filename, function () {
    let dir = spawn('dir', [filename], { shell: true });

    dir.stdout.pipe(process.stdout);
});

...
</code>```

Please, keep in mind you may need to adjust this code slightly. I'm writing all this from memory as I don't have access to a Windows machine right now, so I can't test it myself.

Body:
I am learning Node.js via the book Node.js the Right Way. I am trying to run the following example to watch changes to a file called target.txt that resides in the the same directory as the .js file.

"use strict";
const
    fs = require('fs'),
    spawn = require('child_process').spawn,
    filename = process.argv[2];
if (!filename) {
    throw Error("A file to watch must be specified!");
}
fs.watch(filename, function () {
    let ls = spawn('ls', ['-lh', filename]);
    ls.stdout.pipe(process.stdout);
});
console.log("Now watching " + filename + " for changes...");

I get the following error when I change the text file and save it:

events.js:160
        throw er; // Unhandled 'error' event
        ^

Error: spawn ls ENOENT
      at exports._errnoException (util.js:1018:11)
      at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
      at onErrorNT (internal/child_process.js:367:16)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

Node.js version: v6.11.0

IDE: Visual Studio Code 1.13.1

OS: Windows 10 64x

Body:
There's no ls on Windows, you should use dir instead.

However, that's not an executable. To run .bat and .cmd files you can:

Spawn cmd.exe and pass those files as arguments:

require('child_process').spawn('cmd', ['/c', 'dir']);

Use spawn with the shell option set to true:

require('child_process').spawn('dir', [], { shell: true });

Use exec instead of spawn:

require('child_process').exec('dir', (err, stdout, stderr) => { ... });

For more on that, take a look at this section in the official docs.

EDIT:

I'm not sure I understood you question in the comment correctly, but if you go for the second option, for example, you code will look like this:

...

fs.watch(filename, function () {
    let dir = spawn('dir', [filename], { shell: true });

    dir.stdout.pipe(process.stdout);
});

...

Please, keep in mind you may need to adjust this code slightly. I'm writing all this from memory as I don't have access to a Windows machine right now, so I can't test it myself.


问:
Encoding Javascript in separate file
I have this script in my view:

```<code>@if(ViewBag.UserName != null)
{
    <script type="text/javascript">
        $(function(){
            var msg = 'Welcome, @Encoder.JavaScriptEncode(ViewBag.UserName, false)!';
            $("#welcome-message").html(msg).hide().show('slow');
        })
    </script>
}
</code>```

However, I want to put the Javascript in a separate file, but when I do that the Html Helper "Encoder" won't work obviously, how would I do a work around so that I still have the Encoder but with the Js in the separate file?

答:
Either:

Generate the JavaScript from ASP.NET (making sure you output the right Content-Type response header!) or

Output the data somewhere into the DOM (e.g. a <meta> element or a data-* attribute) and then read it with the JS

Title: Encoding Javascript in separate file

Body:
I have this script in my view:

@if(ViewBag.UserName != null)
{

}

However, I want to put the Javascript in a separate file, but when I do that the Html Helper "Encoder" won't work obviously, how would I do a work around so that I still have the Encoder but with the Js in the separate file?


问:
How can I call two methods simultaneously using `&`
Instead of calling one method in a block using &,

```<code>objects_array.collect(&:errors)
</code>```

can I call two methods simultaneously using &? I want something like this:

```<code>objects_array.collect(&:errors.full_messages)
</code>```

Is it possible?

答: It is possible if you redefine Symbol#method_missing to store the method chain, and also redefine Symbol#to_proc to expand into a proc using the stored method chain. But I am pretty sure that it would introduce complexity more than it helps, and cause some severe problems. It is not worth doing.

Body:
Instead of calling one method in a block using &,

objects_array.collect(&:errors)

can I call two methods simultaneously using &? I want something like this:

objects_array.collect(&:errors.full_messages)

Is it possible?


问:
How to calculate time difference between two dates using LocalDateTime in Java 8?
There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something .

Do we have any method which achieve the same in LocalDateTime in Java-8?

I have tried to use following but unable to achieve the same.

```<code>LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55);
LocalDateTime toDateTime = LocalDateTime.now();
LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);

long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears(years);

long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths(months);

long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays(days);

long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours(hours);

long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes(minutes);

long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);

System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours());

System.out.println(years + " years "
        + months + " months "
        + days + " days "
        + hours + " hours "
        + minutes + " minutes "
        + seconds + " seconds.");
</code>```

It is difficult to check on time and date separately.

Initially I coded it like but it does not looks correct:

```<code>return openBrat!=null
        && openBrat.until(LocalDateTime.now(), ChronoUnit.DAYS) == 0 &&
          openBrat.until(LocalDateTime.now(), ChronoUnit.HOURS) >= 8
         && openBrat.until(LocalDateTime.now(), ChronoUnit.Minutes) >= 0;
</code>```

Could anyone please suggest how to subtract like:

```<code>2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours.
</code>```

答:
My understanding is that you want to get the difference between those 2 dates and "break" it in terms of how many hours, minutes and seconds this difference is.

You can use the Duration class as already explained. But the Duration calculates the difference in seconds and nanoseconds, so you'll have to do some math to get this amount of seconds in separate fields:

```<code>LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55);

Duration duration = Duration.between(d1, d2);
// total seconds of difference (using Math.abs to avoid negative values)
long seconds = Math.abs(duration.getSeconds());
long hours = seconds / 3600;
seconds -= (hours * 3600);
long minutes = seconds / 60;
seconds -= (minutes * 60);
System.out.println(hours + " hours " + minutes + " minutes " + seconds + " seconds");
</code>```

In Java 9 and later, you can call the new Duration::to…Part methods to get number of days, hours, minutes, or seconds rather than calculate the numbers yourself.

The output will be:

7 hours 30 minutes 55 seconds

And the variables hours, minutes and seconds will have the respective values of 7, 30 and 55. If you also want the nanoseconds, just call duration.getNano() to get the respective value (in the example above, it's 0).

If I test with different values:

```<code>LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0);
</code>```

The result will be:

2 hours 0 minutes 0 seconds

If you just want the difference in hours, you can use:

```<code>ChronoUnit.HOURS.between(d1, d2);
</code>```

You can optionally use Math.abs to avoid negative values.

This will return the difference in hours, ignoring the remaining minutes and seconds: in the first example (d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55)) it will return 7 and in the second example (d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0)) it will return 2.

Body:
There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something .

Do we have any method which achieve the same in LocalDateTime in Java-8?

I have tried to use following but unable to achieve the same.

LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55);
LocalDateTime toDateTime = LocalDateTime.now();
LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);

long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears(years);

long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths(months);

long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays(days);

long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours(hours);

long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes(minutes);

long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);

System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours());

System.out.println(years + " years "
        + months + " months "
        + days + " days "
        + hours + " hours "
        + minutes + " minutes "
        + seconds + " seconds.");

It is difficult to check on time and date separately.

Initially I coded it like but it does not looks correct:

return openBrat!=null
        && openBrat.until(LocalDateTime.now(), ChronoUnit.DAYS) == 0 &&
          openBrat.until(LocalDateTime.now(), ChronoUnit.HOURS) >= 8
         && openBrat.until(LocalDateTime.now(), ChronoUnit.Minutes) >= 0;

Could anyone please suggest how to subtract like:

2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours.

Body:
My understanding is that you want to get the difference between those 2 dates and "break" it in terms of how many hours, minutes and seconds this difference is.

You can use the Duration class as already explained. But the Duration calculates the difference in seconds and nanoseconds, so you'll have to do some math to get this amount of seconds in separate fields:

LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55);

Duration duration = Duration.between(d1, d2);
// total seconds of difference (using Math.abs to avoid negative values)
long seconds = Math.abs(duration.getSeconds());
long hours = seconds / 3600;
seconds -= (hours * 3600);
long minutes = seconds / 60;
seconds -= (minutes * 60);
System.out.println(hours + " hours " + minutes + " minutes " + seconds + " seconds");

In Java 9 and later, you can call the new Duration::to…Part methods to get number of days, hours, minutes, or seconds rather than calculate the numbers yourself.

The output will be:

7 hours 30 minutes 55 seconds

And the variables hours, minutes and seconds will have the respective values of 7, 30 and 55. If you also want the nanoseconds, just call duration.getNano() to get the respective value (in the example above, it's 0).

If I test with different values:

LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0);

The result will be:

2 hours 0 minutes 0 seconds

If you just want the difference in hours, you can use:

ChronoUnit.HOURS.between(d1, d2);

You can optionally use Math.abs to avoid negative values.

This will return the difference in hours, ignoring the remaining minutes and seconds: in the first example (d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55)) it will return 7 and in the second example (d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0)) it will return 2.


问:
When is the default cache stored off-heap in Apache Ignite 2.0
This configuration is not valid in 2.0 version

```<code><!-- Enable off-heap storage with unlimited size. -->
<property name="offHeapMaxMemory" value="0"/>
</code>```

Error:

```<code>    WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'grid.cfg' defined in URL [file:/home/ignite/sample-cache.xml]: Cannot create inner bean
 'org.apache.ignite.configuration.CacheConfiguration#4cc0edeb' of type  [org.apache.ignite.configuration.CacheConfiguration] while setting bean
  property 'cacheConfiguration' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with
  name 'org.apache.ignite.configuration.CacheConfiguration#4cc0edeb' defined in URL [file:/home/ignite/sample-cache.xml]: Error setting property
  values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'offHeapMaxMemory' of bean class
 [org.apache.ignite.configuration.CacheConfiguration]: Bean property 'offHeapMaxMemory' is not writable or has an invalid setter method. Does the
 parameter type of the setter match the return type of the getter?
</code>```

Visor SnapShot

```<code>Time of the snapshot: 07/07/17, 16:54:35
+===========================================================================================================================+
|    Name(@)    |    Mode     | Nodes |      Entries (Heap / Off-heap)      |   Hits    |  Misses   |   Reads   |  Writes   |
+===========================================================================================================================+
| txnCache(@c0) | PARTITIONED | 1     | min: 2917681 (2917681 / 0)          | min: 0    | min: 0    | min: 0    | min: 0    |
|               |             |       | avg: 2917681.00 (2917681.00 / 0.00) | avg: 0.00 | avg: 0.00 | avg: 0.00 | avg: 0.00 |
|               |             |       | max: 2917681 (2917681 / 0)          | max: 0    | max: 0    | max: 0    | max: 0    |
+---------------------------------------------------------------------------------------------------------------------------+

Cache 'txnCache(@c0)':
+--------------------------------------------------------------+
| Name(@)                     | txnCache(@c0)                  |
| Nodes                       | 1                              |
| Total size Min/Avg/Max      | 2917681 / 2917681.00 / 2917681 |
|   Heap size Min/Avg/Max     | 2917681 / 2917681.00 / 2917681 |
|   Off-heap size Min/Avg/Max | 0 / 0.00 / 0                   |
+--------------------------------------------------------------+

Nodes for: txnCache(@c0)
+============================================================================================================+
|     Node ID8(@), IP      | CPUs | Heap Used | CPU Load |   Up Time    |         Size         | Hi/Mi/Rd/Wr |
+============================================================================================================+
| 924C5A56(@n0), 10.0.2.55 | 2    | 8.93 %    | 93.83 %  | 00:12:31:969 | Total: 2917681       | Hi: 0       |
|                          |      |           |          |              |   Heap: 2917681      | Mi: 0       |
|                          |      |           |          |              |   Off-Heap: 0        | Rd: 0       |
|                          |      |           |          |              |   Off-Heap Memory: 0 | Wr: 0       |
+------------------------------------------------------------------------------------------------------------+
'Hi' - Number of cache hits.
'Mi' - Number of cache misses.
'Rd' - number of cache reads.
'Wr' - Number of cache writes.

Aggregated queries metrics:
  Minimum execution time: 00:00:00:000
  Maximum execution time: 00:00:00:000
  Average execution time: 00:00:00:000
  Total number of executions: 0
  Total number of failures:   0
</code>```

Visor snapshot shows Off-Heap/Off-Heap-Memory as 0. In Documentation, its mentioned as default off heap is enabled by default. Is there any threshold before storing off-heap? How can i configure that?

答:
There is no offHeapMaxMemory property in CacheConfiguration since 2.0.

Yes, since version 2.0 by default caches store data in off-heap.
You can check it with:

cache.size(CachePeekMode.OFFHEAP))

But also, visor not properly counts "off-heap entries count" metric, but this is already fixed and will be available in version 2.1

Body:
This configuration is not valid in 2.0 version

<property name="offHeapMaxMemory" value="0"/>

Error:

    WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'grid.cfg' defined in URL [file:/home/ignite/sample-cache.xml]: Cannot create inner bean
 'org.apache.ignite.configuration.CacheConfiguration#4cc0edeb' of type  [org.apache.ignite.configuration.CacheConfiguration] while setting bean
  property 'cacheConfiguration' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with
  name 'org.apache.ignite.configuration.CacheConfiguration#4cc0edeb' defined in URL [file:/home/ignite/sample-cache.xml]: Error setting property
  values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'offHeapMaxMemory' of bean class
 [org.apache.ignite.configuration.CacheConfiguration]: Bean property 'offHeapMaxMemory' is not writable or has an invalid setter method. Does the
 parameter type of the setter match the return type of the getter?

Visor SnapShot

Time of the snapshot: 07/07/17, 16:54:35
+===========================================================================================================================+
|    Name(@)    |    Mode     | Nodes |      Entries (Heap / Off-heap)      |   Hits    |  Misses   |   Reads   |  Writes   |
+===========================================================================================================================+
| txnCache(@c0) | PARTITIONED | 1     | min: 2917681 (2917681 / 0)          | min: 0    | min: 0    | min: 0    | min: 0    |
|               |             |       | avg: 2917681.00 (2917681.00 / 0.00) | avg: 0.00 | avg: 0.00 | avg: 0.00 | avg: 0.00 |
|               |             |       | max: 2917681 (2917681 / 0)          | max: 0    | max: 0    | max: 0    | max: 0    |
+---------------------------------------------------------------------------------------------------------------------------+

Cache 'txnCache(@c0)':
+--------------------------------------------------------------+
| Name(@)                     | txnCache(@c0)                  |
| Nodes                       | 1                              |
| Total size Min/Avg/Max      | 2917681 / 2917681.00 / 2917681 |
|   Heap size Min/Avg/Max     | 2917681 / 2917681.00 / 2917681 |
|   Off-heap size Min/Avg/Max | 0 / 0.00 / 0                   |
+--------------------------------------------------------------+

Nodes for: txnCache(@c0)
+============================================================================================================+
|     Node ID8(@), IP      | CPUs | Heap Used | CPU Load |   Up Time    |         Size         | Hi/Mi/Rd/Wr |
+============================================================================================================+
| 924C5A56(@n0), 10.0.2.55 | 2    | 8.93 %    | 93.83 %  | 00:12:31:969 | Total: 2917681       | Hi: 0       |
|                          |      |           |          |              |   Heap: 2917681      | Mi: 0       |
|                          |      |           |          |              |   Off-Heap: 0        | Rd: 0       |
|                          |      |           |          |              |   Off-Heap Memory: 0 | Wr: 0       |
+------------------------------------------------------------------------------------------------------------+
'Hi' - Number of cache hits.
'Mi' - Number of cache misses.
'Rd' - number of cache reads.
'Wr' - Number of cache writes.

Aggregated queries metrics:
  Minimum execution time: 00:00:00:000
  Maximum execution time: 00:00:00:000
  Average execution time: 00:00:00:000
  Total number of executions: 0
  Total number of failures:   0

Visor snapshot shows Off-Heap/Off-Heap-Memory as 0. In Documentation, its mentioned as default off heap is enabled by default. Is there any threshold before storing off-heap? How can i configure that?


问:
Node.JS & Mongoose - insert item into an array in the database
I am currently working on a project and I am stuck with inserting an item into an array/object in the database. What I am trying to do is to add the id of a 'upvoted' post to an array/list in the 'User' Collection, however, I cannot seem to get it to work.

The code for my schemas is as follows:

```<code>// this is a child scheme/sub-document
var uvpSchema = new Schema();
uvpSchema.add({
  post: String
});

var dvpSchema = new Schema();
dvpSchema.add({
  post: String
 });

//main schema
var userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    upVotedPosts: [uvpSchema],
    downVotedPosts: [dvpSchema],
    created_at: Date,
});
</code>```

And here is the code in my 'routes.js' to insert the id of the post into the array:

```<code>var newPush = {
        post: postID  // postID is a variable that I have already defined
    };
    User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
        if (err) console.log(err);
        user.upVotedPosts.push(newPush);
        User.save;
        res.redirect(req.get('referer'));
        console.log(user.upVotedPosts);
    });
</code>```

The error I receive in my terminal is:

```<code>{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b }
events.js:163
      throw er; // Unhandled 'error' event
      ^
</code>```

Thanks in advance ;-)

答:
Route.js

```<code>User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
    if (err) console.log(err);
    user.upVotedPosts.push(newPush);
    User.save;
    res.redirect(req.get('referer'));
    console.log(user.upVotedPosts);
});
</code>```

You dont need to explicitly push, since you pushed using findOneandUpdate - $push

Refer here

Secondly , its

```<code>user.save()
</code>```

and not

```<code>User.save
</code>```

Body:
I am currently working on a project and I am stuck with inserting an item into an array/object in the database. What I am trying to do is to add the id of a 'upvoted' post to an array/list in the 'User' Collection, however, I cannot seem to get it to work.

The code for my schemas is as follows:

// this is a child scheme/sub-document
var uvpSchema = new Schema();
uvpSchema.add({
  post: String
});

var dvpSchema = new Schema();
dvpSchema.add({
  post: String
 });

//main schema
var userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    upVotedPosts: [uvpSchema],
    downVotedPosts: [dvpSchema],
    created_at: Date,
});

And here is the code in my 'routes.js' to insert the id of the post into the array:

var newPush = {
        post: postID  // postID is a variable that I have already defined
    };
    User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
        if (err) console.log(err);
        user.upVotedPosts.push(newPush);
        User.save;
        res.redirect(req.get('referer'));
        console.log(user.upVotedPosts);
    });

The error I receive in my terminal is:

{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b }
events.js:163
      throw er; // Unhandled 'error' event
      ^

Thanks in advance ;-)

Body:
Route.js

User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
    if (err) console.log(err);
    user.upVotedPosts.push(newPush);
    User.save;
    res.redirect(req.get('referer'));
    console.log(user.upVotedPosts);
});

You dont need to explicitly push, since you pushed using findOneandUpdate - $push

Refer here

Secondly , its

user.save()

and not

User.save


问:
Audio and video streaming from web server
I have been working on the audio and video streaming, where I have to pick a file from remote server and then play it on iPhone but I am not getting the results. When I run the project the error generates saying it cannot play it.

I have also tried "iphoneStreamingPlayer" application available at link

http://projectswithlove.com/projects/iPhoneStreamingPlayer.zip

答: Unfortunately I didn't get any solution to this issue. One thing I got to know during searching is that Apple does not directly support it but there are a few private libraries that supports RTSP streaming but are not supported by Apple.</p>


问:
How can i test service with ngRedux
How can i mock getState of ngRedux: with karma jasmine

For example my service get value from store by ngRedux.

```<code>this.ngRedux.getState()
</code>```

答:
I solved the problem by spying on the getState() method:

```<code>spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({ ... });
</code>```

I have no idea if that's the way to do it, but it worked in my case. I don't need to mock any fancy state modifications, though, just one simple getState().

MockNgRedux is part of the @angular-redux/store module. Your test could look somewhat like this:

```<code>...
import {MockNgRedux, NgReduxTestingModule} from '@angular-redux/store/lib/testing';

describe('MyTest', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            ...
            imports: [
                ...
                NgReduxTestingModule
            ],
            providers: [
                ...
                MockNgRedux
            ]
        })
        .compileComponents();
    }));

    it('does something', () => {
        // set up
        spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({here: 'be my mock store'});
        spyOn(MockNgRedux.getInstance(), 'dispatch').and.stub();
        ....
        expect(MockNgRedux.getInstance().dispatch).toHaveBeenCalledWith(something);
    });
});
</code>```

Here's a link to the docs: https://angular-redux.github.io/store/classes/mockngredux.html

Title: How can i test service with ngRedux

Body:
How can i mock getState of ngRedux: with karma jasmine

For example my service get value from store by ngRedux.

this.ngRedux.getState()

Body:
I solved the problem by spying on the getState() method:

spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({ ... });

I have no idea if that's the way to do it, but it worked in my case. I don't need to mock any fancy state modifications, though, just one simple getState().

MockNgRedux is part of the @angular-redux/store module. Your test could look somewhat like this:

...
import {MockNgRedux, NgReduxTestingModule} from '@angular-redux/store/lib/testing';

describe('MyTest', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            ...
            imports: [
                ...
                NgReduxTestingModule
            ],
            providers: [
                ...
                MockNgRedux
            ]
        })
        .compileComponents();
    }));

    it('does something', () => {
        // set up
        spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({here: 'be my mock store'});
        spyOn(MockNgRedux.getInstance(), 'dispatch').and.stub();
        ....
        expect(MockNgRedux.getInstance().dispatch).toHaveBeenCalledWith(something);
    });
});

Here's a link to the docs: https://angular-redux.github.io/store/classes/mockngredux.html


问:
TransactionTooLargeException only on Nougat
I've go an app that works well on devices with Android versions lower than Nougat.

When I launch the app on a device with Nougat and I press home button, the app crashes and in logcat I have:

```<code>!!! FAILED BINDER TRANSACTION !!!  (parcel size = 1819712)
Unhandled exception
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:615)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3636)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3773)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Is there a simple solution? This problem appears only on Nougat.

答: I resolved this problem by saving data in file. Thank you for all your answers.</p>

Body:
I've go an app that works well on devices with Android versions lower than Nougat.

When I launch the app on a device with Nougat and I press home button, the app crashes and in logcat I have:

!!! FAILED BINDER TRANSACTION !!!  (parcel size = 1819712)
Unhandled exception
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:615)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3636)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3773)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Is there a simple solution? This problem appears only on Nougat.