问:
Creating an Angular 5 component in execution time, after lazy-loading its dependencies
I'm trying to do something that may not be quite common. I'm trying to leverage Angular at its finest without needing many external dependencies, but for requirements reasons, I have to use one very specific library for date range picking (this one), but it uses JQuery and Moment.js, aswell Bootstrap's CSS (but this one is already added).

In this case, I could simple load JQuery and Moment.js in the page, but that doesn't seem to be an intelligent approach: the bundle size would get bigger, and I have to optimize this app as much as I can.

Then, I came in to an idea: why not lazy-load these dependencies, and then instantiate my component? Seems like a good approach, right?

I'm using a provider that lets me include in the document scripts from a CDN, and it's working well. But now, I have to somehow insert this daterangepicker component, in execution time, when both libraries have loaded and resolved their promises.

Current status:

1 - I've got this parent class, which loads my dependencies (JQuery and Moment.js) on execution time:

```<code>import { Component, OnInit } from '@angular/core';
import { LibraryLazyLoader } from '../../../providers/library_lazy_loader';
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';

@Component({
  selector: 'date-selector',
  templateUrl: './date-selector.component.html',
  styleUrls: ['./date-selector.component.css'],
  providers: [LibraryLazyLoader]
})
export class DateSelectorComponent implements OnInit {

  isLoaded = false;

  constructor(
    private libraryLoader:LibraryLazyLoader,
    private loadingSpinner:Ng4LoadingSpinnerService
  ){
    this.loadingSpinner.show();
    this.libraryLoader.loadJs('https://code.jquery.com/jquery-3.2.1.min.js')
        .subscribe(() => {
          console.log("JQuery included");
          this.libraryLoader.loadJs('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js')
            .subscribe(() => {
              console.log("Moment.js included");
              this.loadingSpinner.hide();
              this.isLoaded = true;
            })
         })
  }

  ngOnInit() {

  }

}
</code>```

2 - It's template is just like this:

```<code><button>Load js</button>
<div *ngIf="isLoaded">
  <input daterangepicker>
</div>
</code>```

The idea is, when both libraries are loaded, the isLoaded boolean should provoke the view to update with the daterangepicker directive correctly loading, and permitting me using the component.

Thing is, this doesn't work. And though I'm not going to use this in the project, I'm very curious about how it could work, since it could permit us build much more optimized pages! Lazy loading modules are nice, but the next step is to lazy load components, I think. Someone correct me if this approach is not good, but I think it can be a really good improvement to Angular.

So, any ideas?

答:
Just as an idea, you could add a guard to the route which loads the scripts and once the scripts are loaded the component can be loaded.

e.g. extending the Angular documentation example. You could just add a guard to resolve the dependencies before navigating to the view which needs them

```<code>@Injectable()
class TeamResolver implements Resolve<any> {

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    return Promise.all([
import("https://code.jquery.com/jquery-3.2.1.min.js"),
import("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js")
])
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}
</code>```

Also, I am not sure what the issue is with your example above?  As a guess, I would say that you are seeing nothing happen and I would say that is down to needing to let Angular know to run the cycle again. Maybe try

```<code>setTimeout(() => {
   this.loadingSpinner.hide();
   this.isLoaded = true;
})
</code>```

Body:
I'm trying to do something that may not be quite common. I'm trying to leverage Angular at its finest without needing many external dependencies, but for requirements reasons, I have to use one very specific library for date range picking (this one), but it uses JQuery and Moment.js, aswell Bootstrap's CSS (but this one is already added).

In this case, I could simple load JQuery and Moment.js in the page, but that doesn't seem to be an intelligent approach: the bundle size would get bigger, and I have to optimize this app as much as I can.

Then, I came in to an idea: why not lazy-load these dependencies, and then instantiate my component? Seems like a good approach, right?

I'm using a provider that lets me include in the document scripts from a CDN, and it's working well. But now, I have to somehow insert this daterangepicker component, in execution time, when both libraries have loaded and resolved their promises.

Current status:

1 - I've got this parent class, which loads my dependencies (JQuery and Moment.js) on execution time:

import { Component, OnInit } from '@angular/core';
import { LibraryLazyLoader } from '../../../providers/library_lazy_loader';
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';

@Component({
  selector: 'date-selector',
  templateUrl: './date-selector.component.html',
  styleUrls: ['./date-selector.component.css'],
  providers: [LibraryLazyLoader]
})
export class DateSelectorComponent implements OnInit {

  isLoaded = false;

  constructor(
    private libraryLoader:LibraryLazyLoader,
    private loadingSpinner:Ng4LoadingSpinnerService
  ){
    this.loadingSpinner.show();
    this.libraryLoader.loadJs('https://code.jquery.com/jquery-3.2.1.min.js')
        .subscribe(() => {
          console.log("JQuery included");
          this.libraryLoader.loadJs('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js')
            .subscribe(() => {
              console.log("Moment.js included");
              this.loadingSpinner.hide();
              this.isLoaded = true;
            })
         })
  }

  ngOnInit() {

  }

}

2 - It's template is just like this:

<button>Load js</button>

  <input daterangepicker>

The idea is, when both libraries are loaded, the isLoaded boolean should provoke the view to update with the daterangepicker directive correctly loading, and permitting me using the component.

Thing is, this doesn't work. And though I'm not going to use this in the project, I'm very curious about how it could work, since it could permit us build much more optimized pages! Lazy loading modules are nice, but the next step is to lazy load components, I think. Someone correct me if this approach is not good, but I think it can be a really good improvement to Angular.

So, any ideas?

Body:
Just as an idea, you could add a guard to the route which loads the scripts and once the scripts are loaded the component can be loaded.

e.g. extending the Angular documentation example. You could just add a guard to resolve the dependencies before navigating to the view which needs them

