问:
Npm Please try using this command again as root/administrator
I've been desperately trying to install modules using node.js but it always fails getting packages with npm.

I logged in as Administrator and used powershell/cmd with "run as administrator". I also had problems with the registry so I used npm set registry http://registry.npmjs.org/

I tried everything... it just drives me nuts.

Here are the errors:

npm ERR! Please try running this command again as root/Administrator.

```<code>npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "generator-knockout"
npm ERR! cwd D:\Sergiu\Knockout Test
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js'
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE'
npm ERR!  { [Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE']
npm ERR!   errno: 50,
npm ERR!   code: 'EPERM',
npm ERR!   path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\fstream\\lib\\writer.js:284:26',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
</code>```

答:
Here is how I fixed the problem in Windows. I was trying to install the CLI for Angular.

Turn off firewall and antivirus protections.

Right click the nodejs folder (under Program Files), select Properties (scroll all the way down), click the Security tab, and click all items in the ALLOW column (for All System Packages and any user or group that allows you to add the “allow” checkmark).

Click the Windows icon. Type cmd. Right click the top result and select Run as Administrator. A command window results.

Type npm cache clean. If there is an error, close log files or anything open and rerun.

Type npm install -g @angular/cli (Or whatever npm install command you are using)

Check the installation by typing ng –version (Or whatever you need to verify your install)

Good luck!
Note: If you are still having problems, check the Path in Environmental Variables. (To access:  Control Panel → System and Security → System → Advanced system settings → Environment variables.) My path variable included the following:
C:\Users\Michele\AppData\Roaming\npm

Body:
I've been desperately trying to install modules using node.js but it always fails getting packages with npm.

I logged in as Administrator and used powershell/cmd with "run as administrator". I also had problems with the registry so I used npm set registry http://registry.npmjs.org/

I tried everything... it just drives me nuts.

Here are the errors:

npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "generator-knockout"
npm ERR! cwd D:\Sergiu\Knockout Test
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js'
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE'
npm ERR!  { [Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE']
npm ERR!   errno: 50,
npm ERR!   code: 'EPERM',
npm ERR!   path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\fstream\\lib\\writer.js:284:26',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.


来源: stackexchange

问:
Tensorboard Cannot find .runfiles directory error
I installed tensorboard via pip and when I try to execute tensorboard --logdir= Graph/  I get the following error

```<code>Traceback (most recent call last):
  File "/home/pawan/.local/bin/tensorboard", line 152, in <module>
    Main()
  File "/home/pawan/.local/bin/tensorboard", line 102, in Main
    module_space = FindModuleSpace()
  File "/home/pawan/.local/bin/tensorboard", line 83, in FindModuleSpace
    sys.argv[0])
    AssertionError: Cannot find .runfiles directory for /home/pawan/.local/bin/tensorboard
</code>```

I do which tensorboard and get the following

```<code>/home/pawan/.local/bin/tensorboard
</code>```

thanks in advance.

答:
It seems they didn't consider that someone would be pip-installing TensorBoard in a user directory. Below is my hack to get it to work:

In the ~/.local/bin/tensorboard script, there's a section that looks like this:

```<code>def FindModuleSpace():
  # Follow symlinks, looking for my module space
  stub_filename = os.path.abspath(sys.argv[0])
  while True:
    # Found it?
    module_space = stub_filename + '.runfiles'
    if os.path.isdir(module_space):
      break
    for mod in site.getsitepackages():
      module_space = mod + '/tensorboard/tensorboard' + '.runfiles'
      if os.path.isdir(module_space):
        return module_space
</code>```

(just above the assertion with the "Cannot find .runfiles directory" error).

The directory it's looking for is

```<code>~/.local/lib/python2.7/site-packages/tensorboard/tensorboard.runfiles
</code>```

which you can discover by running find ~/.local -name '*runfiles*'.

I simply added it to the for loop over directories and all is well:

```<code>    for mod in site.getsitepackages() + [os.path.expanduser("~/.local/lib/python2.7/site-packages")]
</code>```

This is a hack because:

I explicitly said python2.7, which might not be the version of Python you're using. Correct it for your case.

The use of forward slashes won't work on Windows; a chain of os.path.join would be better.

This issue really should be communicated back to the TensorBoard developers. Did you do that?

ContentLicense: CC BY-SA 3.0

Body:
I installed tensorboard via pip and when I try to execute tensorboard --logdir= Graph/  I get the following error

Traceback (most recent call last):
  File "/home/pawan/.local/bin/tensorboard", line 152, in <module>
    Main()
  File "/home/pawan/.local/bin/tensorboard", line 102, in Main
    module_space = FindModuleSpace()
  File "/home/pawan/.local/bin/tensorboard", line 83, in FindModuleSpace
    sys.argv[0])
    AssertionError: Cannot find .runfiles directory for /home/pawan/.local/bin/tensorboard

I do which tensorboard and get the following

/home/pawan/.local/bin/tensorboard

thanks in advance.

Body:
It seems they didn't consider that someone would be pip-installing TensorBoard in a user directory. Below is my hack to get it to work:

In the ~/.local/bin/tensorboard script, there's a section that looks like this:

def FindModuleSpace():
  # Follow symlinks, looking for my module space
  stub_filename = os.path.abspath(sys.argv[0])
  while True:
    # Found it?
    module_space = stub_filename + '.runfiles'
    if os.path.isdir(module_space):
      break
    for mod in site.getsitepackages():
      module_space = mod + '/tensorboard/tensorboard' + '.runfiles'
      if os.path.isdir(module_space):
        return module_space

(just above the assertion with the "Cannot find .runfiles directory" error).

The directory it's looking for is

~/.local/lib/python2.7/site-packages/tensorboard/tensorboard.runfiles

which you can discover by running find ~/.local -name '*runfiles*'.

I simply added it to the for loop over directories and all is well:

    for mod in site.getsitepackages() + [os.path.expanduser("~/.local/lib/python2.7/site-packages")]

This is a hack because:

I explicitly said python2.7, which might not be the version of Python you're using. Correct it for your case.

The use of forward slashes won't work on Windows; a chain of os.path.join would be better.

This issue really should be communicated back to the TensorBoard developers. Did you do that?


问:
How to prevent new tags being created within a Contenteditable element?
```<code><p contenteditable="true"></p>
<p contenteditable="true"></p>
<h1 contenteditable="true"></h1>
</code>```

The code above consists of individual contenteditable elements rather than having the parent be contenteditable.

The problem I have is that when the user hits the Enter button in either of the contenteditable elements, it creates a new tag within that tag itself.

Example

The output would be:

```<code><p contenteditable="true">
    <p>One</p>
    <p>Two</p>
</p>
</code>```

The desired output would be:

```<code><p contenteditable="true"></p>
<p contenteditable="true">One</p>
<p contenteditable="true">Two</p>
</code>```

I am also using jQuery to ensure that all the elements would end up as being contenteditable:

```<code>setInterval(function () {
    $('p').attr('contenteditable','true');
    $('h1').attr('contenteditable','true');
},100);
</code>```

I would appreciate any help, thanks!

答:
So you need to detect that ENTER key to prevent its new line behavior.

And It would also be a right time to trigger a change element!

$("[contenteditable='true']").on("keydown",function(e){

  if(e.which=="13"){                      // 13 is enter key
    console.log("Enter Key!!");

    $(this).trigger("changeElement");     // Custom event here ;)
    return false;
  }
});

// Handler for our custom event: Focus on the next!
$("[contenteditable='true']").on("changeElement",function(){
  $(this).next().focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p contenteditable="true"></p>
<p contenteditable="true"></p>
<h1 contenteditable="true"></h1></code>```

Body:
The code above consists of individual contenteditable elements rather than having the parent be contenteditable.

The problem I have is that when the user hits the Enter button in either of the contenteditable elements, it creates a new tag within that tag itself.

Example

The output would be:

One

Two

The desired output would be:

One

Two

I am also using jQuery to ensure that all the elements would end up as being contenteditable:

setInterval(function () {
    $('p').attr('contenteditable','true');
    $('h1').attr('contenteditable','true');
},100);

I would appreciate any help, thanks!

Body:
So you need to detect that ENTER key to prevent its new line behavior.

And It would also be a right time to trigger a change element!

$("[contenteditable='true']").on("keydown",function(e){

  if(e.which=="13"){                      // 13 is enter key
    console.log("Enter Key!!");

    $(this).trigger("changeElement");     // Custom event here ;)
    return false;
  }
});

// Handler for our custom event: Focus on the next!
$("[contenteditable='true']").on("changeElement",function(){
  $(this).next().focus();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p contenteditable="true"></p>
<p contenteditable="true"></p>
<h1 contenteditable="true"></h1>


问:
Angular Material and MaterializeCSS Collision
I want to use Angular Material's components while taking advantage of Materialize CSS's utilities (text colors, typography, buttons...).
However, it looks like both libraries can't work along-side each other.
If I try to include Angular Material and Materialize (only css file) the styles looks broken.

Now that I'm thinking about it, even the HTML that every library requires is different (I'm talking about the final-compiled html of course).
Does anyone knows how to overcome this?
I use Angular v4.0, latest angular-cli, latest angular-material and materialize latest version.

Thanks!

答:
I'm successfully using both.  Using Material for navbar, buttons, etc. and Materialize for slider (as a carousel), selects, etc.  I had to reset some Materialize CSS styles that were too generalized, caused collisions, or not well-named ex. .white{ background-color: white; } ... an unfortunate choice.  Also had problems with one of the materialize.js versions where the slider component was broken in the plugin.  For this particular project, I'm on Minko's Angular seed, but it should work in CLI.  The versions below work for me.  Materialize CSS loads Roboto font; not necessary to load independently.

index.html

```<code><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- Roboto loaded by Materialize-->
<!--<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">-->
<!-- if css is not loaded, materialize.js crashes on style not found -->
<link media="screen,projection" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
</code>```

package.json

```<code>"@angular/material": "^2.0.0-beta.1",
"angular2-materialize": "^6.7.1",
"materialize-css": "^0.97.8",
</code>```

project.config.ts

```<code>this.APP_ASSETS = [
  ...this.APP_ASSETS,
  // ...
  {src: `${this.NPM_BASE}/@angular/material/core/theming/prebuilt/indigo-pink.css`, inject: true, vendor: false},
  // ...
  ];
this.addPackageBundles({
  name: '@angular/material',
  path: `${this.NPM_BASE}@angular/material/bundles/material.umd.js`,
});
this.addPackageBundles({
  name: 'angular2-materialize',
  path: `${this.NPM_BASE}angular2-materialize/dist/index.js`,
});
this.addPackageBundles({
  name: 'materialize-css',
  path: `${this.NPM_BASE}materialize-css/dist/js/materialize.js`,
});
</code>```

app.module.ts

```<code>import 'angular2-materialize';
import { MaterializeModule } from 'angular2-materialize';
// https://github.com/mgechev/angular-seed/wiki/Integration-with-AngularMaterial2
import { MaterialModule, MdIconRegistry } from '@angular/material';

@NgModule({
  imports: [
    ...
    MaterializeModule,
    MaterialModule.forRoot(),
    ...
  ],
</code>```

_reset.css

```<code>/* Materialize-CSS global resets */

/* other resets in component stylesheets to take advantage of Angular's css encapsulation */

input:not([type]), input[type=text], input[type=password],
input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea {
      background-color: white;
      border: initial;
      border-bottom: initial;
      border-radius: initial;
      outline: initial;
      height: initial;
      width: initial;
      font-size: initial;
      margin: initial;
      padding: initial;
      box-shadow: initial;
      box-sizing: initial;
      transition: initial;
    }

    nav {
      color: initial;
      background-color: initial;
      width: initial;
      box-shadow: initial;
    }

    nav ul a:hover {
      background: initial;
      background-color: initial;
    }
</code>```

Body:
I'm successfully using both.  Using Material for navbar, buttons, etc. and Materialize for slider (as a carousel), selects, etc.  I had to reset some Materialize CSS styles that were too generalized, caused collisions, or not well-named ex. .white{ background-color: white; } ... an unfortunate choice.  Also had problems with one of the materialize.js versions where the slider component was broken in the plugin.  For this particular project, I'm on Minko's Angular seed, but it should work in CLI.  The versions below work for me.  Materialize CSS loads Roboto font; not necessary to load independently.

index.html

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- Roboto loaded by Materialize-->
<!--<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">-->
<!-- if css is not loaded, materialize.js crashes on style not found -->
<link media="screen,projection" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">

package.json

"@angular/material": "^2.0.0-beta.1",
"angular2-materialize": "^6.7.1",
"materialize-css": "^0.97.8",

project.config.ts

this.APP_ASSETS = [
  ...this.APP_ASSETS,
  // ...
  {src: `${this.NPM_BASE}/@angular/material/core/theming/prebuilt/indigo-pink.css`, inject: true, vendor: false},
  // ...
  ];
this.addPackageBundles({
  name: '@angular/material',
  path: `${this.NPM_BASE}@angular/material/bundles/material.umd.js`,
});
this.addPackageBundles({
  name: 'angular2-materialize',
  path: `${this.NPM_BASE}angular2-materialize/dist/index.js`,
});
this.addPackageBundles({
  name: 'materialize-css',
  path: `${this.NPM_BASE}materialize-css/dist/js/materialize.js`,
});

app.module.ts

import 'angular2-materialize';
import { MaterializeModule } from 'angular2-materialize';
// https://github.com/mgechev/angular-seed/wiki/Integration-with-AngularMaterial2
import { MaterialModule, MdIconRegistry } from '@angular/material';

@NgModule({
  imports: [
    ...
    MaterializeModule,
    MaterialModule.forRoot(),
    ...
  ],

_reset.css

/* Materialize-CSS global resets */

/* other resets in component stylesheets to take advantage of Angular's css encapsulation */

input:not([type]), input[type=text], input[type=password],
input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea {
      background-color: white;
      border: initial;
      border-bottom: initial;
      border-radius: initial;
      outline: initial;
      height: initial;
      width: initial;
      font-size: initial;
      margin: initial;
      padding: initial;
      box-shadow: initial;
      box-sizing: initial;
      transition: initial;
    }

    nav {
      color: initial;
      background-color: initial;
      width: initial;
      box-shadow: initial;
    }

    nav ul a:hover {
      background: initial;
      background-color: initial;
    }


问:
Why is everything a property in iOS SDK tutorials?
In most of the iOS SDK tutorials I've read online both from Apple and elsewhere, so many instance variables are made properties, even when they are only accessed from within their own class.

E.G. in Facebook's latest iOS SDK a user is encouraged to maintain an instance of the Facebook class called facebook in the app delegate. facebook" is a property. This is then referred to throughout the sample code as "self.facebook". But the "facebook" property is not referenced anywhere from outside the app delegate.

Why is this? What am I missing? If an instance variable is only used within its own class, my inclination would be not to make it a property so that it is not publicly visible, and refer to it simply as facebook rather than self.facebook or  self->facebook from within the class.

Frankly, even if I needed the facebook property, I think I'd rather refer to it within the app delegate as simply "facebook" rather than "self.facebook".

So what gives? Why am I seeing properties everywhere?

答:
if you refer to facebook, then it will access the variable directly, if you access self.facebook, then it will go through the setter/getter methods.

the result is that if you need to mutate an object or at somepoint later in time, you need to do other things during the process of changing the value(ie boxing it) then you can put this in the setter method and reduce having to do it everywhere. its a good thing.

ContentLicense: CC BY-SA 2.5


问:
perl what is the difference between the two scripts
```<code>echo ab cd ef | perl -pe 'if($.==1){@L=split;foreach(@L)
{$_="SING.$_";}$_="@L\n"}'
SING.ab SING.cd SING.ef

echo ab cd ef | perl -pe 'if($.==1){@L=split;foreach(@L)
{$_="SING.$_";}print"@L\n"}'
SING.ab SING.cd SING.ef
ab cd ef
</code>```

What is $_="@L\n" doing? What does it mean? I suppose the first output is the output I want, but why can't I get it using the second code?

答:
The -p flag to perl wraps your script in a loop:

```<code>LINE: while (<>) {
    … your script …
}
continue {
    die "-p destination: $!\n" unless print $_;
}
</code>```

In other words: it reads each line into $_, runs your script, and prints $_ afterwards. This is what your first script snippet is depending on.

Your second script prints something on its own, but that doesn't make Perl skip its own print, so it ends up printing the original value of $_ afterwards. You can bypass this by using the -n flag instead of -p -- this behaves the same way, except without the automatic print.

Body:
echo ab cd ef | perl -pe 'if($.==1){@L=split;foreach(@L)
{$_="SING.$_";}$_="@L\n"}'
SING.ab SING.cd SING.ef

echo ab cd ef | perl -pe 'if($.==1){@L=split;foreach(@L)
{$_="SING.$_";}print"@L\n"}'
SING.ab SING.cd SING.ef
ab cd ef

What is $_="@L\n" doing? What does it mean? I suppose the first output is the output I want, but why can't I get it using the second code?

Body:
The -p flag to perl wraps your script in a loop:

LINE: while (<>) {
    … your script …
}
continue {
    die "-p destination: $!\n" unless print $_;
}

In other words: it reads each line into $_, runs your script, and prints $_ afterwards. This is what your first script snippet is depending on.

Your second script prints something on its own, but that doesn't make Perl skip its own print, so it ends up printing the original value of $_ afterwards. You can bypass this by using the -n flag instead of -p -- this behaves the same way, except without the automatic print.


问:
Difference between constructor and getter and setter
I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation.
I have laptop.java as follows

```<code>public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }

    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}
</code>```

and the laoptopRecords.java that is calling constructor as

```<code>public class laptopRecords {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        laptop laptop1=new laptop("Dell");
        System.out.println(laptop1);
    }

}
</code>```

Here I am not using the getter and setter methods and I get desired result for every laptop object.

If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.

laptop.java with getter and setter

```<code>public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }
    public void setlaptop(String brand){
        model=brand;
    }
    public String getlaptop(){
        return model;
    }
    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}