@Injectable()
class TeamResolver implements Resolve<any> {

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    return Promise.all([
import("https://code.jquery.com/jquery-3.2.1.min.js"),
import("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js")
])
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

Also, I am not sure what the issue is with your example above?  As a guess, I would say that you are seeing nothing happen and I would say that is down to needing to let Angular know to run the cycle again. Maybe try

setTimeout(() => {
   this.loadingSpinner.hide();
   this.isLoaded = true;
})


来源: stackexchange

问:
Why does my custom spaCy entity type get detected?
I am writing a spaCy program for which I want to define a custom named entity tag. Following the example here, I add a label called MY_NEW_LABEL to the pipeline.

```<code>import spacy

nlp = spacy.load("en_core_web_lg")

ner = nlp.get_pipe("ner")
new_label = "MY_NEW_LABEL"
ner.add_label(new_label)

documents_path = "my_document.txt"
document = nlp(open(documents_path).read())
print([e for e in document.ents if e.label_ == new_label])
</code>```

When I run the above program it prints out a list of entities labeled with MY_NEW_LABEL. I don't see how this is possible because I never do anything with the label.

Clearly I'm misunderstanding how to work with custom entity tags, but I can't figure out why this would be happening from the documentation. Can anyone tell me why my program doesn't print out an empty list?

答: This is unexpected behavior. I opened it as spaCy issue 1697: Custom Entity Labels Are Erroneously Detected.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am writing a spaCy program for which I want to define a custom named entity tag. Following the example here, I add a label called MY_NEW_LABEL to the pipeline.

import spacy

nlp = spacy.load("en_core_web_lg")

ner = nlp.get_pipe("ner")
new_label = "MY_NEW_LABEL"
ner.add_label(new_label)

documents_path = "my_document.txt"
document = nlp(open(documents_path).read())
print([e for e in document.ents if e.label_ == new_label])

When I run the above program it prints out a list of entities labeled with MY_NEW_LABEL. I don't see how this is possible because I never do anything with the label.

Clearly I'm misunderstanding how to work with custom entity tags, but I can't figure out why this would be happening from the documentation. Can anyone tell me why my program doesn't print out an empty list?


问:
Docker And Chef union, difference
What is the common part and the differences between docker and chef?

As I understand, docker can include chef, but actually I don't have an exact example how do the related to each other...

答:
Chef is a configuration management software. It allows you to automate things like provision, manage, and configure infrastructure. You basically have a central place to manage your infrastructure as code. Think of it as a tool that can:

Interact with multiple infrastructure provisioners (VMWare, AWS, ...)

Manage and Install software on machines

Deploy and start applications
...

Docker on the other hand is quite different. Simply put Docker is a technology to package your application with all of its dependencies in a sandbox which allows you to run the container anywhere since it is self-contained.

As I understand, docker can include chef, but actually I don't have an exact example how do the related to each other...

Nowadays it is very popular to package and distribute applications in docker container. Chef is also a program which can be packaged in a docker container. In fact the docker images for Chef already exist on Dockerhub. You can get
Chef by running the docker container. This will make it easy to get Chef up and running without having to directly install it on your machine. This is what is meant by "docker can include chef".

On the other hand, a Docker container is also a runnable software from the persective of the OS. You can tell Chef to also run a docker container on a machine that chef is managing.

In conclusion, there is no overlap between Docker and Chef. Both tools are used side by side, each for a different purpose. Chef is for managing infrastructure and machines, whereas docker is for packaging, shipping and deploying applications in containers.

Title: Docker And Chef union, difference


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Proofs are programs.

Formal verification of programs is a huge research area.  (See, for example, the group at Carnegie Mellon.)

Many complex programs have been verified; for example, see this kernel written in Haskell (repaired 404 link is for seL4, see also the moved to location and the project's website).

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?

OwnerDisplayName: A. Rex

ContentLicense: CC BY-SA 4.0


问:
How to create fields in Pivot Table that return a blank if there is an error?
I am creating a new field in a pivot table with the percent change formula

```<code>=C1/F1-1
</code>```

However, there are some blanks in my pivot table which causes my pivot table to look a little messy because you cannot divide by 0. I get the #DIV/0! error. How do I write a formula so the cell that reads the #DIV/0! error would return a blank?

Thanks,

G

答:
Right click on any entry in the pivot table and select PivotTable options.

Select the 'Layout & Format' tab, and then under the heading 'format' make sure to check the 'for error values show'. Now simply leave it blank or feel free to enter anything else you want.

Click 'OK' to apply the settings.

Hope I helped!

Body:
I am creating a new field in a pivot table with the percent change formula

=C1/F1-1

However, there are some blanks in my pivot table which causes my pivot table to look a little messy because you cannot divide by 0. I get the #DIV/0! error. How do I write a formula so the cell that reads the #DIV/0! error would return a blank?

Thanks,

G


问:
Mac OS X and multiple Java versions
How can I install an additional java on MacOS?  I installed jdk8 and that works fine. But now I need a jdk7 installation for development purposes. When trying to install the old version via DMG file, i get a warning, that there is already a newer version of java installed and the installer quits.

```<code>    /usr/libexec/java_home -verbose
    Matching Java Virtual Machines (1):
        1.8.0_20, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home

       /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home
</code>```

How to install jdk7 in addition to this one?

答:
For macOS Sierra 420

This guide was cobbled together from various sources (replies above as well as other posts), and works perfect.

0. If you haven't already, install homebrew.

See https://brew.sh/

1. Install jenv

```<code>brew install jenv
</code>```

2. Add jenv to the bash profile

```<code>if which jenv > /dev/null; then eval "$(jenv init -)"; fi
</code>```

3. Add jenv to your path

```<code>export PATH="$HOME/.jenv/shims:$PATH"
</code>```

4. Tap "homebrew/cask-versions"

FYI: "Tap" extends brew's list of available repos it can install, above and beyond brew's default list of available repos.

```<code>brew tap homebrew/cask-versions
</code>```

5. Install the latest version of java

```<code>brew install java --cask
</code>```

6. Install java 6 (or 7 or 8 whatever you need)

```<code>brew install java6 --cask
#brew install java7 --cask
#brew install java8 --cask
</code>```

? Maybe close and restart Terminal so it sees any new ENV vars that got setup.

7. Review Installations

All Java version get installed here: /Library/Java/JavaVirtualMachines lets take a look.

```<code>ls -la /Library/Java/JavaVirtualMachines
</code>```

8. Add each path to jenv one-at-a-time.

We need to add "/Contents/Home" to the version folder.
WARNING: Use the actual paths on your machine... these are just EXAMPLE's

```<code>jenv add /Library/Java/JavaVirtualMachines/1.6.0___EXAMPLE___/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk___EXAMPLE___/Contents/Home
</code>```

9. Check if jenv registered OK

```<code>jenv versions
</code>```

10. Set java version to use (globably)

Where XX matches one of the items in the versions list above.

```<code>jenv global XX
</code>```

Check java version

```<code>if which jenv > /dev/null; then eval "$(jenv init -)"; fi
</code>```0

Check jenv versions

Should also indicate the current version being used with an asterisk.

```<code>if which jenv > /dev/null; then eval "$(jenv init -)"; fi
</code>```1

DONE

Quick future reference

To change java versions

... See the list of available java versions

```<code>if which jenv > /dev/null; then eval "$(jenv init -)"; fi
</code>```2

... then, where XX matches an item in the list above

```<code>jenv global XX
</code>```

Title: Mac OS X and multiple Java versions

Body:
How can I install an additional java on MacOS?  I installed jdk8 and that works fine. But now I need a jdk7 installation for development purposes. When trying to install the old version via DMG file, i get a warning, that there is already a newer version of java installed and the installer quits.

    /usr/libexec/java_home -verbose
    Matching Java Virtual Machines (1):
        1.8.0_20, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home

       /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home

How to install jdk7 in addition to this one?

Body:
For macOS Sierra 420

This guide was cobbled together from various sources (replies above as well as other posts), and works perfect.

0. If you haven't already, install homebrew.

See https://brew.sh/

1. Install jenv

brew install jenv

2. Add jenv to the bash profile

if which jenv > /dev/null; then eval "$(jenv init -)"; fi

3. Add jenv to your path

export PATH="$HOME/.jenv/shims:$PATH"

4. Tap "homebrew/cask-versions"

FYI: "Tap" extends brew's list of available repos it can install, above and beyond brew's default list of available repos.

brew tap homebrew/cask-versions

5. Install the latest version of java

brew install java --cask

6. Install java 6 (or 7 or 8 whatever you need)

brew install java6 --cask
#brew install java7 --cask
#brew install java8 --cask

? Maybe close and restart Terminal so it sees any new ENV vars that got setup.

7. Review Installations

All Java version get installed here: /Library/Java/JavaVirtualMachines lets take a look.

ls -la /Library/Java/JavaVirtualMachines

8. Add each path to jenv one-at-a-time.

We need to add "/Contents/Home" to the version folder.
WARNING: Use the actual paths on your machine... these are just EXAMPLE's

jenv add /Library/Java/JavaVirtualMachines/1.6.0___EXAMPLE___/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk___EXAMPLE___/Contents/Home

9. Check if jenv registered OK

jenv versions

10. Set java version to use (globably)

Where XX matches one of the items in the versions list above.

jenv global XX

Check java version

java -version

Check jenv versions

Should also indicate the current version being used with an asterisk.

jenv versions

DONE

Quick future reference

To change java versions

... See the list of available java versions

jenv versions

... then, where XX matches an item in the list above

jenv global XX


问:
Reading Messy SAS Data
How can I read this -

```<code>    C 303 102 140 B 293 C 399 B 450 233 456
450 A 289 282 555
</code>```

like this -

```<code>Group Score
    C 303
    C 102
    C 140
    B 293
    C 399
    B 450
    B 233
    B 456
    B 450
    A 289
    A 282
    A 555
</code>```

In SAS? I have tried the @'character' column pointer, which I cant seem to get right. This is the code so far :( -

```<code>data OUTCOMES;
infile 'testscores.txt';
input @'C' SCORES; Run;
</code>```

答:
Coo:

The double ampersand (@@) operator for held input looks good [pun intended] for scanning inputs across line boundaries.

Construct an example external data file:

```<code>filename haveFile temp;

data _null_;
  file haveFile;
  put "    C 303 102 140 B 293 C 399 B 450 233 456";
  put "450 A 289 282 555";
run;
</code>```

Read from the file, one token at a time.

```<code>data have ;
  attrib
    token group length=$10
    score length=8
  ;

  retain group;

  infile haveFile ;

  input token @@;
  score = input (token, ?? 12.);  * check if token can be interpreted as a number, the ?? modifier prevents errors and notes in the log;

  if missing (score) and token ne '.' then
    group = token;
  else
    output;
run;
</code>```

Title: Reading Messy SAS Data

Body:
How can I read this -

    C 303 102 140 B 293 C 399 B 450 233 456
450 A 289 282 555

like this -

Group Score
    C 303
    C 102
    C 140
    B 293
    C 399
    B 450
    B 233
    B 456
    B 450
    A 289
    A 282
    A 555

In SAS? I have tried the @'character' column pointer, which I cant seem to get right. This is the code so far :( -

data OUTCOMES;
infile 'testscores.txt';
input @'C' SCORES; Run;

Body:
Coo:

The double ampersand (@@) operator for held input looks good [pun intended] for scanning inputs across line boundaries.

Construct an example external data file:

filename haveFile temp;

data _null_;
  file haveFile;
  put "    C 303 102 140 B 293 C 399 B 450 233 456";
  put "450 A 289 282 555";
run;

Read from the file, one token at a time.

data have ;
  attrib
    token group length=$10
    score length=8
  ;

  retain group;

  infile haveFile ;

  input token @@;
  score = input (token, ?? 12.);  * check if token can be interpreted as a number, the ?? modifier prevents errors and notes in the log;

  if missing (score) and token ne '.' then
    group = token;
  else
    output;
run;


问:
How can I use IStringLocalizer<T> with {}.en.resx in my console app?
I've got a .NET Core Console App that shares some common libraries with my ASP.NET Core App.  I need to add Globalization to the common project and in ASP.NET I can easily create a new .resx file with the language some.en.resx

At the moment, I can register my service, and it is calling the StringLocalizer class but not returning the localised string.  I managed to get it working by removing the .en from the file, but then that breaks my ASP.NET project.

Its like I need to register a default Language somewhere, but I can't work out where.

```<code>class Program
{
    static void Main(string[] args)
    {
        ServiceCollection serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient<MyService>();
        serviceCollection.AddSingleton<LoggerFactory>();

        serviceCollection
            .AddLogging()
            .AddLocalization();

        ServiceProvider buildServiceProvider = serviceCollection.BuildServiceProvider();
        MyService myService = buildServiceProvider.GetService<MyService>();
        string greeting = myService.GetGreeting();
        Console.WriteLine(greeting);
        Console.ReadKey();
    }
}

public class MyService
{
    private readonly IStringLocalizer<MyService> _stringLocalizer;

    public MyService(IStringLocalizer<MyService> stringLocalizer)
    {
        _stringLocalizer = stringLocalizer;
    }

    public string GetGreeting()
    {
        return _stringLocalizer.GetString("Greeting");
    }
}
</code>```

Is there any way I can do this?

答: I haven't managed to find a way of repeating the behaviour of ASP.NET.  I've had to accept that I can't have .en.resx files and luckily with a Culture of "en" ASP.NET uses the default .resx files</p>

Body:
I've got a .NET Core Console App that shares some common libraries with my ASP.NET Core App.  I need to add Globalization to the common project and in ASP.NET I can easily create a new .resx file with the language some.en.resx

At the moment, I can register my service, and it is calling the StringLocalizer class but not returning the localised string.  I managed to get it working by removing the .en from the file, but then that breaks my ASP.NET project.

Its like I need to register a default Language somewhere, but I can't work out where.

class Program
{
    static void Main(string[] args)
    {
        ServiceCollection serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient<MyService>();
        serviceCollection.AddSingleton<LoggerFactory>();

        serviceCollection
            .AddLogging()
            .AddLocalization();

        ServiceProvider buildServiceProvider = serviceCollection.BuildServiceProvider();
        MyService myService = buildServiceProvider.GetService<MyService>();
        string greeting = myService.GetGreeting();
        Console.WriteLine(greeting);
        Console.ReadKey();
    }
}

public class MyService
{
    private readonly IStringLocalizer<MyService> _stringLocalizer;

    public MyService(IStringLocalizer<MyService> stringLocalizer)
    {
        _stringLocalizer = stringLocalizer;
    }

    public string GetGreeting()
    {
        return _stringLocalizer.GetString("Greeting");
    }
}

Is there any way I can do this?


问:
How to get only head and tail text of some DOMNode?
How can I get only head and tail text of nodes in DOMDocument?

Example, in this sample code I don't want to see contents of  tag:

```<code>$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    echo 'nodeValue: '.$node->nodeValue."\n";
    echo 'textContent:'.$node->textContent."\n";
}
</code>```

答:
As an alternative you could also use DOMXPath and an xpath expression to get the text:

```<code>$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

$xpath = new DOMXPath($dom);
$elements = $xpath->query('/root/test/text()');

foreach ($elements as $element) {
    echo $element->nodeValue;
}
</code>```

Demo

Body:
How can I get only head and tail text of nodes in DOMDocument?

Example, in this sample code I don't want to see contents of  tag:

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text some bold text tail text</test>
</root>
');

foreach ($dom->getElementsByTagName('test') as $node) {
    echo 'nodeValue: '.$node->nodeValue."\n";
    echo 'textContent:'.$node->textContent."\n";
}

Body:
As an alternative you could also use DOMXPath and an xpath expression to get the text:

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<root>
  <test>head text <b>some bold text</b> tail text</test>
</root>
');

$xpath = new DOMXPath($dom);
$elements = $xpath->query('/root/test/text()');

foreach ($elements as $element) {
    echo $element->nodeValue;
}

Demo


问:
Get result of Drop Down menu to run another query
I am trying to resubmit my webpage through javascript based on the results of a change to a drop down menu. The drop down menu is created through an SQL query.

HTML/PHP

```<code><td> Workorder/IO: <select id = "WOIODD" name="WO/IO" onchange="getVal()">
<?php
foreach($WoIo as $workorder)
  {
    echo '<option>'.$workorder.'</option>';
  }
?>
</select>
</td>
</tr>
<?php $currentWo=($_GET['cwo']); ?>
</code>```

JAVASCRIPT

```<code> function getVal()
    {
        var currentVal = document.getElementById('WOIODD').value;
        location.href="?cwo="+currentVal;
    }
</code>```

The problem is document.getElementById.value is returning nothing. The value IS NOT null, but nothing is being returned. When I tried to fix the javascript, alert(currentVal) displayed a blank box, even after it was run conditionally with no null value. I need to be able to run another query based on the option chosen in the Work Order dropdown menu.

Any ideas on why this happening, how to fix, or even an alternative method all together?

Thank you,
Joshua

答:
Problem was solved.
First the java script was change to

```<code> function getVal(dropdown)
{
    var currentVal = dropdown.value;

    location.href="?cwo="+currentVal;
}
</code>```

Then the HTML/PHP was changed to

```<code><td> Workorder/IO: <select id = "WOIODD" name="WO/IO" onchange="getVal(this)">
<?php
foreach($WoIo as $workorder)
   {
  echo '<option value="'.$workorder.'">'.$workorder.'</option>';
  }
 ?>
</code>```

Basically it was NOT assessing each option the value so I explicitly assessed each value.

Thank you to everyone's comments it helped point me in the right direction

Body:
I am trying to resubmit my webpage through javascript based on the results of a change to a drop down menu. The drop down menu is created through an SQL query.

HTML/PHP

 Workorder/IO: <select id = "WOIODD" name="WO/IO" onchange="getVal()">
<?php
foreach($WoIo as $workorder)
  {
    echo '<option>'.$workorder.'</option>';
  }
?>
</select>

<?php $currentWo=($_GET['cwo']); ?>

JAVASCRIPT

 function getVal()
    {
        var currentVal = document.getElementById('WOIODD').value;
        location.href="?cwo="+currentVal;
    }

The problem is document.getElementById.value is returning nothing. The value IS NOT null, but nothing is being returned. When I tried to fix the javascript, alert(currentVal) displayed a blank box, even after it was run conditionally with no null value. I need to be able to run another query based on the option chosen in the Work Order dropdown menu.

Any ideas on why this happening, how to fix, or even an alternative method all together?

Thank you,
Joshua

Body:
Problem was solved.
First the java script was change to

 function getVal(dropdown)
{
    var currentVal = dropdown.value;

    location.href="?cwo="+currentVal;
}

Then the HTML/PHP was changed to

<td> Workorder/IO: <select id = "WOIODD" name="WO/IO" onchange="getVal(this)">
<?php
foreach($WoIo as $workorder)
   {
  echo '<option value="'.$workorder.'">'.$workorder.'</option>';
  }
 ?>

Basically it was NOT assessing each option the value so I explicitly assessed each value.

Thank you to everyone's comments it helped point me in the right direction


问:
How to show symfony validation errors?
I try to visualize my error messages from the validator.
When i write the following example:-

```<code>{{ form_errors(form.pGWeek) }}
</code>```

it works fine and i get the message. But my form has 200 fields and so it's not practical.

So i want to iterate over an Array with all messages, at the end of the form like this:

```<code>{% if form.name.vars.errors|length > 0 %}
  <ul class="form-errors name">
   {% for error in form.name.vars.errors %}
        {{ error }}
 {% endfor %}
  </ul>
{% endif %}
</code>```

But i did not get some messages. As well i tried some another versions.. but nothing worked. I'm using Symfony 2.7.

Can give me somebody a tip?

Thanks for a short feedback.

答:
You can make that loop and condition in your controller using dependency injector, and then in your view you iterate that array of errors and put it into a div o wherever you want, I guess there is something like this:

```<code>$errors = $this->get('validator')->validate(yourObject);
        if (!empty($errors)) {
            foreach ($errors as $error)
                throw new \Exception($error->getMessage());
        }
</code>```

That is if you want to stop the process and get an Exception, but you want to show that errors, then you make something similar, you only needs to delete that foreach and render your twig template and give it the $errors variable, in your template then you only need to make a for loop for get the errors!

Title: How to show symfony validation errors?

Body:
I try to visualize my error messages from the validator.
When i write the following example:-

{{ form_errors(form.pGWeek) }}

it works fine and i get the message. But my form has 200 fields and so it's not practical.

So i want to iterate over an Array with all messages, at the end of the form like this:

{% if form.name.vars.errors|length > 0 %}

   {% for error in form.name.vars.errors %}
        {{ error }}
 {% endfor %}

{% endif %}

But i did not get some messages. As well i tried some another versions.. but nothing worked. I'm using Symfony 2.7.

Can give me somebody a tip?

Thanks for a short feedback.

Body:
You can make that loop and condition in your controller using dependency injector, and then in your view you iterate that array of errors and put it into a div o wherever you want, I guess there is something like this:

$errors = $this->get('validator')->validate(yourObject);
        if (!empty($errors)) {
            foreach ($errors as $error)
                throw new \Exception($error->getMessage());
        }

That is if you want to stop the process and get an Exception, but you want to show that errors, then you make something similar, you only needs to delete that foreach and render your twig template and give it the $errors variable, in your template then you only need to make a for loop for get the errors!


问:
Finding id's not in other table SQL
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

```<code>`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`
</code>```

答:
The easy way to do this is:

```<code>select id from [VBSTEST].[dbo].[CUSTOMER]
except
select id from [VMFG9].[dbo].[CUSTOMER];
</code>```

You should also find that this kind of query is faster too.

Apart from being much longer, I think that there is an error in your query.  Since null never equals anything else, it doesn't even equal null, then your condition:

```<code>where v9.id is null
</code>```

means that the condition

```<code>v9.id = v6.[id]
</code>```

can never be true.

Title: Finding id's not in other table SQL

Body:
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`

Body:
The easy way to do this is:

select id from [VBSTEST].[dbo].[CUSTOMER]
except
select id from [VMFG9].[dbo].[CUSTOMER];

You should also find that this kind of query is faster too.

Apart from being much longer, I think that there is an error in your query.  Since null never equals anything else, it doesn't even equal null, then your condition:

where v9.id is null

means that the condition

v9.id = v6.[id]

can never be true.


问:
Why does C# array not have Count property?

Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

```<code>double[] test = new double[1];
</code>```

support the Length property to get the size of the array. But arrays also implement an IList interface:

```<code>IList<double> list = test;
</code>```

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

答:
Simply, they chose to call it Length, and implement Count via explicit interface implementation -something like:

```<code>int ICollection.Count { get { return Length; } }
</code>```

Body:
Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

double[] test = new double[1];

support the Length property to get the size of the array. But arrays also implement an IList interface:

IList<double> list = test;

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

Body:
Simply, they chose to call it Length, and implement Count via explicit interface implementation -something like:

int ICollection.Count { get { return Length; } }


问:
IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))
when deleting users with schedule_files I got this:

IntegrityError at /admin/auth/user/166/delete/
  (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))')

My models are:

```<code>class ScheduleFile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    added = models.DateTimeField(default=django.utils.timezone.now)

    def __str__(self):
        return '[User ID: {}] {}'.format(str(self.user.id), self.user.username)
</code>```

And

```<code>class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3)
    exclude_fba_from_chatzos = models.BooleanField(default=False)
    schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True)
    status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED)
</code>```

And User(AbstractUser)
I decided to create pre_delete signal and delete relative objects of schedule model:

```<code>@receiver(pre_delete, dispatch_uid='User')
def user_del(sender, instance, **kwargs):
    i = instance
    events = VacationEvent.objects.filter(user_id=166)
    schedule = prefetch_related_objects(events, 'schedule_file__user')
    schedule.delete()

# instance.user.schedulefile_set.clear()
# qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file')
# qs.delete()

# b = ScheduleFile.objects.filter(user_id=166)
# e = VacationEvent.objects.filter(user_id=166)
# e.schedule_file.remove(b)
</code>```

But it returns 'NoneType' object has no attribute 'delete'. How can I do it right? Thanks for any help.

答:
you can not delete ScheduleFile because it's primary key is required by
VacationEvent so you have to delete VacationEvent record before the
ScheduleFile model this can be done in several way by signal or overriding
delete function on ScheduleFile model

example:

```<code>def delete(self, using=None):
    if self.schedule_file:
        self.schedule_file.delete()
    super(ScheduleFile, self).delete(using)
</code>```

Body:
when deleting users with schedule_files I got this:

IntegrityError at /admin/auth/user/166/delete/
  (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))')

My models are:

class ScheduleFile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    added = models.DateTimeField(default=django.utils.timezone.now)

    def __str__(self):
        return '[User ID: {}] {}'.format(str(self.user.id), self.user.username)

And

class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3)
    exclude_fba_from_chatzos = models.BooleanField(default=False)
    schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True)
    status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED)

And User(AbstractUser)
I decided to create pre_delete signal and delete relative objects of schedule model:

@receiver(pre_delete, dispatch_uid='User')
def user_del(sender, instance, **kwargs):
    i = instance
    events = VacationEvent.objects.filter(user_id=166)
    schedule = prefetch_related_objects(events, 'schedule_file__user')
    schedule.delete()

# instance.user.schedulefile_set.clear()
# qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file')
# qs.delete()

# b = ScheduleFile.objects.filter(user_id=166)
# e = VacationEvent.objects.filter(user_id=166)
# e.schedule_file.remove(b)

But it returns 'NoneType' object has no attribute 'delete'. How can I do it right? Thanks for any help.

Body:
you can not delete ScheduleFile because it's primary key is required by
VacationEvent so you have to delete VacationEvent record before the
ScheduleFile model this can be done in several way by signal or overriding
delete function on ScheduleFile model

example:

def delete(self, using=None):
    if self.schedule_file:
        self.schedule_file.delete()
    super(ScheduleFile, self).delete(using)


问:
Scrollview not working properly on iPad in xcode(iOS)
Recently, i've been building and app which requires a scrollview, for all the content to fit. I've had a few difficulties creating my scrollview. I've tried a few different methods for building it, but ended up building it in storyboard with autolayout. I've set the height of the view controller to 1000, and therefore also the simulated size to freeform. The width of the content view inside the scrollview, I've to the same as the view which contains the scrollview.

The hierarchy goes like this:

-View controller scene

-Top layout guide

-Bottom layout guide

-View

-Scroll view

-Content view

-Label with text here

-Constraints

-And so on

I've been replicating the process in this link, to create the scrollview:
https://www.ralfebert.de/snippets/ios/auto-layout-recipes/uiscrollview-storyboard/

When running the application on the simulator, I get the following result:
The scrollview is not working properly on the iPad. It seems like the scrollview doesn't adapt to the changes in the width, which happens when its ran on an iPad, since it's bigger. When the app is ran on the iPad, the scrollview stays the same width as if it were shown on the iPhone.

This is how it looks in the editor. The view controller on the left is the view controller which has the scrollview implemented, and the one on the right doesn't. The first image shows the storyboard, when I view it with the iPhone 8, and the second image is when I view it with an 9,7" iPad:

It would be greatly appreciated if anyone could give me a hint to whats going on!

EDIT:
Left side is what it looks like, and right side is what it should look like:

答:
Add the UIScrollView to your main view

Set Top, Left, Right, Bottom constraints all to Zero

Add a UILabel inside the scroll view

Set number of lines to Zero

Set Top, Left, Right, Bottom constraints all to Zero

Set the label's width constraint equal to the scroll view's width

That should do it :)

This will keep the label's text aligned to the top of the scroll view. If you add enough text to fill more than the full screen, it will scroll vertically.


问:
PHP: Distance between 2 addresses with Google Maps?
I'm trying to get the distance between 2 locations through Google Maps API using the below PHP script, which apparently works (their hosted test url works, added below), but when I use the code they provide on my own server it doesn't seem to do anything... PHP is working just fine by the way, and it doesn't seem to be doing anything funny that would require me turning something on in my ini file.

I'm not sure what the issue is... been at this all day.

Any ideas? Maybe it is my .ini?

I'm not sure what I'm missing here. I'm using a shared host, but that shouldn't make a difference. It should technically work as is, any way that is why I'm here - I need some insight.

Website with source code:
http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/#comment-24117

Their live demo: http://demos.codexworld.com/distance-between-two-addresses-google-maps-api-php/

My full test code:

```<code><?php
/**
*
* Author: CodexWorld
* Function Name: getDistance()
* $addressFrom => From address.
* $addressTo => To address.
* $unit => Unit type.
*
**/