</code>```

答:
Getters are always nice. If you forgot what brand you set at creation, it would be nice to have a way of getting it out of that object. What if you got that object from somewhere else? Figuring out the brand using a getter is easy that way. But getters should only be available on directly exposed values. No need to create a getter for internalVersionString if it should not be publically known. But having a getter for colour would be nice... after all, you can see the colour by looking at the laptop (which is a bad analogy for OOP, but it's fitting here IMHO).

Regarding setters... if you have only one attribute, there is not much of a (visible) difference indeed. But what lies beyond that is a deeper subject... mutability. Of course, using a constructor has a greater overhead than simply setting the attribute (getting memory for a whole new object vs. getting memory for a string).

A nice example of not using setters is the String class in Java. A Java String is immutable; once created, it cannot be changed whatsoever. If you want to replace characters or remove some parts, what you get is not a changed String, but instead a brand new String with the desired changes made. But what if you had a class called TextDocument, that contained a whole file's worth of data? Having no ability to replace parts of that one without creating a whole new TextDocument could be hindering.

Having setters automatically means your object is mutable; that means, your object is not fixed upon creation, but can be changed later on. An ArrayList would be a nice example here. You'd certainly not want to allocate a whole new list only to change a single value.

The difference between mutable and immutable are not as clear when using simple cases like your laptop class. Using immutable classes comes in handy when doing parallel work, using mutable classes comes in handy when handling big objects with a large amount of memory needed to allocate.

There's no one-fits-all solution for that problem. But for exposed attributes which should be directly changeable, a setter would be convenient instead of having to construct a whole new object. Imagine a class with multiple attributes... taking your laptop for example, having a brand, a size, a colour and whatnot. If you just want to change the colour, having to construct a new laptop and copying over all the other attributes would be tedious, wouldn't it? A setter would make life easier for you in that case. Just call yourLaptop.setBrand("Dill"); and continue using that laptop. No reason to spend 500 bucks (or rather... bytes) for another one.

Body:
I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation.
I have laptop.java as follows

public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }

    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}

and the laoptopRecords.java that is calling constructor as

public class laptopRecords {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        laptop laptop1=new laptop("Dell");
        System.out.println(laptop1);
    }

}

Here I am not using the getter and setter methods and I get desired result for every laptop object.

If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.

laptop.java with getter and setter

public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }
    public void setlaptop(String brand){
        model=brand;
    }
    public String getlaptop(){
        return model;
    }
    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}


问:
Invalid left-hand side argument error when concatenating a string with variable in a function
I'm attempting to concatenate the value in a function with c and add 5 each time. However, I keep getting the error Uncaught ReferenceError: Invalid left-hand side in assignment. Does anyone know of a workaround? I am assuming I cannot use the + operator as a concatenate and then use it in the +=? I'm confused why this isn't working.

```<code>var c1 = 0;
var c2 = 0;

function(d) {
    d.number; //possible value of 1 or 2
    c + d.number += 5; //isn't this c1 += 5, or c2 += 5?
    "c" + d.number += 5; //also tried this - same error
    console.log(c1);
    console.log(c2);
;}
</code>```

答:
In case what Pointy said in the comments is not clear, you can "construct" the variable name (as you are trying to do) when it's an object property using the [ ] operator.

Here is an example:

```<code>var cObj = {};
cObj.c1 = 0;
cObj.c2 = 0;

function(d) {
    cObj['c' + d.number] += 5;
    console.log(cObj.c1);
    console.log(cObj.c2);
;}
</code>```

Body:
I'm attempting to concatenate the value in a function with c and add 5 each time. However, I keep getting the error Uncaught ReferenceError: Invalid left-hand side in assignment. Does anyone know of a workaround? I am assuming I cannot use the + operator as a concatenate and then use it in the +=? I'm confused why this isn't working.

var c1 = 0;
var c2 = 0;

function(d) {
    d.number; //possible value of 1 or 2
    c + d.number += 5; //isn't this c1 += 5, or c2 += 5?
    "c" + d.number += 5; //also tried this - same error
    console.log(c1);
    console.log(c2);
;}

Body:
In case what Pointy said in the comments is not clear, you can "construct" the variable name (as you are trying to do) when it's an object property using the [ ] operator.

Here is an example:

var cObj = {};
cObj.c1 = 0;
cObj.c2 = 0;

function(d) {
    cObj['c' + d.number] += 5;
    console.log(cObj.c1);
    console.log(cObj.c2);
;}


问:
how to make this function more (time) efficient?
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio
</code>```

thx

答:
I think that your time inefficiency may be coming from the fact you are using Counter instead of the dict. Some discussion here  suggests that the dict class has parts written in pure c, while counter is written in python.

I suggest altering your code to using a dict and test to see if that provides a faster time

Also why is this code duplicated?:

```<code>words = string.split()

words_counts = Counter(words)

words = string.split()

words_counts = Counter(words)

ratios = []
</code>```

Body:
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio

thx

Body:
I think that your time inefficiency may be coming from the fact you are using Counter instead of the dict. Some discussion here  suggests that the dict class has parts written in pure c, while counter is written in python.

I suggest altering your code to using a dict and test to see if that provides a faster time

Also why is this code duplicated?:

words = string.split()

words_counts = Counter(words)

words = string.split()

words_counts = Counter(words)

ratios = []


问:
Need some advice regarding a media query and CSS
I'm hoping someone is able to help with an issue I'm currently having with a website I am designing. The media query for mobile is where I'm getting hung up.

This is an image of it.

The content isn't centered. I can fix the text simply with a text-align property, and I assume that I can just make the image display as a block and use margin: 0 auto to center it, the problem is that the container itself is not centered. I'm using Bootstrap, and it's all in a Bootstrap container.

I think part of the issue is that on small screens, I am hiding some content that is to the right of the content I can't get centered using Bootstrap's "hidden-xs" and "hidden-sm" properties.

Here is the code for the relevant section in the screenshot, plus my CSS for the media query. If anyone could point me in the right direction, I'd appreciate it.

/* Content Styles*/
.gas-content {
 margin: 4.50em 0 4.50em 5%;
}

.left-content {
 margin: 2.50em 0 2.50em 5%;
}

.content-container {
 width: 75%;
 float: left;
}

.test-container {
 width: 25%;
 float: left;
 margin-top: -10px;
}

.move-up {
 margin-top: -2em;
}

.move-down {
 margin-top: 2em;
}

.img-center {
 display: block;
 margin: 0 auto;
}

.content-heading {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 font-weight: 600;
 line-height: 1.50em;
}

.services li {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 text-transform: uppercase;
 font-size: 1.25em;
 font-weight: 600;
}

.emergency-services li {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 text-transform: uppercase;
 font-size: 1.25em;
 font-weight: 600;
}

.contact-box {
 background-color: rgb(3, 17, 85);
 padding: 2em 0 6.50em 0;
}

.contact-box h3 {
 color: white;
 text-transform: uppercase;
 margin-left: 15px;
 font-family: 'Montserrat', sans-serif;
 font-weight: 600;
}

.contact-info {
 color: white;
 margin-left: 15px;
}

.eztouselogo {
 margin-left: 15px;
 margin-bottom: 15px;
}

.services-left {
 margin-right: 0.50em;
}

.content-paragraph {
 font-family: 'Open Sans', sans-serif;
 margin-bottom: 5em;
 line-height: 2.25em;
}

@media (max-width: 991px) {
 .test-container {
  display: none;
 }

 .content-container {
  display: block;
  margin: 0 auto;
  padding: 0 0 0 0;
  float: none;
  clear: both;
 }

 .container {
  display: block;
  margin: 0 auto;
  float: none;
  clear: both;
 }

 .pipes-img {
  width: 75%;
  height: 75%;
  display: block;
  margin: 0 auto;
  float: none;
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!--Begin Main Content -->
   <div class="container"> <!--New Container -->

    <div class="content-container"> <!--Content on Left Side of Testimonials -->
      <div class="row gas-content"> <!--Gas, Water, & Sewer Line Row -->
        <div class="col-md-4">
          <img class="pull-left img-responsive pipes-img" src="img/pipes.jpg">
        </div>
        <div class="col-xs-8 move-up">
          <h3 class="content-heading">Gas, Water, & Sewer Line Inspection and Replacement in the Pittsburgh Area</h3>
          <p class="content-paragraph">Vivamus id ante molestie, vehicula justo nec, facilisis justo. Sed efficitur feugiat accumsan. Nunc vitae fermentum nulla. Aliquam imperdiet nunc felis, et malesuada ligula molestie eget. Proin sodales dictum semper. Proin nec sodales quam. Maecenas ac erat non mauris laoreet volutpat. Proin egestas enim ut magna sagittis vulputate. Aenean non odio lacus. Nam vehicula metus viverra quam laoreet, nec interdum orci porttitor. Etiam gravida velit sit amet commodo suscipit. Cras est erat, scelerisque quis velit non, luctus molestie ex.</p>
          <div class="row">
            <div class="col-xs-5">
              <ul class="services services-left">
                <li>Sewer Lines</li>
                <li>Gas Lines</li>
                <li>Water Lines</li>
              </ul>
            </div>
            <div class="col-xs-7">
              <ul class="services services-right">
                <li>Sewer Inspections</li>
                <li>Water Heaters</li>
                <li>Full-Service Plumbing</li>
              </ul>
            </div>
          </div>
        </div>
      </div> <!--End Gas, Water, & Sewer Line Row --></code>```

答: Change col-xs-8 to col-md-8 to match the same breakpoint as that on the image. Otherwise, the div wrapping the image will be 100%, but the sibling div will remain 2/3s width.

Body:
I'm hoping someone is able to help with an issue I'm currently having with a website I am designing. The media query for mobile is where I'm getting hung up.

This is an image of it.

The content isn't centered. I can fix the text simply with a text-align property, and I assume that I can just make the image display as a block and use margin: 0 auto to center it, the problem is that the container itself is not centered. I'm using Bootstrap, and it's all in a Bootstrap container.

I think part of the issue is that on small screens, I am hiding some content that is to the right of the content I can't get centered using Bootstrap's "hidden-xs" and "hidden-sm" properties.

Here is the code for the relevant section in the screenshot, plus my CSS for the media query. If anyone could point me in the right direction, I'd appreciate it.

/* Content Styles*/
.gas-content {
 margin: 4.50em 0 4.50em 5%;
}

.left-content {
 margin: 2.50em 0 2.50em 5%;
}

.content-container {
 width: 75%;
 float: left;
}

.test-container {
 width: 25%;
 float: left;
 margin-top: -10px;
}

.move-up {
 margin-top: -2em;
}

.move-down {
 margin-top: 2em;
}

.img-center {
 display: block;
 margin: 0 auto;
}

.content-heading {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 font-weight: 600;
 line-height: 1.50em;
}

.services li {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 text-transform: uppercase;
 font-size: 1.25em;
 font-weight: 600;
}

.emergency-services li {
 color: rgb(3, 17, 85);
 font-family: 'Montserrat', sans-serif;
 text-transform: uppercase;
 font-size: 1.25em;
 font-weight: 600;
}

.contact-box {
 background-color: rgb(3, 17, 85);
 padding: 2em 0 6.50em 0;
}

.contact-box h3 {
 color: white;
 text-transform: uppercase;
 margin-left: 15px;
 font-family: 'Montserrat', sans-serif;
 font-weight: 600;
}

.contact-info {
 color: white;
 margin-left: 15px;
}

.eztouselogo {
 margin-left: 15px;
 margin-bottom: 15px;
}

.services-left {
 margin-right: 0.50em;
}

.content-paragraph {
 font-family: 'Open Sans', sans-serif;
 margin-bottom: 5em;
 line-height: 2.25em;
}

@media (max-width: 991px) {
 .test-container {
  display: none;
 }

 .content-container {
  display: block;
  margin: 0 auto;
  padding: 0 0 0 0;
  float: none;
  clear: both;
 }

 .container {
  display: block;
  margin: 0 auto;
  float: none;
  clear: both;
 }

 .pipes-img {
  width: 75%;
  height: 75%;
  display: block;
  margin: 0 auto;
  float: none;
 }
}

Gas, Water, & Sewer Line Inspection and Replacement in the Pittsburgh Area

Vivamus id ante molestie, vehicula justo nec, facilisis justo. Sed efficitur feugiat accumsan. Nunc vitae fermentum nulla. Aliquam imperdiet nunc felis, et malesuada ligula molestie eget. Proin sodales dictum semper. Proin nec sodales quam. Maecenas ac erat non mauris laoreet volutpat. Proin egestas enim ut magna sagittis vulputate. Aenean non odio lacus. Nam vehicula metus viverra quam laoreet, nec interdum orci porttitor. Etiam gravida velit sit amet commodo suscipit. Cras est erat, scelerisque quis velit non, luctus molestie ex.

Sewer Lines

Gas Lines

Water Lines

Sewer Inspections

Water Heaters

Full-Service Plumbing


问:
"Position: Fixed" causing problems
I'm having some issues with position: fixed. Here's my HTML code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <title>Horizontal Menus</title>
    <meta charset="utf-8">
    <link type="text/css" rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
    <nav role="navigation">
    <ul>
    <li><a class="button" href="">Home</a></li>
    <li><a class="button" href="">Links</a></li>
    <li><a class="button" href="">Forums</a></li>
    <li><a class="button" href="">Contact</a></li>
    </ul>
    </nav>

    <p>test</p>
    </body>
    </html>
</code>```

Here's my CSS code:

```<code>body {
    margin: 0;
    padding: 0;
    }
    .button {
    background: #e7e7e7;
    border: 1px solid;
    border-radius: 3px;
    font: 700 1.2em Helvetica,Arial,serif;
    line-height: 28px;
    padding: .4em .8em .4em .8em;
    text-align: center;
    box-sizing: border-box;

    }

    ul {
    padding: .5em;
    list-style-type: none;
    text-align: center;
    background-color: green;
    margin: 0;
    position: fixed;
    }

    li {
    display: inline;
    }

    a {
    color: red;
    }

    a:hover {
    background-color: black;
    color: white;
    }
</code>```

The site shows up like

        this with a fixed position, and it shows up like
        this without a fixed position. I want it to operate like a fixed position, but I also want to keep the navigation bat the way it previously was. Any help would be appreciated :)

答:
Either add width: 100% or left: 0; right: 0

body {
  margin: 0;
  padding: 0;
}

.button {
  background: #e7e7e7;
  border: 1px solid;
  border-radius: 3px;
  font: 700 1.2em Helvetica, Arial, serif;
  line-height: 28px;
  padding: .4em .8em .4em .8em;
  text-align: center;
  box-sizing: border-box;
}

ul {
  padding: .5em;
  list-style-type: none;
  text-align: center;
  background-color: green;
  margin: 0;
  position: fixed;
  width: 100%;
}

li {
  display: inline;
}

a {
  color: red;
}

a:hover {
  background-color: black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Horizontal Menus</title>
  <meta charset="utf-8">
  <link type="text/css" rel="stylesheet" href="stylesheet.css">
</head>

<body>
  <nav role="navigation">
    <ul>
      <li>Home</li>
      <li>Links</li>
      <li>Forums</li>
      <li>Contact</li>
    </ul>
  </nav>

  <p>test</p>
</body>

</html></code>```

Title: "Position: Fixed" causing problems

Body:
I'm having some issues with position: fixed. Here's my HTML code:

    <!DOCTYPE html>

    <title>Horizontal Menus</title>
    <meta charset="utf-8">
    <link type="text/css" rel="stylesheet" href="stylesheet.css">

Home

Links

Forums

Contact

test

Here's my CSS code:

body {
    margin: 0;
    padding: 0;
    }
    .button {
    background: #e7e7e7;
    border: 1px solid;
    border-radius: 3px;
    font: 700 1.2em Helvetica,Arial,serif;
    line-height: 28px;
    padding: .4em .8em .4em .8em;
    text-align: center;
    box-sizing: border-box;

    }

    ul {
    padding: .5em;
    list-style-type: none;
    text-align: center;
    background-color: green;
    margin: 0;
    position: fixed;
    }

    li {
    display: inline;
    }

    a {
    color: red;
    }

    a:hover {
    background-color: black;
    color: white;
    }

The site shows up like

        this with a fixed position, and it shows up like
        this without a fixed position. I want it to operate like a fixed position, but I also want to keep the navigation bat the way it previously was. Any help would be appreciated :)

Body:
Either add width: 100% or left: 0; right: 0

body {
  margin: 0;
  padding: 0;
}

.button {
  background: #e7e7e7;
  border: 1px solid;
  border-radius: 3px;
  font: 700 1.2em Helvetica, Arial, serif;
  line-height: 28px;
  padding: .4em .8em .4em .8em;
  text-align: center;
  box-sizing: border-box;
}

ul {
  padding: .5em;
  list-style-type: none;
  text-align: center;
  background-color: green;
  margin: 0;
  position: fixed;
  width: 100%;
}

li {
  display: inline;
}

a {
  color: red;
}

a:hover {
  background-color: black;
  color: white;
}

<!DOCTYPE html>
<html>

<head>
  <title>Horizontal Menus</title>
  <meta charset="utf-8">
  <link type="text/css" rel="stylesheet" href="stylesheet.css">
</head>

<body>
  <nav role="navigation">
    <ul>
      <li><a class="button" href="">Home</a></li>
      <li><a class="button" href="">Links</a></li>
      <li><a class="button" href="">Forums</a></li>
      <li><a class="button" href="">Contact</a></li>
    </ul>
  </nav>

  <p>test</p>
</body>

</html>


问:
Expected expression before token
Here is the code I got, when trying to compile it, I get two errors which unfortunately I fail to spot at the moment, hopefully another pair of eye would point out some insights.

The error falls at these two lines

```<code>print_all_paths(graph, int source_id, int destination_id, visited_arr, path, path_counter);
</code>```

Error for this one is:

```<code>error: expected expression before 'int'
</code>```

Second error falls at:

```<code>void print_all_paths(Graph* graph, int source_id, int destination_id, int visited_arr[], int path[], int &path_counter)
</code>```

Shows:

```<code>error: expected ';', ',' or ')' before '&' token
</code>```

Thank you!

答:
When you declare a function, you are supposed to provide all the data types of the arguments passed to the function. However, when you call the function, you do not need to specify the data types of the values passed, as they are already defined in the function header.

So change the line causing the first error to:

```<code>print_all_paths(graph, source_id, destination_id, visited_arr, path, path_counter); // The "int" is removed
</code>```

The second error is caused because you cannot reference variables in C; that is A C++ feature. Therefore, you should change int *path_counter instead of int &path_counter in the function void print_all_paths

Title: Expected expression before token

Body:
Here is the code I got, when trying to compile it, I get two errors which unfortunately I fail to spot at the moment, hopefully another pair of eye would point out some insights.

The error falls at these two lines

print_all_paths(graph, int source_id, int destination_id, visited_arr, path, path_counter);

Error for this one is:

error: expected expression before 'int'

Second error falls at:

void print_all_paths(Graph* graph, int source_id, int destination_id, int visited_arr[], int path[], int &path_counter)

Shows:

error: expected ';', ',' or ')' before '&' token

Thank you!

Body:
When you declare a function, you are supposed to provide all the data types of the arguments passed to the function. However, when you call the function, you do not need to specify the data types of the values passed, as they are already defined in the function header.

So change the line causing the first error to:

print_all_paths(graph, source_id, destination_id, visited_arr, path, path_counter); // The "int" is removed

The second error is caused because you cannot reference variables in C; that is A C++ feature. Therefore, you should change int *path_counter instead of int &path_counter in the function void print_all_paths


问:
Creat a listview when I click a button in android
Hello guys I am new on android programming.I want to create a shopping list app so the idea is first. This is my idea :

There is no list then when I click the Add Button

I can give a name to the list and after that add it ( where I can fill this list with products to buy later )

The problem I have is:

I can't find an idea how to create a list when I click a button like this image :

How can I create more than one list and show them like the picture below.

I don't need code, I just the idea and I will search for the rest myself. I already look everywhere but couldn't find solution for it. Thank you guys.

答: You don't really have to createp a list if you click the button. You have to create the list in the UI or the xml files. If you click the add button, what you want to happen is to add data for the list to display. If you don't know about ListViews and how to add data to them using adapters, I suggest reading more on the topic:http://www.vogella.com/tutorials/AndroidListView/article.html</p>


问:
How to dynamically increment dates using strtotime?
I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?</p>

```<code>    <?php
    //incrementing dates for bi-weekly (26 periods// 26 dates)
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
    $i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
    echo'<br>';
    $seconddate =strtotime("+14 days", strtotime($i));//2
    $ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
    echo'<br>';
    ?>
</code>```

答:
Probably the easiest way to do this would be with an array</p>

```<code>$myDates = [];
$firstdate = strtotime("+17 days", strtotime("2017-04-03"));
array_push($myDates, date("Y-m-d",$firstdate));
for($i=0;$i<25;$i++){
    $lastdate = $myDates[$i];
    $nextdate = strtotime("+14 days", strtotime($lastdate));
    array_push($myDates,date("Y-m-d",$nextdate));
}

echo "```".var_dump($myDates)."```";
</code>```

Body:
I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?

    <?php
    //incrementing dates for bi-weekly (26 periods// 26 dates)
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
    $i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
    echo'
';
    $seconddate =strtotime("+14 days", strtotime($i));//2
    $ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
    echo'
';
    ?>

Body:
Probably the easiest way to do this would be with an array

$myDates = [];
$firstdate = strtotime("+17 days", strtotime("2017-04-03"));
array_push($myDates, date("Y-m-d",$firstdate));
for($i=0;$i<25;$i++){
    $lastdate = $myDates[$i];
    $nextdate = strtotime("+14 days", strtotime($lastdate));
    array_push($myDates,date("Y-m-d",$nextdate));
}

echo "<pre>".var_dump($myDates)."</pre>";


问:
K8n NodePort not available to public
If the Google Container Engine cluster has the service configured as LoadBalancer it's available to the general public as expected. But if I change that to NodePort it is not available as <nodeIp>:<nodePort>.
The service (web-service.yml) looks like that:

```<code>apiVersion: v1
kind: Service
metadata:
 name: web
 labels:
   name: web
spec:
 type: NodePort
# type: LoadBalancer
 ports:
   - port: 80
     targetPort: 8080
     protocol: TCP
     nodePort: 30000
 selector:
   name: web
</code>```

I would be very happy if someone could tell me why it isn't working.

Here is some background
The cluster consists of a MongoDB deployment (db-deployment.yml) with an according service (db-service.yml) and a Jetty deployment (web-deployment.yml) with an according service (web-service.yml)

It can be found at GitHub as part of this project with the according Readme.md file.

答:
Did you open the port (30000) in the firewall? Also make sure you use the public IP of your VM.

See this answer

Title: K8n NodePort not available to public

Body:
If the Google Container Engine cluster has the service configured as LoadBalancer it's available to the general public as expected. But if I change that to NodePort it is not available as <nodeIp>:<nodePort>.
The service (web-service.yml) looks like that:

apiVersion: v1
kind: Service
metadata:
 name: web
 labels:
   name: web
spec:
 type: NodePort
# type: LoadBalancer
 ports:
   - port: 80
     targetPort: 8080
     protocol: TCP
     nodePort: 30000
 selector:
   name: web

I would be very happy if someone could tell me why it isn't working.

Here is some background
The cluster consists of a MongoDB deployment (db-deployment.yml) with an according service (db-service.yml) and a Jetty deployment (web-deployment.yml) with an according service (web-service.yml)

It can be found at GitHub as part of this project with the according Readme.md file.


问:
Oops, try again. Your function failed on the message yes. It returned 'yes' when it should have returned 'Shutting down'
Here is my pyhton practice program:

```<code>def shut_down(s):
    return s

    if yes():
        shut_down("Shutting down")
    elif no():
        shut_down("Shutdown aborted")
    else:
        shut_down("Sorry")
</code>```

the question given to me are:

if the shut_down function receives an s equal to "yes", it should return "Shutting down"

elif s is equal to "no", then the function should return "Shutdown aborted".

if shut_down gets anything other than those inputs, the function should return "Sorry"

答:
something shorter than the best answer:</p>

```<code>def shut_down(s):

    if s == "yes":
        return "Shutting down"
    elif s == "no":
        return "Shutdown aborted"
    else:
        return "Sorry"

print shut_down("algo")
</code>```

Body:
Here is my pyhton practice program:

def shut_down(s):
    return s

    if yes():
        shut_down("Shutting down")
    elif no():
        shut_down("Shutdown aborted")
    else:
        shut_down("Sorry")

the question given to me are:

if the shut_down function receives an s equal to "yes", it should return "Shutting down"

elif s is equal to "no", then the function should return "Shutdown aborted".

if shut_down gets anything other than those inputs, the function should return "Sorry"

Body:
something shorter than the best answer:

def shut_down(s):

    if s == "yes":
        return "Shutting down"
    elif s == "no":
        return "Shutdown aborted"
    else:
        return "Sorry"

print shut_down("algo")


问:
Lost CSR file but have the KEY file and CRT files
I requested a SSL certificate by generating a key file then a .csr file. I submitted these to a provided and obtained the .crt files.

I then accidentally removed the .csr

I still have all the other files and can setup a https site. However will this be a problem down the line? Is there a way I can get the .csr file back? Will i ever need this again?

答: No. You can generate a new CSR any time you need it, which is only at renewal or re-keying time.</p>


问:
Bootstrap gallery won't change image after implemented into site
My image gallery, won't change foxus images, despite working fine on bootsnipp, where I got it.

Here is the site, "live"

here is the bootsnipp I got.

and the source can be found on github at /blakeaham/dansite1

Details:  I put the js from the bootsnipp into the gallery.html, at the bottom, but I tried moving it to the top, and linking it as a separate file, which doesn't help,

答:
Your site reports jQuery is not defined. Looking through your source code, you appear to have commented it out.

Also, remember that the DOM is read sequentially, so your image clicks not working is probably because they're using jQuery higher up in your DOM than when you reference jQuery.

It's recommended to include jQuery in your  to ensure that it loads before any actual jQuery code (though you still have to watch for dependencies).

Don't forget that you can always debug your site and spot the error messages in your Developer Console by pressing F12 :)

Hope this helps! :)

Body:
Your site reports jQuery is not defined. Looking through your source code, you appear to have commented it out.

Also, remember that the DOM is read sequentially, so your image clicks not working is probably because they're using jQuery higher up in your DOM than when you reference jQuery.

It's recommended to include jQuery in your <head> to ensure that it loads before any actual jQuery code (though you still have to watch for dependencies).

Don't forget that you can always debug your site and spot the error messages in your Developer Console by pressing F12 :)

Hope this helps! :)


问:
Fetch POST with formData is empty in Express JS route
I have a form that uses fetch() to AJAX with a route on NodeJS. When the AJAX POST hits the route, req.body shows an empty object {}.

Here's the code:

// in app.js

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

// in form.js

```<code>form.getElementById('form__option').addEventListener('submit', e => {
    e.preventDefault()
    const form = $('form')[0]
    fetch('/polls/create', {
        method: 'POST',
        body: new FormData(form)
    })
})
</code>```

// in appRoute.js

```<code>exports.createPost = (req, res, next) => {
    console.log('req body', req.body)
    res.send('NOT IMPLEMENTED: pollsController createPost');
}
</code>```

答:
The issue here is that FormData will set the content type to be multipart/form-data, which Express' body-parser doesn't understand.

Note the comment here:

[body-parser] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: busboy and connect-busboy; multiparty and connect-multiparty; formidable; multer.

So in other words, you have to user a different module to handle the multipart body that FormData sends. I can recommend formidable, in which case you're server code would look something like:

```<code>const formidable = require('formidable')

exports.createPost = (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        console.log(fields)
        res.send('NOT IMPLEMENTED: pollsController createPost');
    }
}
</code>```

Body:
I have a form that uses fetch() to AJAX with a route on NodeJS. When the AJAX POST hits the route, req.body shows an empty object {}.

Here's the code:

// in app.js

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

// in form.js

form.getElementById('form__option').addEventListener('submit', e => {
    e.preventDefault()
    const form = $('form')[0]
    fetch('/polls/create', {
        method: 'POST',
        body: new FormData(form)
    })
})

// in appRoute.js

exports.createPost = (req, res, next) => {
    console.log('req body', req.body)
    res.send('NOT IMPLEMENTED: pollsController createPost');
}

Body:
The issue here is that FormData will set the content type to be multipart/form-data, which Express' body-parser doesn't understand.

Note the comment here:

[body-parser] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: busboy and connect-busboy; multiparty and connect-multiparty; formidable; multer.

So in other words, you have to user a different module to handle the multipart body that FormData sends. I can recommend formidable, in which case you're server code would look something like:

const formidable = require('formidable')

exports.createPost = (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        console.log(fields)
        res.send('NOT IMPLEMENTED: pollsController createPost');
    }
}


问:
How to make an array of UIImageViews at class level in Swift?
When I try to make an array with UIImageView s declared as @IBAction I receive the "Cannot use instance member within property initializer, property initializers run before self is available" compiler error. How do I workaround this?

答: You declared imageViews as a constant (a separate issue) then redeclared it again in viewDidLoad. You shouldn't need to redeclare it (or you could just declare once in viewDidLoad)</p>


问:
program running in Tizen gear s2 can't get same result in with windows?
I am developing a project in tizen gear S2, but I try to use the same code in my pc but I can't get the same result with in gear s2, so what's wrong with this problem?</p>

答: Gear S2 is commercial device and use own theme. But PC emulator is raw Tizen platform and use reference theme. So, It you use default theme and UI framework(EFL), Your widget may show different theme and style.</p>


问:
In general, does replacing AND with a pair of nested IFs speed things up?
I'm weighing the differences between

```<code>If[condition1 AND condition2, A, B]
</code>```

and

```<code>If[condition1, If[condition2, A, B], B]
</code>```

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.

答: Often (but not always), languages will have a feature called short circuited logic whereby the second operand in an AND condition will only be evaluated if the first is true (Also for an OR, the second will only be evaluated if the first is false). That would be dependent on the language, however.</p>

Body:
I'm weighing the differences between

If[condition1 AND condition2, A, B]

and

If[condition1, If[condition2, A, B], B]

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.


问:
float object over an image using CSS?
Is it possible to float an object over an image using css? I want to place a form over an image (that isn't a background). Float doesn't work, but is there some variable that does provide this function?

When you float an object it pushes the text to either side of the object. What I am looking for is something that will not do this, that will just float without regard to what is underneath it.

答:
If you make the image in question the background image for the div or (yes, I'm saying it) table used to format the form, then the form will "float" over the image.

If that is not sufficient for your needs, check out http://w3schools.com/css/css_positioning.asp

Title: float object over an image using CSS?


问:
Conditions in Thymeleaf th:href parameter
So I have an element in my Thymeleaf template which has a link looking like that:

```<code>th:href="@{'/search/'+${searchType}(parameter1=${parameter1}, ... parameter10=${parameter10})}"
</code>```

According to the current implementation the parameter1...10 can have values that I don't want to include in the href. For example, if it's id, it can be -1, which means that no id chosen, so this parameter have to be omitted to avoid clattering the url string, so instead of

/search/type?parameter1=-1

get just clean

/search/type

How this can be achieved?
I tried this:

```<code>th:href="@{'/search/'+${searchType}((${parameter1}=='-1'?''parameter1=${parameter1}))}"
</code>```

But this expression causes exception:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse
  as expression:

I tried this:

```<code>th:href="@{'/search/'+${searchType}(parameter1=(${parameter1}=='-1'?'':${parameter1}))}"
</code>```

But then the result is still not acceptable:

/search/type?parameter1=

So what is the correct way to eliminate undesirable parameters from the url?

答:
Looks like I did more research and found a way.
The key word is: preprocessing.
This is the link.
So for my purposes the following expression works:

```<code>th:href="@{'/search/'+${searchType}(__(${parameter1}=='-1'?','parameter1=${parameter1})__,__(${parameter2}=='-1'?','parameter2=${parameter2})__)}"
</code>```

Short explanation: surround the expression with double underscores __(${parameter1}=='-1'?','parameter1=${parameter1})__, and then the surrounded expression will only be added if it evaluates to non-empty string. In the case of url parameters ',' evaluates to two empty parameters and not added.

Body:
So I have an element in my Thymeleaf template which has a link looking like that:

th:href="@{'/search/'+${searchType}(parameter1=${parameter1}, ... parameter10=${parameter10})}"

According to the current implementation the parameter1...10 can have values that I don't want to include in the href. For example, if it's id, it can be -1, which means that no id chosen, so this parameter have to be omitted to avoid clattering the url string, so instead of

/search/type?parameter1=-1

get just clean

/search/type

How this can be achieved?
I tried this:

th:href="@{'/search/'+${searchType}((${parameter1}=='-1'?''parameter1=${parameter1}))}"

But this expression causes exception:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse
  as expression:

I tried this:

th:href="@{'/search/'+${searchType}(parameter1=(${parameter1}=='-1'?'':${parameter1}))}"

But then the result is still not acceptable:

/search/type?parameter1=

So what is the correct way to eliminate undesirable parameters from the url?

Body:
Looks like I did more research and found a way.
The key word is: preprocessing.
This is the link.
So for my purposes the following expression works:

th:href="@{'/search/'+${searchType}(__(${parameter1}=='-1'?','parameter1=${parameter1})__,__(${parameter2}=='-1'?','parameter2=${parameter2})__)}"

Short explanation: surround the expression with double underscores __(${parameter1}=='-1'?','parameter1=${parameter1})__, and then the surrounded expression will only be added if it evaluates to non-empty string. In the case of url parameters ',' evaluates to two empty parameters and not added.


问:
Joining 2 tables cause resources exceeded error in BigQuery
I am trying to fetch records by joining 2 tables, and in this case I consider 6 months worth of data.
I get the "Resources exceeded error".

Could anyone please advice on some query enhancements that would help me in bypassing this error?

Thanks in advance!!

```<code>    SELECT
      *
    FROM (
      SELECT
        A.Id1 AS Id1,
        A.Id2 AS Id1,
        StartTime,
        StopTime,
        Duration AS ID,
        Latitude,
        Longitude,
        DateTime
      FROM (
        SELECT
          *
        FROM
          `Tb1`
        WHERE
          HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451)
          AND _PARTITIONTIME BETWEEN TIMESTAMP('2016-01-01')
          AND TIMESTAMP('2016-12-31') ) AS A
      JOIN (
        SELECT
          *
        FROM
          `Tb2.T2016*`
        WHERE
          _TABLE_SUFFIX BETWEEN "0601"
          AND "1231"
          AND HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451) ) AS B
      ON
        A.StartTime < B.DateTime
        AND A.StopTime >= B.DateTime
        AND A.Id1 = B.Id1 )
    ORDER BY
      Id1,
      Id2,
      DateTime`
</code>```