    function getDistance($addressFrom, $addressTo, $unit){
        //Change address format
        $formattedAddrFrom = str_replace(' ','+',$addressFrom);
        $formattedAddrTo = str_replace(' ','+',$addressTo);

        //Send request and receive json data
        $geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
        $outputFrom = json_decode($geocodeFrom);
        $geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
        $outputTo = json_decode($geocodeTo);

        //Get latitude and longitude from geo data
        $latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
        $longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
        $latitudeTo = $outputTo->results[0]->geometry->location->lat;
        $longitudeTo = $outputTo->results[0]->geometry->location->lng;

        //Calculate distance from latitude and longitude
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
        if ($unit == "K") {
            return ($miles * 1.609344).' km';
        } else if ($unit == "N") {
            return ($miles * 0.8684).' nm';
        } else {
            return $miles.' mi';
        }
    }

    if (!empty($_POST['addrFrom']) && !empty($_POST['addrTo'])) {
        $addressFrom = htmlspecialchars($_POST['addrFrom']);
        $addressTo = htmlspecialchars($_POST['addrTo']);
        $distance = getDistance($addressFrom, $addressTo, "K");
        $success = true;
    }
?>

<!DOCTYPE html>
<html>
<head></head>
<body>
    <form method="post">
        <p class="distance"><span>Distance:<?php if ($success == true) { echo ' ' . $distance; } ?></span> </p>
        <p><label>Address From</label><input type="text" name="addrFrom" value=""></p>
        <p><label>Address To</label><input type="text" name="addrTo" value=""></p>
        <p><input type="submit" name="submit" value="Calculate Distance"></p>
    </form>
</body>
</html>
</code>```

答:
Try This - slightly modified your way of doing it..:</p>

```<code><?php
/**
* Author: CodexWorld
* Function Name: getDistance()
* $addressFrom => From address.
* $addressTo => To address.
* $unit => Unit type.
*
**/

    function getDistance($addressFrom, $addressTo, $unit){
        //Change address format
        $formattedAddrFrom = str_replace(' ','+',$addressFrom);
        $formattedAddrTo = str_replace(' ','+',$addressTo);

        //Send request and receive json data
        $geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
        $outputFrom = json_decode($geocodeFrom);
        $geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
        $outputTo = json_decode($geocodeTo);

        //Get latitude and longitude from geo data
        $latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
        $longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
        $latitudeTo = $outputTo->results[0]->geometry->location->lat;
        $longitudeTo = $outputTo->results[0]->geometry->location->lng;

        //Calculate distance from latitude and longitude
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
        if ($unit == "K") {
            return ($miles * 1.609344).' km';
        } else if ($unit == "N") {
            return ($miles * 0.8684).' nm';
        } else {
            return $miles.' mi';
        }
    }

    if (isset($_POST['submit'])) {
        $addressFrom = htmlspecialchars($_POST['addrFrom']);
        $addressTo = htmlspecialchars($_POST['addrTo']);
        $distance = getDistance($addressFrom, $addressTo, "K");
        echo $distance;
    }

?>

<!DOCTYPE html>
<html>
<head></head>
<body>
    <form method="post">
        <p><label>Address From</label><input type="text" name="addrFrom" value=""></p>
        <p><label>Address To</label><input type="text" name="addrTo" value=""></p>
        <p><input type="submit" name="submit" value="Calculate Distance"></p>
    </form>
</body>
</html>
</code>```

Body:
I'm trying to get the distance between 2 locations through Google Maps API using the below PHP script, which apparently works (their hosted test url works, added below), but when I use the code they provide on my own server it doesn't seem to do anything... PHP is working just fine by the way, and it doesn't seem to be doing anything funny that would require me turning something on in my ini file.

I'm not sure what the issue is... been at this all day.

Any ideas? Maybe it is my .ini?

I'm not sure what I'm missing here. I'm using a shared host, but that shouldn't make a difference. It should technically work as is, any way that is why I'm here - I need some insight.

Website with source code:
http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/#comment-24117

Their live demo: http://demos.codexworld.com/distance-between-two-addresses-google-maps-api-php/

My full test code:

<?php
/**
*
* Author: CodexWorld
* Function Name: getDistance()
* $addressFrom => From address.
* $addressTo => To address.
* $unit => Unit type.
*
**/

    function getDistance($addressFrom, $addressTo, $unit){
        //Change address format
        $formattedAddrFrom = str_replace(' ','+',$addressFrom);
        $formattedAddrTo = str_replace(' ','+',$addressTo);

        //Send request and receive json data
        $geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
        $outputFrom = json_decode($geocodeFrom);
        $geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
        $outputTo = json_decode($geocodeTo);

        //Get latitude and longitude from geo data
        $latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
        $longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
        $latitudeTo = $outputTo->results[0]->geometry->location->lat;
        $longitudeTo = $outputTo->results[0]->geometry->location->lng;

        //Calculate distance from latitude and longitude
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
        if ($unit == "K") {
            return ($miles * 1.609344).' km';
        } else if ($unit == "N") {
            return ($miles * 0.8684).' nm';
        } else {
            return $miles.' mi';
        }
    }

    if (!empty($_POST['addrFrom']) && !empty($_POST['addrTo'])) {
        $addressFrom = htmlspecialchars($_POST['addrFrom']);
        $addressTo = htmlspecialchars($_POST['addrTo']);
        $distance = getDistance($addressFrom, $addressTo, "K");
        $success = true;
    }
?>

<!DOCTYPE html>

    <form method="post">

Distance:<?php if ($success == true) { echo ' ' . $distance; } ?>

Address From<input type="text" name="addrFrom" value="">

Address To<input type="text" name="addrTo" value="">

<input type="submit" name="submit" value="Calculate Distance">

    </form>

Body:
Try This - slightly modified your way of doing it..:

<?php
/**
* Author: CodexWorld
* Function Name: getDistance()
* $addressFrom => From address.
* $addressTo => To address.
* $unit => Unit type.
*
**/

    function getDistance($addressFrom, $addressTo, $unit){
        //Change address format
        $formattedAddrFrom = str_replace(' ','+',$addressFrom);
        $formattedAddrTo = str_replace(' ','+',$addressTo);

        //Send request and receive json data
        $geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
        $outputFrom = json_decode($geocodeFrom);
        $geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
        $outputTo = json_decode($geocodeTo);

        //Get latitude and longitude from geo data
        $latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
        $longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
        $latitudeTo = $outputTo->results[0]->geometry->location->lat;
        $longitudeTo = $outputTo->results[0]->geometry->location->lng;

        //Calculate distance from latitude and longitude
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
        if ($unit == "K") {
            return ($miles * 1.609344).' km';
        } else if ($unit == "N") {
            return ($miles * 0.8684).' nm';
        } else {
            return $miles.' mi';
        }
    }

    if (isset($_POST['submit'])) {
        $addressFrom = htmlspecialchars($_POST['addrFrom']);
        $addressTo = htmlspecialchars($_POST['addrTo']);
        $distance = getDistance($addressFrom, $addressTo, "K");
        echo $distance;
    }

?>

<!DOCTYPE html>
<html>
<head></head>
<body>
    <form method="post">
        <p><label>Address From</label><input type="text" name="addrFrom" value=""></p>
        <p><label>Address To</label><input type="text" name="addrTo" value=""></p>
        <p><input type="submit" name="submit" value="Calculate Distance"></p>
    </form>
</body>
</html>


问:
How to map array elements to select binary tree nodes?
I have an array of length n. I want to sort the array elements such that my new array elements are like

```<code>arr[0] = arr[n/2]
arr[1] = arr[n/4]
arr[2] = arr[3n/4]
arr[3] = arr[n/8]
arr[4] = arr[3n/8]
arr[5] = arr[5n/8]
</code>```

and so on...

What I have tried, using vectors.

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

bool myfunc (int l, int r)
{
        int m = (l+r)/2;
        return m;
}

int main()
{
    std::vector<int> myvector = {3,1,20,9,7,5,6,22,17,14,4};
    std::sort (myvector.begin(), myvector.end(), myfunc);

    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    return 0;

}
</code>```

So, for an array for length 11, I expect

```<code>myvector[0] = arr[5]
myvector[1] = arr[2]
myvector[2] = arr[8]
myvector[3] = arr[0]
myvector[4] = arr[3]
myvector[5] = arr[6]
myvector[6] = arr[9]
myvector[7] = arr[1]
myvector[8] = arr[4]
myvector[9] = arr[7]
myvector[10] = arr[10]
</code>```

My question is, what should be my function definition of myfunc, such that I get expected output

```<code>bool myfunc (int l, int r)
    {
            int m = (l+r)/2;
            //Cant figure out this logic
    }
</code>```

I have tried debugger, but that definitely doesnt help in defining the function! Any clues would be appreciated.

答:
It appears you want a binary search tree (BST) stored in array form, using the same internal represenation which is often used to store a heap.

The expected output is an array such that the one based indexes form a tree, where for any one-based index x, the left node of x is at index 2*x, and the right node of x is at index 2*x+1. Additionally, there are no gaps, meaning every member of the array is used, up to N. (It is a complete binary tree) Since c++ uses zero-based indexing, you need to be careful with this one-based index.

That way of representing a tree is very good for storing a heap data structure, but very bad for a binary search tree where you want to insert things, thus breaking the completeness, and forcing you into a very expensive rebalance.

You asked for a mapping from the sorted array index to this array format. We can build it using a recursive function. This recursive function will take exactly the same amount of work as it would have taken to build the binary tree, and in fact, it is nearly identical to how you would write that function, so this is not an optimal approach. We are doing as much work as the entire problem requires, just to come up with an intermediary step.

The special note here is that we do not want the median. We want to ensure that the left subtree forms a perfect binary tree, so that it fits in the array with no gaps. Therefore, it must have a power of 2, minus 1 nodes. The right subtree can be merely complete.

```<code>int log2(int n) {
    if (n > 1)
        return 1 + log2(n / 2);
    return 0;
}

// current_position is the index in bst_indexes
void build_binary_tree_index_mapping(std::vector<int> &bst_indexes, int lower, int upper, int current_position=0) {
    if (current_position >= bst_indexes.size())
        return;

    int power = log2(upper - lower);
    int number = 1 << (power); // left subtree must be perfect
    int root = lower + number - 1;

    // fill current_position
    // std::cout << current_position << " = " << root << std::endl;
    bst_indexes[current_position] = root;

    if (lower < root) {
        // fill left subtree
        int left_node_position = (current_position + 1) * 2 - 1;
        build_binary_tree_index_mapping(bst_indexes, lower, root - 1, left_node_position);
    }

    if (root < upper) {
        // fill right subtree
        int right_node_position = (current_position + 1) * 2 + 1 - 1;
        build_binary_tree_index_mapping(bst_indexes, root + 1, upper, right_node_position);
    }
}
</code>```

This gives me {7, 3, 9, 1, 5, 8, 10, 0, 2, 4, 6} as the index mapping. It differs from yours because you left spaces in the lower left of the tree, and I am ensuring that the array is completely filled, so I had to shift the bottom row over, then the BST property required reordering everything.

As a side note, in order to use this mapping, you first must sort the data, which is also about the same complexity as the whole problem.

Additionally, the sorted vector already gives you a superior way to do a binary search, using std::binary_search http://en.cppreference.com/w/cpp/algorithm/binary_search.

Body:
I have an array of length n. I want to sort the array elements such that my new array elements are like

arr[0] = arr[n/2]
arr[1] = arr[n/4]
arr[2] = arr[3n/4]
arr[3] = arr[n/8]
arr[4] = arr[3n/8]
arr[5] = arr[5n/8]

and so on...

What I have tried, using vectors.

#include <iostream>
#include <algorithm>
#include <vector>

bool myfunc (int l, int r)
{
        int m = (l+r)/2;
        return m;
}

int main()
{
    std::vector<int> myvector = {3,1,20,9,7,5,6,22,17,14,4};
    std::sort (myvector.begin(), myvector.end(), myfunc);

    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    return 0;

}

So, for an array for length 11, I expect

myvector[0] = arr[5]
myvector[1] = arr[2]
myvector[2] = arr[8]
myvector[3] = arr[0]
myvector[4] = arr[3]
myvector[5] = arr[6]
myvector[6] = arr[9]
myvector[7] = arr[1]
myvector[8] = arr[4]
myvector[9] = arr[7]
myvector[10] = arr[10]

My question is, what should be my function definition of myfunc, such that I get expected output

bool myfunc (int l, int r)
    {
            int m = (l+r)/2;
            //Cant figure out this logic
    }

I have tried debugger, but that definitely doesnt help in defining the function! Any clues would be appreciated.

Body:
It appears you want a binary search tree (BST) stored in array form, using the same internal represenation which is often used to store a heap.

The expected output is an array such that the one based indexes form a tree, where for any one-based index x, the left node of x is at index 2*x, and the right node of x is at index 2*x+1. Additionally, there are no gaps, meaning every member of the array is used, up to N. (It is a complete binary tree) Since c++ uses zero-based indexing, you need to be careful with this one-based index.

That way of representing a tree is very good for storing a heap data structure, but very bad for a binary search tree where you want to insert things, thus breaking the completeness, and forcing you into a very expensive rebalance.

You asked for a mapping from the sorted array index to this array format. We can build it using a recursive function. This recursive function will take exactly the same amount of work as it would have taken to build the binary tree, and in fact, it is nearly identical to how you would write that function, so this is not an optimal approach. We are doing as much work as the entire problem requires, just to come up with an intermediary step.

The special note here is that we do not want the median. We want to ensure that the left subtree forms a perfect binary tree, so that it fits in the array with no gaps. Therefore, it must have a power of 2, minus 1 nodes. The right subtree can be merely complete.

int log2(int n) {
    if (n > 1)
        return 1 + log2(n / 2);
    return 0;
}

// current_position is the index in bst_indexes
void build_binary_tree_index_mapping(std::vector<int> &bst_indexes, int lower, int upper, int current_position=0) {
    if (current_position >= bst_indexes.size())
        return;

    int power = log2(upper - lower);
    int number = 1 << (power); // left subtree must be perfect
    int root = lower + number - 1;

    // fill current_position
    // std::cout << current_position << " = " << root << std::endl;
    bst_indexes[current_position] = root;

    if (lower < root) {
        // fill left subtree
        int left_node_position = (current_position + 1) * 2 - 1;
        build_binary_tree_index_mapping(bst_indexes, lower, root - 1, left_node_position);
    }

    if (root < upper) {
        // fill right subtree
        int right_node_position = (current_position + 1) * 2 + 1 - 1;
        build_binary_tree_index_mapping(bst_indexes, root + 1, upper, right_node_position);
    }
}

This gives me {7, 3, 9, 1, 5, 8, 10, 0, 2, 4, 6} as the index mapping. It differs from yours because you left spaces in the lower left of the tree, and I am ensuring that the array is completely filled, so I had to shift the bottom row over, then the BST property required reordering everything.

As a side note, in order to use this mapping, you first must sort the data, which is also about the same complexity as the whole problem.

Additionally, the sorted vector already gives you a superior way to do a binary search, using std::binary_search http://en.cppreference.com/w/cpp/algorithm/binary_search.


问:
Undefined method `detailsFileTag' for nil:NilClass
My aim is to test a design pattern—in this case the decorator pattern.

I have taken the below code from the lib/ folder and controller folder.
The library file here has a BasicTag class which is inherited by class TaggingDecor and an another class DescriptionDecor.

Now all these three classes have a common function called detailsForTag.
This function when is called from controller file as listed below.
The error is

undefined method `detailsFileTag' for nil:NilClass

and the error line is as tagged below in the code.

```<code># the concrete component we would like to decorate
class BasicTag
    def initialize()
        @init_basicTag = "File with no tags"
    end

    # getter method
    def detailsFileTag
        return " test from BasicTag....."
    end
end

# decorator class -- this serves as the superclass for all the concrete decorators
# the base/super class decorator (i.e. no actual decoration yet), each concrete decorator (i.e. subclass) will add its own decoration
class TaggingDecor
    def initialize(r_file)
        @r_file = r_file
        @aTagg = "no tag added"
        @aDescTag = "no description added"
    end

    # override the details method to include the description of the extra feature
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

# a concrete decorator
class TagDec < TaggingDecor
    def initialize(r_file)
        super(r_file)
        @aTagg = "no tag added"
        @aDescTag = "tagdec description added"
    end

# override the details method to include the description
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

# another concrete decorator
class DescriptionDec < TaggingDecor
    def initialize(r_file)
        super(r_file)
        @aTagg = "no tag added"
        @aDescTag = "descriptiondec description added"
    end

# override the details method to include the description
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

============================= controller file ============================

  # POST /file_taggings
  # POST /file_taggings.json
  def create
    @file_tagging = FileTagging.new(file_tagging_params)

#####################################################
#rails g scaffold fileTagging filename:string filetag:string filedescription:string
# information For logging the file details into table
  @file_tagging.filename = params[:file_tagging][:filename]
  @file_tagging.filetag = params[:file_tagging][:filetag]
  @file_tagging.filedescription = params[:file_tagging][:filedescription]

########################################################################
# information For logging the file details
  # create an instance/object of a BasicTag
    myTagg = BasicTag.new

  # add the extra features to the new car
    if params[:file_tagging][:filetag].to_s.length > 0 then
      myTagg = TagDec.new(myTagg)
    end

    #if params[:file_tagging][:description].to_s.length > 0 then
    #  myTagg = DescriptionDec.new(myTagg)
    #end

    ## populate the Description details - By calling the BASE class and SUPER class as stated above.
#Error is here for the call myTagg.detailsFileTag !
    @file_tagging.filedescription =  myTagg.detailsFileTag

   # retrieve the instance/object of the MyLogger class
  logger = MyLogger.instance
  logger.logInformation("A new file details are: " +  @file_tagging.filesdescription)
  logger.logInformation("A new file details are: ")
#####################################################

    respond_to do |format|
      if @file_tagging.save
        format.html { redirect_to @file_tagging, notice: 'File tagging was successfully created.' }
        format.json { render :show, status: :created, location: @file_tagging }
      else
        format.html { render :new }
        format.json { render json: @file_tagging.errors, status: :unprocessable_entity }
      end
    end
  end
============================================================
</code>```

答:
Yes correct its a nill object. So I had by mistake deleted out the ruby file in the model folder, which was created by the scaffold.
model>> FileTagging.rb.</p>

Body:
My aim is to test a design pattern—in this case the decorator pattern.

I have taken the below code from the lib/ folder and controller folder.
The library file here has a BasicTag class which is inherited by class TaggingDecor and an another class DescriptionDecor.

Now all these three classes have a common function called detailsForTag.
This function when is called from controller file as listed below.
The error is

undefined method `detailsFileTag' for nil:NilClass

and the error line is as tagged below in the code.

# the concrete component we would like to decorate
class BasicTag
    def initialize()
        @init_basicTag = "File with no tags"
    end

    # getter method
    def detailsFileTag
        return " test from BasicTag....."
    end
end

# decorator class -- this serves as the superclass for all the concrete decorators
# the base/super class decorator (i.e. no actual decoration yet), each concrete decorator (i.e. subclass) will add its own decoration
class TaggingDecor
    def initialize(r_file)
        @r_file = r_file
        @aTagg = "no tag added"
        @aDescTag = "no description added"
    end

    # override the details method to include the description of the extra feature
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

# a concrete decorator
class TagDec < TaggingDecor
    def initialize(r_file)
        super(r_file)
        @aTagg = "no tag added"
        @aDescTag = "tagdec description added"
    end

# override the details method to include the description
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

# another concrete decorator
class DescriptionDec < TaggingDecor
    def initialize(r_file)
        super(r_file)
        @aTagg = "no tag added"
        @aDescTag = "descriptiondec description added"
    end

# override the details method to include the description
    def detailsFileTag
        return @aTagg + @aDescTag
    end
end

============================= controller file ============================

  # POST /file_taggings
  # POST /file_taggings.json
  def create
    @file_tagging = FileTagging.new(file_tagging_params)

#####################################################
#rails g scaffold fileTagging filename:string filetag:string filedescription:string
# information For logging the file details into table
  @file_tagging.filename = params[:file_tagging][:filename]
  @file_tagging.filetag = params[:file_tagging][:filetag]
  @file_tagging.filedescription = params[:file_tagging][:filedescription]

########################################################################
# information For logging the file details
  # create an instance/object of a BasicTag
    myTagg = BasicTag.new

  # add the extra features to the new car
    if params[:file_tagging][:filetag].to_s.length > 0 then
      myTagg = TagDec.new(myTagg)
    end

    #if params[:file_tagging][:description].to_s.length > 0 then
    #  myTagg = DescriptionDec.new(myTagg)
    #end

    ## populate the Description details - By calling the BASE class and SUPER class as stated above.
#Error is here for the call myTagg.detailsFileTag !
    @file_tagging.filedescription =  myTagg.detailsFileTag

   # retrieve the instance/object of the MyLogger class
  logger = MyLogger.instance
  logger.logInformation("A new file details are: " +  @file_tagging.filesdescription)
  logger.logInformation("A new file details are: ")
#####################################################

    respond_to do |format|
      if @file_tagging.save
        format.html { redirect_to @file_tagging, notice: 'File tagging was successfully created.' }
        format.json { render :show, status: :created, location: @file_tagging }
      else
        format.html { render :new }
        format.json { render json: @file_tagging.errors, status: :unprocessable_entity }
      end
    end
  end
============================================================


问:
How to get value of a cell at position (row,column) with openpyxl?
I'm using openpyxl to get a value of a cell at a specific position defined by row and column number.
Code from the documentation doesn't work.

Link to documentation:
http://openpyxl.readthedocs.io/en/default/tutorial.html#accessing-one-cell.

Code from documentation:

for i in range(1,101):
  ...        for j in range(1,101):
  ...            ws.cell(row=i,column=j)

Code gives this Exception:

warn("Using a coordinate with ws.cell is deprecated. Use ws[coordinate] instead")

答:
Use openpyxl.cell.cell.Cell.value as,

```<code>wb = load_workbook(file_name, read_only=True)
test_sheet = wb["Test"]
row = 1
column = 1
print(test_sheet<b>.cell(row, column).value</b>)</code>```

Body:
Use openpyxl.cell.cell.Cell.value as,

wb = load_workbook(file_name, read_only=True)
test_sheet = wb["Test"]
row = 1
column = 1
print(test_sheet.cell(row, column).value)


问:
XPath Query using NOT, not working
I'm trying to figure out how to selected all of the Suppliers who do not have TV as a product. I'd also like an explanation on the differences of your answer and what I have.
I have the following query written:

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier/Product[not(@name="TV")]/..')
FROM Tb_XPathQueryTable
</code>```

This is my table, plus a bunch of other Suppliers.

```<code><SuppliersList>
  <Supplier name="Joe">
    <City>Paris</City>
    <Product name="Airplane"/>
    <Product name="Milk"/>
    <Product name="TV"/>
    <Product name="Orange"/>
 </Supplier>
</code>```

答:
On your xpath you are selecting first the Product and then going to its parent, so it will match the specified example (because the TV Product has siblings that match the same parent).

This xpath should work:

```<code>/SuppliersList/Supplier[not(Product[@name="TV"])]
</code>```

As you can see, we are selecting Supplier which doesn't contain a Product child with name="TV"

Title: XPath Query using NOT, not working

Body:
I'm trying to figure out how to selected all of the Suppliers who do not have TV as a product. I'd also like an explanation on the differences of your answer and what I have.
I have the following query written:

SELECT XMLColumn.query('/SuppliersList/Supplier/Product[not(@name="TV")]/..')
FROM Tb_XPathQueryTable

This is my table, plus a bunch of other Suppliers.

<SuppliersList>
  <Supplier name="Joe">
    <City>Paris</City>
    <Product name="Airplane"/>
    <Product name="Milk"/>
    <Product name="TV"/>
    <Product name="Orange"/>
 </Supplier>

Body:
On your xpath you are selecting first the Product and then going to its parent, so it will match the specified example (because the TV Product has siblings that match the same parent).

This xpath should work:

/SuppliersList/Supplier[not(Product[@name="TV"])]

As you can see, we are selecting Supplier which doesn't contain a Product child with name="TV"


问:
In bootstrap datepicker change month event is not working
I have a booking availability checking section on my website. I used bootstrap datepicker.

When page loads first time, I am fetching some dates using jquery ajax & php from database to disable dates on datepicker calendar. So, I used setDatesDisabled. On first loads of datepicker it is works fine.

When I change month I am getting json response but dates are not disabled on datepicker. I have tried with changeMonth event but not working. Please help me to solve this issue

Json response

disableDates:["13.01.2018", "20.01.2018", "27.01.2018"]

```<code>$("#dateFrom").datepicker({
                autoclose: true,
                todayHighlight: true,
                format: 'dd.mm.yy',
                startDate: new Date()
            }).on('show', function(e) {
                $.ajax({
                    url: '/cabinowner/bookings/availability',
                    dataType: 'JSON',
                    type: 'POST'
                })
                    .done(function( response ) {
                        $("#dateFrom").datepicker('setDatesDisabled', response.disableDates);
                    })
                    .fail(function(response, jqxhr, textStatus, error) {
                    });
            });

            $("#dateFrom").datepicker().on('changeMonth', function(e) {
                $.ajax({
                    url: '/cabinowner/bookings/availability',
                    dataType: 'JSON',
                    type: 'POST',
                    data: { date : moment(e.date).format('YY-MM-DD') }
                })
                    .done(function( response ) {
                        // here response is getting but next month is not showing
                        $("#dateFrom").datepicker('setDatesDisabled', response.disableDates);
                    })
                    .fail(function(response, jqxhr, textStatus, error) {
                    });
            });

            $("#dateFrom").datepicker().on('changeDate', function(e) {
                var temp   = $(this).datepicker('getDate');
                var start  = new Date(temp);
                start.setDate(start.getDate() + 1); // Here date is setting greater than start date

                var end    = new Date(start);
                end.setDate(end.getDate() + 60);

                $("#dateTo").datepicker({
                    autoclose: true,
                    format: 'dd.mm.yy',
                    startDate: start,
                    endDate: end
                });
            });
</code>```

答:
I think you got the reference wrong here, you are adding 3 different datepickers on the same element. This should work :</p>

```<code>var datePicker = $("#dateFrom").datepicker({
    autoclose: true,
    todayHighlight: true,
    format: 'dd.mm.yy',
    startDate: new Date()
});
datePicker.on('show', function (e) {
    $.ajax({
        url: '/cabinowner/bookings/availability',
        dataType: 'JSON',
        type: 'POST'
    })
        .done(function (response) {
            datePicker.setDatesDisabled(response.disableDates);
        })
        .fail(function (response, jqxhr, textStatus, error) {
        });
});

datePicker.on('changeMonth', function (e) {
    $.ajax({
        url: '/cabinowner/bookings/availability',
        dataType: 'JSON',
        type: 'POST',
        data: {date: moment(e.date).format('YY-MM-DD')}
    })
        .done(function (response) {
            // here response is getting but next month is not showing
            datePicker.setDatesDisabled(response.disableDates);
        })
        .fail(function (response, jqxhr, textStatus, error) {
        });
});

datePicker.on('changeDate', function (e) {
    var temp = $(this).datepicker('getDate');
    var start = new Date(temp);
    start.setDate(start.getDate() + 1); // Here date is setting greater than start date

    var end = new Date(start);
    end.setDate(end.getDate() + 60);

    $("#dateTo").datepicker({
        autoclose: true,
        format: 'dd.mm.yy',
        startDate: start,
        endDate: end
    });
});
</code>```

Body:
I have a booking availability checking section on my website. I used bootstrap datepicker.

When page loads first time, I am fetching some dates using jquery ajax & php from database to disable dates on datepicker calendar. So, I used setDatesDisabled. On first loads of datepicker it is works fine.

When I change month I am getting json response but dates are not disabled on datepicker. I have tried with changeMonth event but not working. Please help me to solve this issue

Json response

disableDates:["13.01.2018", "20.01.2018", "27.01.2018"]

$("#dateFrom").datepicker({
                autoclose: true,
                todayHighlight: true,
                format: 'dd.mm.yy',
                startDate: new Date()
            }).on('show', function(e) {
                $.ajax({
                    url: '/cabinowner/bookings/availability',
                    dataType: 'JSON',
                    type: 'POST'
                })
                    .done(function( response ) {
                        $("#dateFrom").datepicker('setDatesDisabled', response.disableDates);
                    })
                    .fail(function(response, jqxhr, textStatus, error) {
                    });
            });