答:
Start with removing ORDER BY part of your query!

```<code>ORDER BY
  Id1,
  Id2,
  DateTime
</code>```

Usually, this is the main reason for

```<code>resources exceeded error in BigQuery
</code>```

I also noticed some issue with your query that most likely related to the fact that you slightly obscured your original query

1 - same column name used

```<code>A.Id1 AS Id1,
A.Id2 AS Id1,
</code>```

2 - different time period

'2016-01-01' - '2016-12-31' in

```<code>BETWEEN TIMESTAMP('2016-01-01') AND TIMESTAMP('2016-12-31')
</code>```

vs. '2016-06-01' - '2016-12-31'

```<code>BETWEEN "0601" AND "1231"
</code>```

Body:
I am trying to fetch records by joining 2 tables, and in this case I consider 6 months worth of data.
I get the "Resources exceeded error".

Could anyone please advice on some query enhancements that would help me in bypassing this error?

Thanks in advance!!

    SELECT
      *
    FROM (
      SELECT
        A.Id1 AS Id1,
        A.Id2 AS Id1,
        StartTime,
        StopTime,
        Duration AS ID,
        Latitude,
        Longitude,
        DateTime
      FROM (
        SELECT
          *
        FROM
          `Tb1`
        WHERE
          HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451)
          AND _PARTITIONTIME BETWEEN TIMESTAMP('2016-01-01')
          AND TIMESTAMP('2016-12-31') ) AS A
      JOIN (
        SELECT
          *
        FROM
          `Tb2.T2016*`
        WHERE
          _TABLE_SUFFIX BETWEEN "0601"
          AND "1231"
          AND HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451) ) AS B
      ON
        A.StartTime = B.DateTime
        AND A.Id1 = B.Id1 )
    ORDER BY
      Id1,
      Id2,
      DateTime`

Body:
Start with removing ORDER BY part of your query!

ORDER BY
  Id1,
  Id2,
  DateTime

Usually, this is the main reason for

resources exceeded error in BigQuery

I also noticed some issue with your query that most likely related to the fact that you slightly obscured your original query

1 - same column name used

A.Id1 AS Id1,
A.Id2 AS Id1,

2 - different time period

'2016-01-01' - '2016-12-31' in

BETWEEN TIMESTAMP('2016-01-01') AND TIMESTAMP('2016-12-31')

vs. '2016-06-01' - '2016-12-31'

BETWEEN "0601" AND "1231"


问:
node.js Jade javascript jquery not doing anything reasonable
This is my .jade file

```<code>extends layout
block content
  script(src="/jquery/dist/jquery.js")
  script(type="text/javascript").
    var x = $('#s').text;
    console.log('jquery', x);

  h1= title
  input(type="text", id="s", name="s", text="#{s}", value="#{s}")
  p
  p end