            $("#dateFrom").datepicker().on('changeMonth', function(e) {
                $.ajax({
                    url: '/cabinowner/bookings/availability',
                    dataType: 'JSON',
                    type: 'POST',
                    data: { date : moment(e.date).format('YY-MM-DD') }
                })
                    .done(function( response ) {
                        // here response is getting but next month is not showing
                        $("#dateFrom").datepicker('setDatesDisabled', response.disableDates);
                    })
                    .fail(function(response, jqxhr, textStatus, error) {
                    });
            });

            $("#dateFrom").datepicker().on('changeDate', function(e) {
                var temp   = $(this).datepicker('getDate');
                var start  = new Date(temp);
                start.setDate(start.getDate() + 1); // Here date is setting greater than start date

                var end    = new Date(start);
                end.setDate(end.getDate() + 60);

                $("#dateTo").datepicker({
                    autoclose: true,
                    format: 'dd.mm.yy',
                    startDate: start,
                    endDate: end
                });
            });

Body:
I think you got the reference wrong here, you are adding 3 different datepickers on the same element. This should work :

var datePicker = $("#dateFrom").datepicker({
    autoclose: true,
    todayHighlight: true,
    format: 'dd.mm.yy',
    startDate: new Date()
});
datePicker.on('show', function (e) {
    $.ajax({
        url: '/cabinowner/bookings/availability',
        dataType: 'JSON',
        type: 'POST'
    })
        .done(function (response) {
            datePicker.setDatesDisabled(response.disableDates);
        })
        .fail(function (response, jqxhr, textStatus, error) {
        });
});

datePicker.on('changeMonth', function (e) {
    $.ajax({
        url: '/cabinowner/bookings/availability',
        dataType: 'JSON',
        type: 'POST',
        data: {date: moment(e.date).format('YY-MM-DD')}
    })
        .done(function (response) {
            // here response is getting but next month is not showing
            datePicker.setDatesDisabled(response.disableDates);
        })
        .fail(function (response, jqxhr, textStatus, error) {
        });
});

datePicker.on('changeDate', function (e) {
    var temp = $(this).datepicker('getDate');
    var start = new Date(temp);
    start.setDate(start.getDate() + 1); // Here date is setting greater than start date

    var end = new Date(start);
    end.setDate(end.getDate() + 60);

    $("#dateTo").datepicker({
        autoclose: true,
        format: 'dd.mm.yy',
        startDate: start,
        endDate: end
    });
});


问:
WAMP ignore my.ini
C:\wamp\bin\mysql\mysql5.6.17 has my.ini. I add text log=c:/wamp/logs/mysql_query.log but it's not working.

Any changes do not work. I tried to rename the file myblablabla.ini, but WAMP server successfully started. I think, he uses a different configuration file. How to find it?

Thanks for the help.

答:
The answer above is correct but not totally, at least for me.
I'm using wampserver 2.5 64bit.
I must add BOTH [wampmysqld64] and [mysqld64] section in my .ini file in order to make it works!

```<code>[wampmysqld64]
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

[mysqld64]
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
</code>```

Go to wamp icon and do like this:
1. Wamp > MySQL > MySQL console

Run select @@sql_mode; // check results

Wamp > MySQL > my.ini // edit file with the code I've mentioned above.

Restart wamp all services

Run select @@sql_mode; // check results, need to be:

+--------------------------------------------+
| @@sql_mode                                 |
+--------------------------------------------+
| NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+--------------------------------------------+

Title: WAMP ignore my.ini

Body:
The answer above is correct but not totally, at least for me.
I'm using wampserver 2.5 64bit.
I must add BOTH [wampmysqld64] and [mysqld64] section in my .ini file in order to make it works!

[wampmysqld64]
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

[mysqld64]
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Go to wamp icon and do like this:
1. Wamp > MySQL > MySQL console

Run select @@sql_mode; // check results

Wamp > MySQL > my.ini // edit file with the code I've mentioned above.

Restart wamp all services

Run select @@sql_mode; // check results, need to be:

+--------------------------------------------+
| @@sql_mode                                 |
+--------------------------------------------+
| NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+--------------------------------------------+


问:
printing from a ListView Javafx
I hava a javafx application where the user enters some details in test fields and it is shown on a listview. I now have a button to print using the printjob but everytime I hit the print button the printer prints garbage data like jhsjs6sh3#uhbsbkahi instead of the real values from the ListView. below is my codes for the print functon

```<code>public void print (final Node node) {
        Printer printer = Printer.getDefaultPrinter();
        PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
        final double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
        final double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
        node.getTransforms().add(new Scale(scaleX, scaleY));

        PrinterJob job =PrinterJob.createPrinterJob();
        if (job != null ){

            boolean success = job.printPage(node);
            System.out.println("printed");
            if (success){
                System.out.println(success);
                job.endJob();
            }
        }

    }
</code>```

@FXML

    private void printOps(ActionEvent event){

        print(billingDataList);

}

I use a MacBook for my development and HP printer.

答:
You will have to figure out the scaling. This prints using SnapShot and awt. Using code from here.

```<code>import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication61 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        ListView<String> list = new ListView<>();
        ObservableList<String> items = FXCollections.observableArrayList("A", "B", "C", "D");
        list.setItems(items);

        VBox root = new VBox();

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction((event) ->
        {
            WritableImage image = list.snapshot(new SnapshotParameters(), null);
            File file = new File("nodeImage.png");

            try
            {
                ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);

                Image imageToPrint = new Image(file.toURI().toString());
                BufferedImage bufferedImage = SwingFXUtils.fromFXImage(imageToPrint, null);
                printImage(bufferedImage);
            }
            catch (IOException ex)
            {
                System.out.println(ex.toString());
            }
        });

        root.getChildren().add(btn);
        root.getChildren().add(list);
        Scene scene = new Scene(root, 1080, 720);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    private void printImage(BufferedImage image)
    {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable((Graphics graphics, PageFormat pageFormat, int pageIndex) ->
        {
            // Get the upper left corner that it printable
            int x = (int) Math.ceil(pageFormat.getImageableX());
            int y = (int) Math.ceil(pageFormat.getImageableY());
            if (pageIndex != 0)
            {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
            return PAGE_EXISTS;
        });
        try
        {
            printJob.print();
        }
        catch (PrinterException e1)
        {
            e1.printStackTrace();
        }
    }
}
</code>```

Title: printing from a ListView Javafx

Body:
I hava a javafx application where the user enters some details in test fields and it is shown on a listview. I now have a button to print using the printjob but everytime I hit the print button the printer prints garbage data like jhsjs6sh3#uhbsbkahi instead of the real values from the ListView. below is my codes for the print functon

public void print (final Node node) {
        Printer printer = Printer.getDefaultPrinter();
        PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
        final double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
        final double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
        node.getTransforms().add(new Scale(scaleX, scaleY));

        PrinterJob job =PrinterJob.createPrinterJob();
        if (job != null ){

            boolean success = job.printPage(node);
            System.out.println("printed");
            if (success){
                System.out.println(success);
                job.endJob();
            }
        }

    }

@FXML