</code>```

This is what gets written to the console:

```<code>jquery function ( value ) {
        return access( this, function( value ) {
            return value === undefined ?
                jQuery.text( this ) :
                this.empty().each( function() {
                    if ( this.nodeType === 1 || this.nodeTyp…
</code>```

The text input get filled correctly when rendered by the router.

Why can't this just given me the text (or value for that matter because I tried that too) of the input?

答:
you need to use .text() or .val()
and you need to mode the script block down below the input tag

```<code>extends layout
block content
  h1= title
  input(type="text", id="s", name="s", text="#{s}", value="#{s}")
  p
  p end
  script(src="/jquery/dist/jquery.js")
  script(type="text/javascript").
    var x = $('#s').text();
    console.log('jquery', x);
</code>```

EDIT: I'm sorry. Does a input text even have a text attribute? use .val();

Body:
This is my .jade file

extends layout
block content
  script(src="/jquery/dist/jquery.js")
  script(type="text/javascript").
    var x = $('#s').text;
    console.log('jquery', x);

  h1= title
  input(type="text", id="s", name="s", text="#{s}", value="#{s}")
  p
  p end

This is what gets written to the console:

jquery function ( value ) {
        return access( this, function( value ) {
            return value === undefined ?
                jQuery.text( this ) :
                this.empty().each( function() {
                    if ( this.nodeType === 1 || this.nodeTyp…

The text input get filled correctly when rendered by the router.

Why can't this just given me the text (or value for that matter because I tried that too) of the input?

Body:
you need to use .text() or .val()
and you need to mode the script block down below the input tag

extends layout
block content
  h1= title
  input(type="text", id="s", name="s", text="#{s}", value="#{s}")
  p
  p end
  script(src="/jquery/dist/jquery.js")
  script(type="text/javascript").
    var x = $('#s').text();
    console.log('jquery', x);

EDIT: I'm sorry. Does a input text even have a text attribute? use .val();


问:
function that calculates non-zero inputs of a vector
I'm new to scheme and having difficulty understanding vectors in scheme. I need to create a function that calculates the number of non-zero inputs in
a vector. I need to do this by not converting the vector into a list.
For exampl3.

```<code>(non-zero-dim #(3 0 2 4 0 2))
returns 4
</code>```

My code so far is

```<code>(define non-zero-input
(lambda (vector)
(let ((size (vector-length vector)))
  do ((position 0 (+ position 1))
      (total 0
(if ((not (zero? vector-ref vector position)))
(+ total 1))
(((= position size) total)))))))
</code>```

However I'm getting this error :do: bad syntax in: (do ((position 0 (+ position 1)) (total 0 (if ((not (zero? vector-ref vector position))) (+ total 1)) (((= position size) total))
How do i fix this error ?

答:
Using the built-in procedures vector-length and vector-filter-not, you can simplify your function as:

```<code>(define (non-zero-dim vec)
  (vector-length (vector-filter-not zero? vec)))
</code>```

For example,

```<code>> (non-zero-dim #(3 0 2 4 0 2))
4
</code>```

Some things to consider:

Keep track of your brackets. For example, (zero? vector-ref vector position) should be (zero? (vector-ref vector position)), whereby arity of zero? is one, and arity of vector-ref is two. Similarly with do ... vs. (do ... etc.

if statements must have an else clause (ie. (if condition then else)). For example, (if true 1) would fail, but (if true 1 2) would pass. Hence, (if ((not (zero? vector-ref vector position))) (+ total 1)) would fail.

Body:
I'm new to scheme and having difficulty understanding vectors in scheme. I need to create a function that calculates the number of non-zero inputs in
a vector. I need to do this by not converting the vector into a list.
For exampl3.

(non-zero-dim #(3 0 2 4 0 2))
returns 4

My code so far is

(define non-zero-input
(lambda (vector)
(let ((size (vector-length vector)))
  do ((position 0 (+ position 1))
      (total 0
(if ((not (zero? vector-ref vector position)))
(+ total 1))
(((= position size) total)))))))

However I'm getting this error :do: bad syntax in: (do ((position 0 (+ position 1)) (total 0 (if ((not (zero? vector-ref vector position))) (+ total 1)) (((= position size) total))
How do i fix this error ?

Body:
Using the built-in procedures vector-length and vector-filter-not, you can simplify your function as:

(define (non-zero-dim vec)
  (vector-length (vector-filter-not zero? vec)))

For example,

> (non-zero-dim #(3 0 2 4 0 2))
4

Some things to consider:

Keep track of your brackets. For example, (zero? vector-ref vector position) should be (zero? (vector-ref vector position)), whereby arity of zero? is one, and arity of vector-ref is two. Similarly with do ... vs. (do ... etc.

if statements must have an else clause (ie. (if condition then else)). For example, (if true 1) would fail, but (if true 1 2) would pass. Hence, (if ((not (zero? vector-ref vector position))) (+ total 1)) would fail.


问:
How to run Webpack Hot Module Replacement (HMR) in Production
Id like to run HMR in production, using it for seamless application updates. I cannot seem to find any docs or tutorials regarding how to do this.

My setup is currently "serverless", and statics are served from AWS S3. My first thought is i would create an "Update" server of some sort, wherby the HMR clients would poll for updates, and the magic would work.

My questions:

a) How do I run this in production (optimally)

b) For this to work the "Update" server will have to know of module changes, how?

I know the json file with the updates is what HMR relies on to know of the changes, will i have to push some sort of this file to the server?

Or, Do I have the server watch S3 files somehow, and recompile, in turn triggering updates.

A complete solution would be awesome, but also just some sudo logic as to how this could work would be great.

答:
Read this two documents to understand how it works:

https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack

https://github.com/webpack/docs/wiki/hot-module-replacement

No idea to what you mean by "serverless"... How would you serve a website without a server? You will need at least webpack or a nodejs/express instance running somewhere

This will not be optimal. This feature is thought to be used for development. HMR will add listeners to the application for file changes and add code for replacing old modules with new ones. This adds overhead to your code. Optimal would be no hmr.


问:
Uncaught TypeError: Cannot read property 'split' of undefined window location
I have this error and I google about it. But I didn´t found my issue

```<code>  var url = window.location.hash.split('?Token=')[1];
        url = url.split('Token=');

        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
            completado,
            fallo);
        }
</code>```

My value isn´t empty or undefinied, can anyone help me there? Thanks!

答: I think it should be var url = window.location.split('?Token=')[1]; (no .hash since you want to take parameter)

Body:
I have this error and I google about it. But I didn´t found my issue

  var url = window.location.hash.split('?Token=')[1];
        url = url.split('Token=');

        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
            completado,
            fallo);
        }

My value isn´t empty or undefinied, can anyone help me there? Thanks!


问:
Getting overflow when I divide in assembly language
I'm doing a code that add 2 numbers of 4 digits in assembly language (intel 8086). At some point in the code, I want to divide AX by BX register (using div BX), for example AX=2AB3 (10931 in decimal) and BX=2710 (10000 in decimal).

Normally, as result I should have AX=1 (quotient) and DX=3A3 (remainder), the problem is that the emulator show me the overflow message.

Here is the code :

DATA SEGMENT

MSG1 DB 0DH,0AH, "first number  : $" ,0DH
MSG2 DB 0DH,0AH, "second number  : $" ,0DH
RST  DB 0DH,0AH, "result  : $" ,0DH

DATA ENDS
PILE SEGMENT PARA STACK
    DB 128 DUP (?)
PILE ENDS

CODE SEGMENT
    ASSUME CS:CODE,DS:DATA,SS:PILE

DEBUT:
mov ax,data
mov ds,ax

mov dx,offset MSG1     ; first msg
mov ah,9
int 21h

mov ah,1     ; multipling first number by 1000 and store it
int 21h
sub al,30h
mov ah,0
mov bx,1000
mul bx
push ax

mov ah,1         ; multipling second number by 100 and store it
int 21h
sub al,30h
mov ah,0
mov bx,100
mul bx
push ax

mov ah,1        ; multipling third number by 10 and store it
int 21h
sub al,30h
mov ah,0
mov bx,10
mul bx
push ax

mov ah,1            ; last number
int 21h
sub al,30h
mov ah,0
push ax

mov dx,offset MSG2    ;same thing for the second 4 digits number
mov ah,9
int 21h

mov ah,1
int 21h
sub al,30h
mov ah,0
mov bx,1000
mul bx
push ax

mov ah,1
int 21h
sub al,30h
mov ah,0
mov bx,100
mul bx
push ax

mov ah,1
int 21h
sub al,30h
mov ah,0
mov bx,10
mul bx
push ax

mov ah,1
int 21h
sub al,30h
mov ah,0
push ax
       ;-------------------------------
       ;here I'm doing the addition to all the stored numbers to have the result number
       ;in the DX register
pop dx
pop bx
add dx,bx
pop bx
add dx,bx
pop bx
add dx,bx
pop bx
add dx,bx
pop bx
add dx,bx
pop bx
add dx,bx
pop bx
add dx,bx
push dx   ; I've stored the result number because I'm going to use the DX register to show the
          ; third message

mov dx,offset RST
mov ah,9
int 21h

pop dx   ;restore the result number
mov ax,dx
mov bx,10000
div bx     ;I'm dividing the result number by 10000 to have the first number of the result number
           ;in AX register ( quotient) , the error message show up here
push dx
push ax

pop dx
add dl,30h
mov ah,2
int 21h

pop ax
mov bx,1000 ;deviding by 1000 to have the second number
div bx     ;same error
push dx
push ax
pop dx
add dl,30h
mov ah,2
int 21h

pop ax
mov bx,100
div bx
push dx
push ax
pop dx
add dl,30h
mov ah,2
int 21h

pop ax
mov bx,10
div bx
push dx
push ax
pop dx
add dl,30h
mov ah,2
int 21h

pop dx

add dl,30h
mov ah,2
int 21h```

答:
Try this change:

```<code>pop dx            ;restore the result number
mov ax,dx
xor dx,dx         ;; added this line to clear dx
mov bx,10000
div bx
</code>```

or it could be:

```<code>pop ax            ;; restore the result into ax
xor dx,dx         ;; added this line to clear dx
mov bx,10000
div bx
</code>```

Body:
Try this change:

pop dx            ;restore the result number
mov ax,dx
xor dx,dx         ;; added this line to clear dx
mov bx,10000
div bx

or it could be:

pop ax            ;; restore the result into ax
xor dx,dx         ;; added this line to clear dx
mov bx,10000
div bx


问:
getting the last item in a javascript object
If I have an object like:

```<code>{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }
</code>```

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?

答: No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot and at other times be banana and so on. If you need to rely on ordering, your best bet is to go with arrays.  The power of key-value data structures lies in accessing values by their keys, not in being able to get the nth item of the object.

Body:
If I have an object like:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?


问:
how to make this function more (time) efficient?
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio
</code>```

thx

答:
Let's clean it up a bit:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    words = string.split()

    words_counts = Counter(words)
</code>```

That's redundant! Replace 4 statements with 2:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)
</code>```

Next:

```<code>    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)
</code>```

I don't know what you think that code does. I hope you're not being tricky. But .keys returns an iterable, and X in <iterable> is WAY slower than X in <dict>. Also, note: you don't append anything if the innermost (weights[W][word] != 0) condition fails. That might be a bug, since you try to append 0 in another else condition. (I don't know what you're doing, so I'm just pointing it out.) And this is Python, not Perl or C or Java. So no parens required around if <test>:

Let's go with that:

```<code>    ratios = []

    for word in words:
        if word in weights[W] and word in rel_weight[W]:
            if weights[W][word] != 0:
                ratios.append(words_counts[word] * rel_weight[W][word] / weights[W][word])

        else:
            ratios.append(0)
</code>```

Next:

```<code>    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))
</code>```

You're trying to prevent dividing by zero. But you can use the truthiness of a list to check this, and avoid the comparison:

```<code>    if words:
        ratios = np.divide(ratios, float(len(words)))
</code>```

The rest is fine, but you don't need the variable.

```<code>    ratio = np.sum(ratios)

    return ratio
</code>```

With those mods applied, your function looks like this:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)
    ratios = []

    for word in words:
        if word in weights[W] and word in rel_weight[W]:
            if weights[W][word] != 0:
                ratios.append(words_counts[word] * rel_weight[W][word] / weights[W][word])

        else:
            ratios.append(0)

    if words:
        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)
    return ratio
</code>```

Looking at it at little harder, I see you're doing this:

```<code>word_counts = Counter(words)

for word in words:
    append(   word_counts[word] * ...)
</code>```

According to me, that means if "apple" appears 6 times, you are going to append 6*... to the list, once for each word. So you'll have 6 different occurrences of 6*... in your list. Are you sure that's what you want? Or should it be for word in word_counts to just iterate over the distinct words?

Another optimization is to remove lookups from inside your loop. You keep looking up weights[W] and rel_weight[W], even though the value of W never changes. Let's cache those values outside the loop. Also, let's cache a pointer to the ratios.append method.

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)
    ratios = []

    # Cache these values for speed in loop
    ratios_append = ratios.append
    weights_W = weights[W]
    rel_W = rel_weight[W]

    for word in words:
        if word in weights_W and word in rel_W:
            if weights_W[word] != 0:
                ratios_append(words_counts[word] * rel_W[word] / weights_W[word])

        else:
            ratios_append(0)

    if words:
        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)
    return ratio
</code>```

Try that, see how it works. Please look at the bold note above, and the questions. There might be bugs, there might be more ways to speed up.

Body:
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio

thx

Body:
Let's clean it up a bit:

def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    words = string.split()

    words_counts = Counter(words)

That's redundant! Replace 4 statements with 2:

def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)

Next:

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

I don't know what you think that code does. I hope you're not being tricky. But .keys returns an iterable, and X in <iterable> is WAY slower than X in <dict>. Also, note: you don't append anything if the innermost (weights[W][word] != 0) condition fails. That might be a bug, since you try to append 0 in another else condition. (I don't know what you're doing, so I'm just pointing it out.) And this is Python, not Perl or C or Java. So no parens required around if <test>:

Let's go with that:

    ratios = []

    for word in words:
        if word in weights[W] and word in rel_weight[W]:
            if weights[W][word] != 0:
                ratios.append(words_counts[word] * rel_weight[W][word] / weights[W][word])

        else:
            ratios.append(0)

Next:

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

You're trying to prevent dividing by zero. But you can use the truthiness of a list to check this, and avoid the comparison:

    if words:
        ratios = np.divide(ratios, float(len(words)))

The rest is fine, but you don't need the variable.

    ratio = np.sum(ratios)

    return ratio

With those mods applied, your function looks like this:

def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)
    ratios = []

    for word in words:
        if word in weights[W] and word in rel_weight[W]:
            if weights[W][word] != 0:
                ratios.append(words_counts[word] * rel_weight[W][word] / weights[W][word])

        else:
            ratios.append(0)

    if words:
        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)
    return ratio

Looking at it at little harder, I see you're doing this:

word_counts = Counter(words)

for word in words:
    append(   word_counts[word] * ...)

According to me, that means if "apple" appears 6 times, you are going to append 6*... to the list, once for each word. So you'll have 6 different occurrences of 6*... in your list. Are you sure that's what you want? Or should it be for word in word_counts to just iterate over the distinct words?

Another optimization is to remove lookups from inside your loop. You keep looking up weights[W] and rel_weight[W], even though the value of W never changes. Let's cache those values outside the loop. Also, let's cache a pointer to the ratios.append method.

def match_share(string, W, weights, rel_weight):

    words = string.split()
    words_counts = Counter(words)
    ratios = []

    # Cache these values for speed in loop
    ratios_append = ratios.append
    weights_W = weights[W]
    rel_W = rel_weight[W]

    for word in words:
        if word in weights_W and word in rel_W:
            if weights_W[word] != 0:
                ratios_append(words_counts[word] * rel_W[word] / weights_W[word])

        else:
            ratios_append(0)

    if words:
        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)
    return ratio

Try that, see how it works. Please look at the bold note above, and the questions. There might be bugs, there might be more ways to speed up.


答:
Use href instead of hash.

```<code> var url = window.location.href.split('?Token=')[1];
 // url = url.split('Token='); no need to split it again.

 function cambiarContrasena(usuario, completado, fallo) {
        apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
        completado,
        fallo);
 }