    private void printOps(ActionEvent event){

        print(billingDataList);

}

I use a MacBook for my development and HP printer.

Body:
You will have to figure out the scaling. This prints using SnapShot and awt. Using code from here.

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication61 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        ListView<String> list = new ListView<>();
        ObservableList<String> items = FXCollections.observableArrayList("A", "B", "C", "D");
        list.setItems(items);

        VBox root = new VBox();

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction((event) ->
        {
            WritableImage image = list.snapshot(new SnapshotParameters(), null);
            File file = new File("nodeImage.png");

            try
            {
                ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);

                Image imageToPrint = new Image(file.toURI().toString());
                BufferedImage bufferedImage = SwingFXUtils.fromFXImage(imageToPrint, null);
                printImage(bufferedImage);
            }
            catch (IOException ex)
            {
                System.out.println(ex.toString());
            }
        });

        root.getChildren().add(btn);
        root.getChildren().add(list);
        Scene scene = new Scene(root, 1080, 720);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    private void printImage(BufferedImage image)
    {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable((Graphics graphics, PageFormat pageFormat, int pageIndex) ->
        {
            // Get the upper left corner that it printable
            int x = (int) Math.ceil(pageFormat.getImageableX());
            int y = (int) Math.ceil(pageFormat.getImageableY());
            if (pageIndex != 0)
            {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
            return PAGE_EXISTS;
        });
        try
        {
            printJob.print();
        }
        catch (PrinterException e1)
        {
            e1.printStackTrace();
        }
    }
}


问:
htaccess block everything but index.php and folder public and files in it
I'm kinda new to htaccess, I'm trying to block everything but index.php, the folder public and the files it contain. I have googled around and got this so far. Its kinda working but it looks like the webserver dont have access to the files either. It opens index.php but no css,js or php files are included. I can also go to domain.com/folder/ and get to the index page but its empty i would want it to redirect to index.php if possible. And i also have no clue about how to open the public folder while everything else above is set. </p>

```<code>AuthType Basic
order allow,deny
<Files ~ "^(index\.php|)$">
  Allow from all
</Files>
<Files .htaccess>
  Order Allow,Deny
  Deny from all
</Files>

DirectoryIndex index.php
</code>```

答:
Replace all of your code with this mod_rewrite rule in your site root .htaccess:

```<code>DirectoryIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/(?:index\.php$|public/|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteRule . - [F]
</code>```

This rule will block everything except public/ folder, index.php or any other file ending with .css, .js, images etc.

Body:
I'm kinda new to htaccess, I'm trying to block everything but index.php, the folder public and the files it contain. I have googled around and got this so far. Its kinda working but it looks like the webserver dont have access to the files either. It opens index.php but no css,js or php files are included. I can also go to domain.com/folder/ and get to the index page but its empty i would want it to redirect to index.php if possible. And i also have no clue about how to open the public folder while everything else above is set.

AuthType Basic
order allow,deny
<Files ~ "^(index\.php|)$">
  Allow from all
</Files>
<Files .htaccess>
  Order Allow,Deny
  Deny from all
</Files>

DirectoryIndex index.php

Body:
Replace all of your code with this mod_rewrite rule in your site root .htaccess:

DirectoryIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/(?:index\.php$|public/|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteRule . - [F]

This rule will block everything except public/ folder, index.php or any other file ending with .css, .js, images etc.