</code>```

Difference between hash and href is they return different part of URL. Here is the anatomy of URL:

(source: doepud.co.uk)

In this case window.location.hash returns #00h02m30s where windows.location.href returns entire URL.

Title: Uncaught TypeError: Cannot read property 'split' of undefined window location

Body:
Use href instead of hash.

 var url = window.location.href.split('?Token=')[1];
 // url = url.split('Token='); no need to split it again.

 function cambiarContrasena(usuario, completado, fallo) {
        apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
        completado,
        fallo);
 }

Difference between hash and href is they return different part of URL. Here is the anatomy of URL:

(source: doepud.co.uk)

In this case window.location.hash returns #00h02m30s where windows.location.href returns entire URL.

ContentLicense: CC BY-SA 4.0


问:
Mosquitto not working over TLS on Raspberry Pi
I have installed Mosquitto on a brand new Raspberry Pi. OS is Raspbian.
I followed the instructions on the Owntracks website.

The broker is listening on port 1883 on localhost. Using a username and password I can run mosquitto_sub in one ssh session to the Pi, and receive messages sent by mosquitto_pub from another ssh session.

The broker is also listening on port 8883. I created certificates using the script in the Owntracks repository.

When I run mosquitto_pub on the Pi, using the hostname or IP-address I get an error "Error: Connection refused".
When I use localhost or 127.0.0.1 the error is "A TLS error occurred.".

If I run mosquitto_pub on my desktop computer (which is in the same LAN as the Pi), the error is "Connection refused". The command I run here is

mosquitto_pub -t owntracks/test -m Test -h pi1 --cafile ca.crt

where pi1 is the hostname of the Pi running the broker. The ca.crt file is copied from the Pi to the desktop computer.

The Mosquitto log is not showing why the connections are refused.

The TLS setup in the Mosquitto config looks like this:

listener 1883 127.0.0.1

listener 8883

cafile /etc/mosquitto/ca_certificates/ca.crt

certfile /etc/mosquitto/certs/server.crt

keyfile /etc/mosquitto/certs/server.key

require_certificate false

What is wrong in my setup?

答:
if you try to use TLS with mosquitto
you must add this option to your command "-p 8883" to indicate the port
and you don't need to  put "-h localhost or pi " because you use the client command mosquitto_pub in the same machine that run mosquitto broker
then your command we'll be :
"mosquitto_pub -d -u username -P password -t /path/to/the/topic --cafile /path/to/the/certificate -p 8883
don't forgot to comment this line

listener 1883

in your mosquitto.conf