问:
Django backwards foreign key manager
I am trying to dynamically get a model's backwards foreign key manager.

If I have:

```<code>class modelA(models.Model)
    name = models.CharField(max_length=100)

class modelB(models.Model)
    fk = models.ManyToManyField(modelA)
</code>```

From the docs I can see that I can get the backwards foreign key manager by doing:

```<code>a = modelB.modela_set
</code>```

in the shell this gives me

```<code>django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager
</code>```

with which I can do

```<code>a.all()
</code>```

and get a result.

However If I have the string 'modela' and I do:

```<code>a = getattr(modelB, 'modela_set')
</code>```

I will get

```<code>django.db.models.fields.related_descriptors.ManyToManyDescriptor
</code>```

and if i do:

```<code>a.all()
</code>```

I get an attribute error.

I do not understand why getattr() is behaving this way.

Is there a way to do this?

答:
It was a class vs instance issue.

```<code>getattr(modelB, 'modela_set')
</code>```

is different than:

```<code>a = ModelB.objects.get(pk=1)
getattr(a, 'modela_set')
</code>```

Title: Django backwards foreign key manager

Body:
I am trying to dynamically get a model's backwards foreign key manager.

If I have:

class modelA(models.Model)
    name = models.CharField(max_length=100)

class modelB(models.Model)
    fk = models.ManyToManyField(modelA)

From the docs I can see that I can get the backwards foreign key manager by doing:

a = modelB.modela_set

in the shell this gives me

django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager

with which I can do

a.all()

and get a result.

However If I have the string 'modela' and I do:

a = getattr(modelB, 'modela_set')

I will get

django.db.models.fields.related_descriptors.ManyToManyDescriptor

and if i do:

a.all()

I get an attribute error.

I do not understand why getattr() is behaving this way.

Is there a way to do this?

Body:
It was a class vs instance issue.

getattr(modelB, 'modela_set')

is different than:

a = ModelB.objects.get(pk=1)
getattr(a, 'modela_set')


来源: stackexchange

问:
How to accomplish this nl to br functionality in ASP.NET Core MVC?
In the past, in previous versions of MVC, in the need for one nl to br functionality in Razor Views, I used to implement the following nl to br HTML helper:

```<code>public static class FormatingHelpers
{
    public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
    {
        if (string.IsNullOrEmpty(text))
            return MvcHtmlString.Create(text);
        else
        {
            StringBuilder builder = new StringBuilder();
            string[] lines = text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                    builder.Append("<br/>");
                builder.Append(HttpUtility.HtmlEncode(lines[i]));
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}
</code>```

Now I tried that with ASP.NET Core MVC but it didn't work, the MvcHtmlString class doesn't exist.

In truth, I think that HTML helpers don't even exist anymore, replaced by tag helpers.

Anyway, how can this Nl2Br functionality be implement with ASP.NET Core MVC?

答:
Very similar to the proposal of Danny van der Kraan with slight changes for ASP.NET Core 1.1</p>

```<code>using System.Net;
using System.Text;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AppName.TagHelpers
{
    [HtmlTargetElement("nl2br", Attributes = "text")]
    public class Nl2brTagHelper : TagHelper
    {
        [HtmlAttributeName("text")]
        public string Text { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = string.Empty;

            StringBuilder builder = new StringBuilder();
            string[] lines = Text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                {
                    builder.Append("<br/>");
                }
                builder.Append(WebUtility.HtmlEncode(lines[i]));
            }

            output.Content.SetHtmlContent(builder.ToString());
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the past, in previous versions of MVC, in the need for one nl to br functionality in Razor Views, I used to implement the following nl to br HTML helper:

public static class FormatingHelpers
{
    public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
    {
        if (string.IsNullOrEmpty(text))
            return MvcHtmlString.Create(text);
        else
        {
            StringBuilder builder = new StringBuilder();
            string[] lines = text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                    builder.Append("
");
                builder.Append(HttpUtility.HtmlEncode(lines[i]));
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}

Now I tried that with ASP.NET Core MVC but it didn't work, the MvcHtmlString class doesn't exist.

In truth, I think that HTML helpers don't even exist anymore, replaced by tag helpers.

Anyway, how can this Nl2Br functionality be implement with ASP.NET Core MVC?

Body:
Very similar to the proposal of Danny van der Kraan with slight changes for ASP.NET Core 1.1

using System.Net;
using System.Text;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AppName.TagHelpers
{
    [HtmlTargetElement("nl2br", Attributes = "text")]
    public class Nl2brTagHelper : TagHelper
    {
        [HtmlAttributeName("text")]
        public string Text { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = string.Empty;

            StringBuilder builder = new StringBuilder();
            string[] lines = Text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                {
                    builder.Append("<br/>");
                }
                builder.Append(WebUtility.HtmlEncode(lines[i]));
            }

            output.Content.SetHtmlContent(builder.ToString());
        }
    }
}


问:
Python Scrapy - common way to configure scrapers
Python framework Scrapy works pretty well but I can not figure out how to configure spiders at runtime. Seems that all configuration should me made "statically" which is not handy. Awful design or I missed something?

For example I have a spider that requires difficult initialization routine.
I use my own scripts to obtain HTTP headers for crawling (cookies, user-agent etc.) - as it were logged-in user.
This takes one-two minute. After that these headers should be applied to all requests.

Right now I do this in __init__ method of the spider. But I can not set up User-Agent from the constructor of the spider. custom_settings must be set up as class variable. Therefore I have to use middleware to set up user agent for each request. This is an ugly solution.

Do we have some common pattern to init spiders - some kind of spider factory ? Smth like this:

```<code>class SpiderConfigurator:

    def __init__():
        ...

    def configureSpider(spider, environment):
        ...
        spider.setMyCustomSettings(arg1, arg2)
        ...
        environment.setMyCustomSettings(argName1, argValue1)
        environment.setMyCustomSettings('User-Agent', 'my value')
</code>```

答:
Scrapy allows to lounch crawling from the script: Run Scrapy from script Thanks to @paultrmbrth for this hint

But we can not init spider - we just pass spider class to Crawler instance and then crawler instantiates the object. What we can do - pass parameters for our spider`s constructor. Smth like this:

```<code>os.chdir(scrapyDir)
projectSettings = get_project_settings()
crawlerProcess = CrawlerProcess(projectSettings)
crawlerProcess.crawl(SpiderCls,
                     argumentName1=argumentValue1,
                     argumentName2=argumentValue2)
</code>```

Arguments argumentName1 and argumentName2 will be passed to the spider`s constructor.

ContentLicense: CC BY-SA 4.0

Body:
Python framework Scrapy works pretty well but I can not figure out how to configure spiders at runtime. Seems that all configuration should me made "statically" which is not handy. Awful design or I missed something?

For example I have a spider that requires difficult initialization routine.
I use my own scripts to obtain HTTP headers for crawling (cookies, user-agent etc.) - as it were logged-in user.
This takes one-two minute. After that these headers should be applied to all requests.

Right now I do this in __init__ method of the spider. But I can not set up User-Agent from the constructor of the spider. custom_settings must be set up as class variable. Therefore I have to use middleware to set up user agent for each request. This is an ugly solution.

Do we have some common pattern to init spiders - some kind of spider factory ? Smth like this:

class SpiderConfigurator:

    def __init__():
        ...

    def configureSpider(spider, environment):
        ...
        spider.setMyCustomSettings(arg1, arg2)
        ...
        environment.setMyCustomSettings(argName1, argValue1)
        environment.setMyCustomSettings('User-Agent', 'my value')

Body:
Scrapy allows to lounch crawling from the script: Run Scrapy from script Thanks to @paultrmbrth for this hint

But we can not init spider - we just pass spider class to Crawler instance and then crawler instantiates the object. What we can do - pass parameters for our spider`s constructor. Smth like this:

os.chdir(scrapyDir)
projectSettings = get_project_settings()
crawlerProcess = CrawlerProcess(projectSettings)
crawlerProcess.crawl(SpiderCls,
                     argumentName1=argumentValue1,
                     argumentName2=argumentValue2)

Arguments argumentName1 and argumentName2 will be passed to the spider`s constructor.


问:
Convert .dmp file to .hprof file
I have tried running the command

```<code>jmap -dump:format=b,file=jvm.hprof core.20170103.212745.20453.0007.dmp
</code>```

But i get an error

```<code>Error attaching to remote server: java.rmi.UnknownHostException: Unknown host: core.20170103.212745.20453.0007.dmp; nested exception is:
    java.net.UnknownHostException: core.20170103.212745.20453.0007.dmp
sun.jvm.hotspot.debugger.DebuggerException: java.rmi.UnknownHostException:
</code>```

What is the error? I tried putting it on a TomCat server and running it but still throws an error

答:
You are missing the "executable" parameter, so jmap thinks you're trying to connect to a remote host.
try something like:</p>

```<code>jmap -dump:format=b,file=jvm.hprof /usr/bin/java core.20170103.212745.20453.0007.dmp
</code>```

Title: Convert .dmp file to .hprof file

Body:
I have tried running the command

jmap -dump:format=b,file=jvm.hprof core.20170103.212745.20453.0007.dmp

But i get an error

Error attaching to remote server: java.rmi.UnknownHostException: Unknown host: core.20170103.212745.20453.0007.dmp; nested exception is:
    java.net.UnknownHostException: core.20170103.212745.20453.0007.dmp
sun.jvm.hotspot.debugger.DebuggerException: java.rmi.UnknownHostException:

What is the error? I tried putting it on a TomCat server and running it but still throws an error

Body:
You are missing the "executable" parameter, so jmap thinks you're trying to connect to a remote host.
try something like:

jmap -dump:format=b,file=jvm.hprof /usr/bin/java core.20170103.212745.20453.0007.dmp


问:
Angular 2 How do I call a service method when an observable changes/when a services returns new results?
I have a simple app component with a search input and an observable resultItems: Observable<Array<string>>; powered by a search service that returns results to the UI via *ngFor.  There is also a leaflet map that should render the locations of the results.  The search service works well and I can render the location of one result in the map onclick.   My question is:  What is the recommended way to call the map service mapResults every time the search service returns new results or the observable changes?  I can imagine how I could create a custom pipe that would iterate over the parks in the service results and call mapservice.mapResult but that seems odd since the pipe wouldn't return anything to the UI and I'm a little concerned with performance, understanding little about pure and impure pipes.  I have also seen mention of a process by which you subscribe to changes of an observable, but I'm lost with the semantics and changes among API versions.

I apologize if this is a problem of poor design. I only have a few weeks of Angular learning and I admittedly haven't read the documentation thoroughly. Please point any and all issues you see.

simple Search Service

```<code>import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';

@Injectable()
export default class ParkSearchService {

    constructor(private jsonp: Jsonp) { }

    search(parkSearchterm: string) {
        var search = new URLSearchParams()
        search.set('q', 'PARK_NAME:*' + parkSearchterm+'*');
        search.set('wt', 'json');

        search.set('json.wrf','JSONP_CALLBACK')

        var test = this.jsonp
            .get('http://parksearch/parks_full/select?', { search })
            .map((response) => response.json()['response']['docs']);

        return test

    }
}
</code>```

exert from app.component.html

```<code>  <md-card *ngFor="let item of resultItems | async; let i = index"
                 class="search-result"
                 [ngClass]="{ 'selected-result': selectedIndex === i }">
            <md-card-header class="clickable"
                            (click)="showBoundary(item)"
                            md-tooltip="Zoom to park">
                <md-card-title>{{item.PARK_NAME}}</md-card-title>
            </md-card-header>
            <md-card-content style="height: 75px; overflow-y: auto">
                <button md-button
                        color="primary"
                        md-tooltip="more info"
                        (click)="openDtl(item.PARK_HOME_PAGE_URL)">
                    <md-icon>info</md-icon>
                    <span>Details...</span>
                </button>
                <button md-button
                        color="primary"
                        md-tooltip="open park website"
                        (click)="openParkURL(item.PARK_HOME_PAGE_URL)">
                    <md-icon>web</md-icon>
                    <span>WebSite</span>
                </button>
                Amenties: {{ item.AMEN_LIST }}
            </md-card-content>
        </md-card>
</code>```

app.component.ts  (forgot to include)

```<code> export class AppComponent {
    private selectedIndex: number;
    public events: any[] = [];
    //park search items
    resultItems: Observable<Array<string>>;
    parkSearchterm = new FormControl();

    //setup resultitems
    ngOnInit() {
            this.mapService.initialize();
            this.resultItems = this.parkSearchterm.valueChanges
                .debounceTime(400)
                .distinctUntilChanged()
                .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm));
</code>```

map service:

```<code>//Thanks for the help getting started https://github.com/haoliangyu
import { Injectable } from '@angular/core';
import { Map, GeoJSON } from 'leaflet';

@Injectable()
export default class MapService {
    public map: Map;
    private currentLayer: GeoJSON;
    private resultsLayer: any;
    private resultfeatureCollection: any;

    constructor() {

    }

    initialize() {
        if (this.map) {
            return;
        }

        this.map = L.map('map', {
            zoomControl: true,
            zoom: 6,
            minZoom: 3,
            maxZoom: 19
        });

        L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
        }).addTo(this.map);

        L.control.scale().addTo(this.map);

        //Add the results layer
        this.resultsLayer = L.geoJSON(this.resultfeatureCollection, {
            style: () => {
                return {
                    color: '#ff00005',
                    fillColor: '#3F51B5'
                };
            }
        }).addTo(this.map);
    }
    mapResults(park) {
        //update the restults layer
        let resultfeatureCollection: GeoJSON.FeatureCollection<any> = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: "Polygon",
                        coordinates: JSON.parse(park.BBOX[0])
                    },
                    properties: {
                        name: 'test'
                    }
                }
            ]
        };

        this.resultsLayer.addData(resultfeatureCollection);
        this.map.fitBounds(this.resultsLayer.getBounds());
    }

}
</code>```

答:
You are very close to what you need: You already have an observable stream created for your results, called resultItems, that is right. Then on your template, when you use it through the async pipe what Angular does internally is subscribes to this stream to get its values.

So if you want to "also" map when resultItems yields is by subscribing to it by yourself as well. There's a catch though: by default every subscription duplicates the workload for the stream, meaning that every time the user makes a new search it would run the API call twice: 1 for the async subscription and another one for your .subscribe.

The way to resolve that is by using .publish(): What this allows is to share the result of an stream between many subscribers, so your code would look like this:

```<code>ngOnInit() {
    this.mapService.initialize();
    this.resultItems = this.parkSearchterm.valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm))
        .publish();
    // With publish() we are sharing the items from this stream to all of their subscribers
    // We just need to tell it to do the "first subscription"
    this.resultConnection = this.resultItems.connect();
    // This "resultConnection" is the base subscription... We will have to dispose it in our ngOnDestroy method or we might get memory leaks

    // Now we can tell the map service to update when we get a value:
    this.resultItems.subscribe((park) => this.mapService.mapResults(park));
    // (Not sure if the data types are correct, I assume you can map them)
    // When `async` calls .subscribe() to do his job, we won't get duplicate API calls thanks to .publish()
}
</code>```

To clarify, what connect() does is subscribe to the original stream, and start forwarding the values recieved to the subscribers of the published stream (this.resultItems). Now you are the owner of that subscription, so you are responsible of disposing it whenever you don't need more searches.

Body:
I have a simple app component with a search input and an observable resultItems: Observable<Array<string>>; powered by a search service that returns results to the UI via *ngFor.  There is also a leaflet map that should render the locations of the results.  The search service works well and I can render the location of one result in the map onclick.   My question is:  What is the recommended way to call the map service mapResults every time the search service returns new results or the observable changes?  I can imagine how I could create a custom pipe that would iterate over the parks in the service results and call mapservice.mapResult but that seems odd since the pipe wouldn't return anything to the UI and I'm a little concerned with performance, understanding little about pure and impure pipes.  I have also seen mention of a process by which you subscribe to changes of an observable, but I'm lost with the semantics and changes among API versions.

I apologize if this is a problem of poor design. I only have a few weeks of Angular learning and I admittedly haven't read the documentation thoroughly. Please point any and all issues you see.

simple Search Service

import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';

@Injectable()
export default class ParkSearchService {

    constructor(private jsonp: Jsonp) { }

    search(parkSearchterm: string) {
        var search = new URLSearchParams()
        search.set('q', 'PARK_NAME:*' + parkSearchterm+'*');
        search.set('wt', 'json');

        search.set('json.wrf','JSONP_CALLBACK')

        var test = this.jsonp
            .get('http://parksearch/parks_full/select?', { search })
            .map((response) => response.json()['response']['docs']);

        return test

    }
}

exert from app.component.html

  <md-card *ngFor="let item of resultItems | async; let i = index"
                 class="search-result"
                 [ngClass]="{ 'selected-result': selectedIndex === i }">
            <md-card-header class="clickable"
                            (click)="showBoundary(item)"
                            md-tooltip="Zoom to park">
                <md-card-title>{{item.PARK_NAME}}</md-card-title>
            </md-card-header>
            <md-card-content style="height: 75px; overflow-y: auto">
                <button md-button
                        color="primary"
                        md-tooltip="more info"
                        (click)="openDtl(item.PARK_HOME_PAGE_URL)">
                    <md-icon>info</md-icon>
                    Details...
                </button>
                <button md-button
                        color="primary"
                        md-tooltip="open park website"
                        (click)="openParkURL(item.PARK_HOME_PAGE_URL)">
                    <md-icon>web</md-icon>
                    WebSite
                </button>
                Amenties: {{ item.AMEN_LIST }}
            </md-card-content>
        </md-card>

app.component.ts  (forgot to include)

 export class AppComponent {
    private selectedIndex: number;
    public events: any[] = [];
    //park search items
    resultItems: Observable<Array<string>>;
    parkSearchterm = new FormControl();

    //setup resultitems
    ngOnInit() {
            this.mapService.initialize();
            this.resultItems = this.parkSearchterm.valueChanges
                .debounceTime(400)
                .distinctUntilChanged()
                .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm));

map service:

//Thanks for the help getting started https://github.com/haoliangyu
import { Injectable } from '@angular/core';
import { Map, GeoJSON } from 'leaflet';

@Injectable()
export default class MapService {
    public map: Map;
    private currentLayer: GeoJSON;
    private resultsLayer: any;
    private resultfeatureCollection: any;

    constructor() {

    }

    initialize() {
        if (this.map) {
            return;
        }

        this.map = L.map('map', {
            zoomControl: true,
            zoom: 6,
            minZoom: 3,
            maxZoom: 19
        });

        L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap, Tiles courtesy of Humanitarian OpenStreetMap Team'
        }).addTo(this.map);

        L.control.scale().addTo(this.map);

        //Add the results layer
        this.resultsLayer = L.geoJSON(this.resultfeatureCollection, {
            style: () => {
                return {
                    color: '#ff00005',
                    fillColor: '#3F51B5'
                };
            }
        }).addTo(this.map);
    }
    mapResults(park) {
        //update the restults layer
        let resultfeatureCollection: GeoJSON.FeatureCollection<any> = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: "Polygon",
                        coordinates: JSON.parse(park.BBOX[0])
                    },
                    properties: {
                        name: 'test'
                    }
                }
            ]
        };

        this.resultsLayer.addData(resultfeatureCollection);
        this.map.fitBounds(this.resultsLayer.getBounds());
    }

}

Body:
You are very close to what you need: You already have an observable stream created for your results, called resultItems, that is right. Then on your template, when you use it through the async pipe what Angular does internally is subscribes to this stream to get its values.

So if you want to "also" map when resultItems yields is by subscribing to it by yourself as well. There's a catch though: by default every subscription duplicates the workload for the stream, meaning that every time the user makes a new search it would run the API call twice: 1 for the async subscription and another one for your .subscribe.

The way to resolve that is by using .publish(): What this allows is to share the result of an stream between many subscribers, so your code would look like this:

ngOnInit() {
    this.mapService.initialize();
    this.resultItems = this.parkSearchterm.valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm))
        .publish();
    // With publish() we are sharing the items from this stream to all of their subscribers
    // We just need to tell it to do the "first subscription"
    this.resultConnection = this.resultItems.connect();
    // This "resultConnection" is the base subscription... We will have to dispose it in our ngOnDestroy method or we might get memory leaks

    // Now we can tell the map service to update when we get a value:
    this.resultItems.subscribe((park) => this.mapService.mapResults(park));
    // (Not sure if the data types are correct, I assume you can map them)
    // When `async` calls .subscribe() to do his job, we won't get duplicate API calls thanks to .publish()
}

To clarify, what connect() does is subscribe to the original stream, and start forwarding the values recieved to the subscribers of the published stream (this.resultItems). Now you are the owner of that subscription, so you are responsible of disposing it whenever you don't need more searches.


问:
How to understand array sorting in Swift
Can someone please visualize the process of sorting?

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
</code>```

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

答:
The "(4 times)" means your closure ({ $0 > $1 }) is getting invoked 4 times by the sorted function.

I don't know what the false means, but presumably it's the last return value from your closure, which depends entirely on the internal sorting algorithm used by sorted (which you can visualize e.g. with David Shaw's method). I.e. $0 and $1 are not "changing their positions".

Body:
Can someone please visualize the process of sorting?

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?


问:
How can I switch to ruby 1.9.3 installed using Homebrew?
I have installed ruby 1.9.3 using hombrew

brew install ruby

But default 1.8.7 is still used. How can I switch osx to use 1.9.3 as default ruby?

答:
In OSX you can change the path using:

sudo nano /etc/paths

And then add a path or change the order.


问:
What do curly braces in the Windows registry mean?
I've been wondering this for a while and can't seem to get answer.

In Windows (maybe other places too), what do the curly braces mean? I'm guessing it has to do with hex but not sure.

Any help would be appreciated.

*UPDATE

I'm sorry I wasn't as specific as I should have been. I was talking about in the registry, but I've also seen it in folder paths.

答:
You mean curly braces as in {}? They're just characters and you can pretty well assign any meaning you want to them, although they're more useful in "balancing" situations, the same as [], <> and ().

Examples are:

block delineation in certain programming languages:
if (true) { do something }

array initialisers in certain programming languages:
int x[] = { 1, 2, 3 };

formatted printing where they're replaced in a format string with actual arguments, something like:
format ("My name is {1:s}{0:s}", "Diablo", "Pax");

Limiting the characters used in environment variable names in certain shells:
echo ${name}Diablo

surrounding character for GUIDs:
{3F2504E0-4F89-11D3-9A0C-0305E82C3301}

There are no doubt dozens of other uses in other scenarios as well, those were just the ones that came immediately to mind.

Since you seem to be specifically asking about GUIDs (based on your comment), you can start here.

ContentLicense: CC BY-SA 2.5


问:
How to add crypto to a nodejs build?
"It is possible for Node.js to be built without including support for the crypto module."

How can I add crypto to Node.js or choose how to build with ?

I know there is a npm package with the name "crypto" but there are packages who needs the crypto built-in.

答:
By default nodejs official packages are built with all defaults native packages.

But in some case you can experiment error trying to load (using require) a excluded module using a custom build (for example without OpenSSL support).

The 'crypto' npm module is an external module with a different interface and functions... and for his name it can conflicts with node's native one.

Title: How to add crypto to a nodejs build?


问:
Colon syntax error in if statement
Ok, so i'm pretty new to the whole coding scene, and i've been working on python through code academy. On the site there is an activity where you make a pig latin translator. I was able to make this just fine, but when I attempted to recreate it in the python shell I was getting some weird errors in the if statement.

```pyg = "ay"

original = raw_input("Enter a word bro:")\
if len(original) > 0 and original.isalpha():\

    print original\

else:
    print "error"```

I get a syntax error on the colon ending the statement, so I assumed it was some kind of indentation error. However when I put a line space between the line previous and the if statement, it works just fine! Can anyone explain why this is??

答:
Ending each line with \ is what's tripping you up. (See the documentation for "Explicit line joining")

\ is the chatacter used to continue a line if you want to have a "single line" span multiple lines of text

The python interpreter sees it and ignores the next newline character and thus sees:

```pyg = "ay"

original = raw_input("Enter a word bro:")if len(original) > 0 and original.isalpha():
    print original

else:
    print "error"```

when you add the extra space it works because the if statement is again on it's own line

Title: Colon syntax error in if statement

Body:
Ok, so i'm pretty new to the whole coding scene, and i've been working on python through code academy. On the site there is an activity where you make a pig latin translator. I was able to make this just fine, but when I attempted to recreate it in the python shell I was getting some weird errors in the if statement.

pyg = "ay"

original = raw_input("Enter a word bro:")\
if len(original) > 0 and original.isalpha():\

    print original\

else:
    print "error"

I get a syntax error on the colon ending the statement, so I assumed it was some kind of indentation error. However when I put a line space between the line previous and the if statement, it works just fine! Can anyone explain why this is??

Body:
Ending each line with \ is what's tripping you up. (See the documentation for "Explicit line joining")

\ is the chatacter used to continue a line if you want to have a "single line" span multiple lines of text

The python interpreter sees it and ignores the next newline character and thus sees:

pyg = "ay"

original = raw_input("Enter a word bro:")if len(original) > 0 and original.isalpha():
    print original

else:
    print "error"

when you add the extra space it works because the if statement is again on it's own line


问:
Generate PDF from HTML using Django and Reportlab
I am coming back with a new question which I am unable to answer, having scratched my head the whole day on it.

I want to generate a PDF from a webpage by clicking on a "Download PDF" button. I tried several modules including Reportlab and XHTML2PDF but I am not able to generate any pdf nor downloading it... Here is what I did with Reportlab, following Render HTML to PDF in Django site

-- views.py --

```<code>import cStringIO as StringIO
import ho.pisa as pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape

def index_data(request):
#Code to generate data
     return render(request, "analytics/stat.html", locals())
     return render_to_pdf(
        'analytics/stat.html',
        {
            'pagesize':'A4',
            'mylist': results,
        }
    )

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors```%s```' % escape(html))
</code>```

-- urls.py --

```<code>from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', "analytics.views.main_page", name="main_page"),
    url(r'^portail/$', "analytics.views.index_data", name="index"),
    url(r'^generate_pdf/$', "analytics.views.GroupPDFGenerate.as_view()", name="generate_pdf")
</code>```

]

-- Template analytics/stat.html --

```<code>{% extends "analytics/layout.html" %}

{% block title %}
    Audience
{% endblock title %}

{% block head %}
 # Script to generate google charts
{% endblock head %}

{% block body %}
<div class="page-header">
  <h1 align="center"> Audience </h1>
</div>
<div class="row">
  <div class="col-md-1">
      <h3 align="center"><a href="/logout/">Logout</a></h3>
      <h3 align="center"><a href="statistiques.pdf">Download pdf</a></h3>
  </div>
 </div>

{% endblock %}
</code>```

Also, is there a better module to process ?

答: If you say you are having problems even generating your PDF, I suggest you start by looking over the example I mentioned in this answer of using Reportlab, xhtml2pdf with django-easy-pdf. Get the PDF to render in the browser first and then move on to getting a link for downloading it.</p>

Body:
I am coming back with a new question which I am unable to answer, having scratched my head the whole day on it.

I want to generate a PDF from a webpage by clicking on a "Download PDF" button. I tried several modules including Reportlab and XHTML2PDF but I am not able to generate any pdf nor downloading it... Here is what I did with Reportlab, following Render HTML to PDF in Django site

-- views.py --

import cStringIO as StringIO
import ho.pisa as pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape

def index_data(request):
#Code to generate data
     return render(request, "analytics/stat.html", locals())
     return render_to_pdf(
        'analytics/stat.html',
        {
            'pagesize':'A4',
            'mylist': results,
        }
    )

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors
%s
' % escape(html))

-- urls.py --

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', "analytics.views.main_page", name="main_page"),
    url(r'^portail/$', "analytics.views.index_data", name="index"),
    url(r'^generate_pdf/$', "analytics.views.GroupPDFGenerate.as_view()", name="generate_pdf")

]

-- Template analytics/stat.html --

{% extends "analytics/layout.html" %}

{% block title %}
    Audience
{% endblock title %}

{% block head %}
 # Script to generate google charts
{% endblock head %}

{% block body %}

 Audience

Logout

Download pdf

{% endblock %}

Also, is there a better module to process ?


问:
Create zip style file without compression
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress.

Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?

答:
You can use Zip for this. You would use a compression level of something like "none" or  "store", which just combines the files without compression. This site enumerates some of them:

Maximum - The slowest of the
  compression options, but the most
  useful for creating small archives.

Normal - The default value.

Low - Faster than the default, but
  less effective.

Minimum - Extremely fast
  compression, but not as efficient as
  other methods.

None - Creates a ZIP file but does
  not compress it. File size may be
  slightly larger if archive is
  encrypted or made self-extracting.

Here are some C# examples:

CodeProject

EggheadCafe

For the unix unaware, this is exactly what tar does. When you see .tar.gz files, it's just a bunch of files combined into a tar file, and then run through gzip.

OwnerDisplayName: Jason Miesionczek

OwnerDisplayName: Michael Haren

LastEditorDisplayName: Michael Haren


问:
How to dynamically create block of content and then add class?
I'm pretty bad at Angularjs, sorry. I need to create 'commentary box' onclick, then i need to insert this "box" to global-wrap-container (it's a class name).

Here i have my "comment box"

```<code>  <div class="comment-reply-wrap" >
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{repUsers.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='repUsers.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{repUsers.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)">
            <i class="fa fa-reply" aria-hidden="true"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</code>```

Here is the function, where i push information and "commentary" appears.

```<code>$scope.addRepUser = function() {
$scope.bool = false;

//Dynamically create array of objects and push data
  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

//Clear input fields in main form
$scope.repUser.name = '';
$scope.repUser.email = '';
$scope.repUser.text = ''; };
</code>```

答:
You have to use ng-repeat</p>

```<code><div class="your-class" ng-repat="user in repUsers">
 <span class="comment-email">{{user.email}}</span>
 <span class="comment-date">10/29/2010 at 6:40AM</span>
 <span class="comment">{{user.text}}</span>
</div>
</code>```

Body:
I'm pretty bad at Angularjs, sorry. I need to create 'commentary box' onclick, then i need to insert this "box" to global-wrap-container (it's a class name).

Here i have my "comment box"

          {{repUsers.name}}

          {{repUsers.email}}
          10/29/2010 at 6:40AM
          <button type="submit" class="reply" ng-click="createReplyForm($event)">

          </button>

Here is the function, where i push information and "commentary" appears.

$scope.addRepUser = function() {
$scope.bool = false;

//Dynamically create array of objects and push data
  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

//Clear input fields in main form
$scope.repUser.name = '';
$scope.repUser.email = '';
$scope.repUser.text = ''; };

Body:
You have to use ng-repeat

<div class="your-class" ng-repat="user in repUsers">
 <span class="comment-email">{{user.email}}</span>
 <span class="comment-date">10/29/2010 at 6:40AM</span>
 <span class="comment">{{user.text}}</span>
</div>


问:
Storing the entire output of a while loop
I'm having problems storing the ouput of a while loop in Python3. The code below just stores the last output: 5702887

```<code>x = 1
y = 2
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)
</code>```

How do I get x to store:

```<code>1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
</code>```

答:
As it is written, you will never get 1 in that list. The reason being is that your first loop through effectively is 3-1 which equals 2. If you know for a fact 1 needs to be included, just add it to the list already when you create it.

```<code>answer = [1]
</code>```

Then run your loop, and it will append the rest of the data starting from 2 onwards to the list. Without knowing why 1 is explicitly needed, I have no basis to adjust the algorithm to get the desired result.

If you are allowed to change the values of x and y, then make:

```<code>x = 1
y = 1
</code>```

This will give you the desired result in your answer[] list without needing to specify 1 initially in the list when creating it

```<code>x = 1
y = 1
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)

print(answer)
</code>```

Output is:

```<code>[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887]
</code>```

Body:
I'm having problems storing the ouput of a while loop in Python3. The code below just stores the last output: 5702887

x = 1
y = 2
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)

How do I get x to store:

1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887

Body:
As it is written, you will never get 1 in that list. The reason being is that your first loop through effectively is 3-1 which equals 2. If you know for a fact 1 needs to be included, just add it to the list already when you create it.

answer = [1]

Then run your loop, and it will append the rest of the data starting from 2 onwards to the list. Without knowing why 1 is explicitly needed, I have no basis to adjust the algorithm to get the desired result.

If you are allowed to change the values of x and y, then make:

x = 1
y = 1

This will give you the desired result in your answer[] list without needing to specify 1 initially in the list when creating it

x = 1
y = 1
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)

print(answer)

Output is:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887]


问:
Total read time in Dataflow job has high variance
I have a Dataflow job that reads log files from my GCS bucket that are split by time and host machine. The structure of the bucket is as follows:

/YYYY/MM/DD/HH/mm/HOST/*.gz

Each job can end up consuming on the order of 10,000+ log files of around 10-100 KB in size.

Normally our job takes approximately 5 minutes to complete. We at times see our jobs spike to 2-3x that amount of time, and find that the majority of the increase is seen in the work items related to reading the data files. How can we reduce this variance on our job execution time? Is there a throughput issue with reading from GCS?

答:
Most likely the variance you see in your jobs is due to GCS network latency. While typically the latency to retrieve items from GCS is rather small, it can spike depending on various factors like network conditions and time of day. There is no SLA around latency when it comes to reading from GCS. The throughput from GCS is probably not the factor as the size of the data files you are reading are rather small.

If network conditions are such that your latency increases significantly, this effect will grow proportionally by the number of files you are reading.

One way to alleviate the variance in job time is to try and combine your log files before reading them in such that you have fewer files to read that are larger in size.


问:
Angular 2 form reset() not resetting values _submitted or submitted
Is there a way so form.reset() also resets values form.submitted to false again? This is annoying in my case as I use form.submitted as condition to show validation error in template. This means validation errors show up after form is cleared (reset).

template:

```<code><form ... #f="ngForm" (ngSubmit)="f.form.valid && submitProduct(f)>
  <input type="text" name="productName" [(ngModel)]="product.name" #productName="ngModel" required>
  <div *ngIf="f.submitted && !productName.valid">Product name is required</div>
  <button type="submit" value="true" >Submit Request</button>
</form>
</code>```

component:

```<code>submitProduct(form: NgForm) {
    this.productService.createProduct(this.product).subscribe(data => {
        form.reset();
        // HERE annoyingly validation errors show up on empty form.
      }
    );
}
</code>```

答:
Found the answer myself. Use

```<code>form.resetForm();
</code>```

instead. This sets submitted to false and pristine to true.

Body:
Is there a way so form.reset() also resets values form.submitted to false again? This is annoying in my case as I use form.submitted as condition to show validation error in template. This means validation errors show up after form is cleared (reset).

template:

<form ... #f="ngForm" (ngSubmit)="f.form.valid && submitProduct(f)>
  <input type="text" name="productName" [(ngModel)]="product.name" #productName="ngModel" required>

Product name is required

  <button type="submit" value="true" >Submit Request</button>
</form>

component:

submitProduct(form: NgForm) {
    this.productService.createProduct(this.product).subscribe(data => {
        form.reset();
        // HERE annoyingly validation errors show up on empty form.
      }
    );
}

Body:
Found the answer myself. Use

form.resetForm();

instead. This sets submitted to false and pristine to true.


问:
How can I make adsense appear on my website again?
I have just developed this website: www.hackit4me.com and I tried to add adsense to it (today). My adsense account is prety old (three years old), but it does not show up on the website as you can see. Is there anything I can do to fix this problem? Thank you beforehand.</p>

答:
The ads can become inactive after not using them for such a long period.Try to make a new ad unit, paste the code to your site where ever you want and wait for at least 2-3 days for them to become active.
You can check whether the ads are active or not, in Adsense Dashbaord->my ad units and filter them with date created.</p>


问:
bash Shell - not exiting for if-elif conditions
Bash shell not exiting - for below code - although I don't get any errors.
Please help me with exit mechanism

When I press CTRL+D i get the output correctly for appropriate conditions

```<code>#!/bin/bash

read un < $HOME/un.txt

sqlplus $un @report.sql > Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls

mail_to="xxxx"

count=$(grep -c "no rows selected" $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

error=$(grep -c ERROR $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

if [ "$error" -gt 0 ]

then

    echo -e "Error occurred\n\nNOTE: In case of Schema/password change is done to HARP database, the private variables in the script needs modifications - SCM team Will take appropriate action" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

elif [ "$count" -gt 0 ]

then

    echo -e "Hi All\n\nNo Packages where migrated for `date -d "1 day ago" +"%b_%d_%Y"` \n\n\nThanks & Regards \nSCM team \n\n\n" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

else

    cat mail_content_2 | mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  -a $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls $mail_to

fi

exit 0
</code>```

答: Try set -e to exit the script at any error, but its unclear what your problem is...

Body:
Bash shell not exiting - for below code - although I don't get any errors.
Please help me with exit mechanism

When I press CTRL+D i get the output correctly for appropriate conditions

#!/bin/bash

read un < $HOME/un.txt

sqlplus $un @report.sql > Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls

mail_to="xxxx"

count=$(grep -c "no rows selected" $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

error=$(grep -c ERROR $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

if [ "$error" -gt 0 ]

then

    echo -e "Error occurred\n\nNOTE: In case of Schema/password change is done to HARP database, the private variables in the script needs modifications - SCM team Will take appropriate action" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

elif [ "$count" -gt 0 ]

then

    echo -e "Hi All\n\nNo Packages where migrated for `date -d "1 day ago" +"%b_%d_%Y"` \n\n\nThanks & Regards \nSCM team \n\n\n" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

else

    cat mail_content_2 | mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  -a $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls $mail_to

fi

exit 0


问:
functions with different names but same arguments
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

```<code>search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);
</code>```

now lets assume I have the name of the requested method, lets assume esa, in a string:

```<code>string methodName = "esa"
</code>```

is it possible to call the corresponding function by using macros?
I tested

```<code>#define CALL_SEARCH_MV(method) search_##method
</code>```

and then try to call it by:

```<code>CALL_SEARCH_MV(methodName.c_str())
</code>```

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

答:
You can use a combination of Macros, function pointers and clever hacking to achieve the desired result with ease.

In your main.cpp (or where the search functionality lives):

```<code>#include <map>
#include <string>
#include <iostream>

typedef int(*search)(int a, int b);

#define SEARCH(x) int search_##x(int a, int b);
#include "search_func.incl"
#undef SEARCH

#define SEARCH(x) {#x, search_##x},
std::map<std::string, search> search_funcs = {
#include "search_func.incl"
};
#undef SEARCH

int main(char** argv, int argc)
{
    std::cout << search_funcs["esa"](1, 2) << std::endl;
    std::cout << search_funcs["tss"](3, 4) << std::endl;
    std::cout << search_funcs["fss"](5, 6) << std::endl;
    std::cout << search_funcs["ds"](7, 8) << std::endl;

    return 0;
}

int search_esa(int a, int b) { return 100 * a + 10 * b + 0; }
int search_tss(int a, int b) { return 100 * a + 10 * b + 1; }
int search_fss(int a, int b) { return 100 * a + 10 * b + 2; }
int search_ds(int a, int b) { return 100 * a + 10 * b + 3; }
</code>```

In search_func.incl

```<code>SEARCH(esa)
SEARCH(tss)
SEARCH(fss)
SEARCH(ds)
</code>```

How this works
The search_func.incl file specifies the name of your search functions with a macro. When you include the file, you switch up the definition of the macro so that the included functions are presented differently.

```<code>SEARCH(abc)
</code>```

becomes a function declaration on the first include:

```<code>int search_abc(int a, int b);
</code>```

and a key value pair {string, function pointer} on the second include:

```<code>{"abc", search_abc},
</code>```

These KVP are in a map, so when  you need to call a function, the string maps to the function name automatically.

Body:
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);

now lets assume I have the name of the requested method, lets assume esa, in a string:

string methodName = "esa"

is it possible to call the corresponding function by using macros?
I tested

#define CALL_SEARCH_MV(method) search_##method

and then try to call it by:

CALL_SEARCH_MV(methodName.c_str())

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

Body:
You can use a combination of Macros, function pointers and clever hacking to achieve the desired result with ease.

In your main.cpp (or where the search functionality lives):

#include <map>
#include <string>
#include <iostream>

typedef int(*search)(int a, int b);

#define SEARCH(x) int search_##x(int a, int b);
#include "search_func.incl"
#undef SEARCH

#define SEARCH(x) {#x, search_##x},
std::map<std::string, search> search_funcs = {
#include "search_func.incl"
};
#undef SEARCH

int main(char** argv, int argc)
{
    std::cout << search_funcs["esa"](1, 2) << std::endl;
    std::cout << search_funcs["tss"](3, 4) << std::endl;
    std::cout << search_funcs["fss"](5, 6) << std::endl;
    std::cout << search_funcs["ds"](7, 8) << std::endl;

    return 0;
}

int search_esa(int a, int b) { return 100 * a + 10 * b + 0; }
int search_tss(int a, int b) { return 100 * a + 10 * b + 1; }
int search_fss(int a, int b) { return 100 * a + 10 * b + 2; }
int search_ds(int a, int b) { return 100 * a + 10 * b + 3; }

In search_func.incl

SEARCH(esa)
SEARCH(tss)
SEARCH(fss)
SEARCH(ds)

How this works
The search_func.incl file specifies the name of your search functions with a macro. When you include the file, you switch up the definition of the macro so that the included functions are presented differently.

SEARCH(abc)

becomes a function declaration on the first include:

int search_abc(int a, int b);

and a key value pair {string, function pointer} on the second include:

{"abc", search_abc},

These KVP are in a map, so when  you need to call a function, the string maps to the function name automatically.


问:
Angular2 - How can I add HTTP headers to responses my app sends to the browser?
I'm prototyping an Angular2 app at work. The app should run under some company middleware that expects several Link headers in responses it gets from the angular2 app. Unfortunately, I haven't been able to figure out how to add headers to responses that Angular provides out of the box.

To clarify what I mean - when I send a GET Request directly to my Angular app, it sends back a Text/HTML response that a browser can render into an SPA. I would like to add headers to this response, and can't figure out how. The closest I've found is the discussion here: Angular2 - set headers for every request

This sounds like a duplicate, but having looked through similar questions, I've found how to add headers to Responses I generate explicitly with an HTTP object from the HttpModule, but not how to attach headers to the Responses that Angular creates out-of-the-box. I'd love to use something like an HTTP Interceptor that just attaches headers to every response my app sends out, but it doesn't look like Angular2 will have interceptors until release 4.1.

Edit: Things I've tried:

Adding a provider for Http ResponseOptions in my (main) AppModule that adds headers to responses

This adds the header to all responses I receive from http requests that my app receives from the HttpModule, but doesn't add the header to responses that my app itself sends to outside services.

Edit 2: I misunderstood where my Angular app ends and where the server hosting it begins. Headers like this can be added in the server - for my simple example, I needed to configure the webpack-dev-server. See the accepted answer below.

答:
Web Starter Pack uses webpack-dev-server just as a development hosting platform/Web server for your efforts, but it 's not, in the end, part of your final Angular app proper.  You'll eventually serve your Angular app from some other hardened Web server software such as Apache, IIS, etc.

For development purposes, you should be able to configure webpack-dev-server to add custom headers by modifying your webpack.config.js by setting the headers options, per the documentation.

devServer.headers

Adds headers to all requests:

```<code>headers: {
  "X-Custom-Foo": "bar"
}
</code>```

For example:

webpack.config.js

```<code>...
devServer: {
  ...
  headers: {
    "X-Custom-Foo": "bar"
  }
  ...
}
...
</code>```

Although to actually read the "initial load" headers within your Angular application once it initializes (if that is what you're looking to do) you may need to add your values as [non-httpOnly] cookies, then read them on ngInit().

Source: DevServer Documentation - Header

Body:
Web Starter Pack uses webpack-dev-server just as a development hosting platform/Web server for your efforts, but it 's not, in the end, part of your final Angular app proper.  You'll eventually serve your Angular app from some other hardened Web server software such as Apache, IIS, etc.

For development purposes, you should be able to configure webpack-dev-server to add custom headers by modifying your webpack.config.js by setting the headers options, per the documentation.

devServer.headers

Adds headers to all requests:

headers: {
  "X-Custom-Foo": "bar"
}

For example:

webpack.config.js

...
devServer: {
  ...
  headers: {
    "X-Custom-Foo": "bar"
  }
  ...
}
...

Although to actually read the "initial load" headers within your Angular application once it initializes (if that is what you're looking to do) you may need to add your values as [non-httpOnly] cookies, then read them on ngInit().

Source: DevServer Documentation - Header


问:
Displaying multiple feature modules that use router in the same view in Angular
I have an use case in which I need to have multiple modules loaded in the view at the same time. Thing is, each of those modules might be as simple as a component, or a complex Angular module with a router and everything. I guess you could call it a plugable framework.

The number of modules I have to show or who they are is dynamic (I'm getting them from a server).

My first idea is that it would be good for this case if the feature module's router wouldn't be a singleton with the main one and also if they wouldn't update the url completly.

Each of the feature module should be able to be launched as a stand-alone app if bootstrapped (therefore, I do need it to be able incorporate all Angular 4 features including the router).

I managed to get something working by playing with the router and with named router outlets (secondary routes) but not sure how good that is in the long run.

How should I approach this?

答:
I am in the early stages of attacking a somewhat similar scenario. In my app, the UI is organized in panels that are designed to stand alone on smaller displays, or side by side on larger. I find this approach works well for my routes, as my app is designed to edit a complex, highly hiegraphical document with many inter-related sections. e.g. User follows link on list to open detail, new detail panel appears to right... follows link on detail to related node... etc.

The solution I'm noodling with now is attempting to use an ngrx store that interacts with the router (and router-store) to dynamically create panels based upon router data. Well, technically it does not create the panels, it only serves the data that tells a component what to create and render.

I know my situ is not exactly the same as yours, but perhaps there's something in my approach that may help you find usefull or at least thought provoking.


问:
Need help optimizing speed for a loop/dot-product function in C++
I've identified a function in a tightloop that's responsible for 50% of the time in my program(finding nearest neighbors). It calculates the euclidean distance between two unit vectors. Is there any way to make this run faster? (currently I am using gcc's -march=native and -ffast-math flags)

```<code>template<typename T>
  static inline T distance(const T* x, const T* y, int f) {
    T pp = 0, qq = 0, pq = 0;
    for (int z = 0; z < f; z++, x++, y++) {
      pp += (*x) * (*x);
      qq += (*y) * (*y);
      pq += (*x) * (*y);
    }
    T ppqq = pp * qq;
    if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq);
    else return 2.0;
  }
</code>```

答:
This code is higly paralelizable, you could try to use OpenMP or a small thread to do the computations in different threads.

```<code>template<typename T>
  static inline T distance(const T[] x, const T[] y, int f) {
    T pp = 0, qq = 0, pq = 0;
    #pragma omp parallel for private(x,z) reduction(*:pp)
    for (int z = 0; z < f; z++, x++) {
      pp += (*x) * (*x);
    }
  }
</code>```

OpenMP is a Paralelization library that relies on Pragmas for paralelizing code, it's really common in scientific computing. You can easily create threads by specifiying a pragma over the statement you wanna paralelize.

The simplest format is

```<code>#pragma omp parallel for
for(int i = 0; i < 10000; i++) {
    paralelized code here
}
</code>```

This will take care of creating the threads, executing the paralelized code and joiining the threads back for you with a simple #pragma definition.

Body:
I've identified a function in a tightloop that's responsible for 50% of the time in my program(finding nearest neighbors). It calculates the euclidean distance between two unit vectors. Is there any way to make this run faster? (currently I am using gcc's -march=native and -ffast-math flags)

template<typename T>
  static inline T distance(const T* x, const T* y, int f) {
    T pp = 0, qq = 0, pq = 0;
    for (int z = 0; z < f; z++, x++, y++) {
      pp += (*x) * (*x);
      qq += (*y) * (*y);
      pq += (*x) * (*y);
    }
    T ppqq = pp * qq;
    if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq);
    else return 2.0;
  }

Body:
This code is higly paralelizable, you could try to use OpenMP or a small thread to do the computations in different threads.

template<typename T>
  static inline T distance(const T[] x, const T[] y, int f) {
    T pp = 0, qq = 0, pq = 0;
    #pragma omp parallel for private(x,z) reduction(*:pp)
    for (int z = 0; z < f; z++, x++) {
      pp += (*x) * (*x);
    }
  }

OpenMP is a Paralelization library that relies on Pragmas for paralelizing code, it's really common in scientific computing. You can easily create threads by specifiying a pragma over the statement you wanna paralelize.

The simplest format is

#pragma omp parallel for
for(int i = 0; i < 10000; i++) {
    paralelized code here
}

This will take care of creating the threads, executing the paralelized code and joiining the threads back for you with a simple #pragma definition.


问:
Adding a parameter when naming a variable
I would like to create a dictionary for each Identification number.

The argument passed in could be e.g. {Id, Key, Value}

I want to create a new dictionary by appending the Id to a prefix e.g. Dict

Then I want to write the Key to the dict using dict:store(Key, [Value], oldDict)

The Value at this point is a queue, so I will first read the queue and add to it then write back to the dictionary.

My question is how does the Id get appended to the prefix?

答:
You want to construct a variable name at runtime

That's impossible, sorry.

In Erlang, you cannot attach names to things at runtime†. Your only option would be store all dictionaries in another dictionary and passing that around.

For glueing together a static identifier (D) and a number, Erlang gives you quite a number of possibilities. The easiest way would be to construct a tuple {d, ID} and using that as the key.
You can also use any of the string concatentation methods described below.

Now that you've clarified your question, most of my original interpretations have lost context. I'm leaving them here, anyway.

You want to concatenate a string and an integer

This is easy, just use:

```<code>"D" ++ integer_to_list(SomeID)
</code>```

You want to set a value in a dictionary, using the above as the key

Erlang is a functional language, so destructively modifiying a dictionary is not possible.
Supposing you have a dictionary stored in the variable Dict and SomeID is set to three.
You can obtain a copy of Dict in which "D3" is set to Value using:

```<code>NewDict = dict:store("D" ++ integer_to_list(SomeID), Value, Dict)
</code>```

You are looking for a printf-like mechanism

The Erlang function io_lib:format(FmtString, Args) can be used for that. Unlike printf, formatting directives start with a tilde character.
You can look up the right directive in the manual, but for adding an integer to the string "D", the call would look like this:

```<code>io_lib:format("D~b", [SomeID])
</code>```

Gotcha: io_lib:format/2 returns a deep list of characters. If you want a flat list, use lists:flatten/1 on the result. You can try this in the Erlang shell:

```<code>(b@frog)1> SomeID = 3.
3
(b@frog)2> io_lib:format("D~b", [SomeID]).
[68,"3"]
(b@frog)3> lists:flatten(io_lib:format("D~b", [SomeID])).
"D3"
</code>```

† actually, you can do that using the process dictionary. Don't! You'll lose the ability to properly
test and debug your program (apart from going to hell).

Body:
You want to construct a variable name at runtime

That's impossible, sorry.

In Erlang, you cannot attach names to things at runtime†. Your only option would be store all dictionaries in another dictionary and passing that around.

For glueing together a static identifier (D) and a number, Erlang gives you quite a number of possibilities. The easiest way would be to construct a tuple {d, ID} and using that as the key.
You can also use any of the string concatentation methods described below.

Now that you've clarified your question, most of my original interpretations have lost context. I'm leaving them here, anyway.

You want to concatenate a string and an integer

This is easy, just use:

"D" ++ integer_to_list(SomeID)

You want to set a value in a dictionary, using the above as the key

Erlang is a functional language, so destructively modifiying a dictionary is not possible.
Supposing you have a dictionary stored in the variable Dict and SomeID is set to three.
You can obtain a copy of Dict in which "D3" is set to Value using:

NewDict = dict:store("D" ++ integer_to_list(SomeID), Value, Dict)

You are looking for a printf-like mechanism

The Erlang function io_lib:format(FmtString, Args) can be used for that. Unlike printf, formatting directives start with a tilde character.
You can look up the right directive in the manual, but for adding an integer to the string "D", the call would look like this:

io_lib:format("D~b", [SomeID])

Gotcha: io_lib:format/2 returns a deep list of characters. If you want a flat list, use lists:flatten/1 on the result. You can try this in the Erlang shell:

(b@frog)1> SomeID = 3.
3
(b@frog)2> io_lib:format("D~b", [SomeID]).
[68,"3"]
(b@frog)3> lists:flatten(io_lib:format("D~b", [SomeID])).
"D3"

† actually, you can do that using the process dictionary. Don't! You'll lose the ability to properly
test and debug your program (apart from going to hell).


问:
Addition of two integer in binary representation
I would like to implement code which will add two integers by their binary representation.

For instance:

```<code>a = [1 1 1 0];
</code>```

and

```<code>b = [1 0 1 1];
</code>```

So I implemented the following algorithm:

```<code>function s=add_binary(a,b)
  m=length(a);
  s=zeros(m+1,0);
  n=length(a);
  c=0;
  for ii=n:-1:1
    d=floor((a(ii)+b(ii)+c)/2);
    s(ii)=a(ii)+b(ii)+c-2*d;
    c=d;
  end
  s(1)=c;
end
</code>```

However, it returns this as a result:

```<code>s=add_binary(a,b)

s =

     1     0     0     1
</code>```

Here, there should be an additional 1 on the left, such that it would read:

```<code>1 1 0 0 1
</code>```

Where am I making a mistake?

答:
Since you're dealing with binary numbers, why not use logical operators?

```<code>function s = add_binary(a, b)
  a = [0 a];
  b = [0 b];
  c = a&b;
  while any(c)
    b = xor(a, b);
    a = circshift(c, -1);
    c = a&b;
  end
  s = a+b;
end
</code>```

And a test:

```<code>>> a = randi([0 1], [1 6])
a =
     0     1     0     1     0     1
>> b = randi([0 1], [1 6])
b =
     1     1     0     0     0     1
>> s = add_binary(a, b)
s =
     1     0     0     0     1     1     0
</code>```

Body:
I would like to implement code which will add two integers by their binary representation.

For instance:

a = [1 1 1 0];

and

b = [1 0 1 1];

So I implemented the following algorithm:

function s=add_binary(a,b)
  m=length(a);
  s=zeros(m+1,0);
  n=length(a);
  c=0;
  for ii=n:-1:1
    d=floor((a(ii)+b(ii)+c)/2);
    s(ii)=a(ii)+b(ii)+c-2*d;
    c=d;
  end
  s(1)=c;
end

However, it returns this as a result:

s=add_binary(a,b)

s =

     1     0     0     1

Here, there should be an additional 1 on the left, such that it would read:

1 1 0 0 1

Where am I making a mistake?

Body:
Since you're dealing with binary numbers, why not use logical operators?

function s = add_binary(a, b)
  a = [0 a];
  b = [0 b];
  c = a&b;
  while any(c)
    b = xor(a, b);
    a = circshift(c, -1);
    c = a&b;
  end
  s = a+b;
end

And a test:

>> a = randi([0 1], [1 6])
a =
     0     1     0     1     0     1
>> b = randi([0 1], [1 6])
b =
     1     1     0     0     0     1
>> s = add_binary(a, b)
s =
     1     0     0     0     1     1     0


问:
A better way how to make Eclipse resistant to Java updates
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

```<code>-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe
</code>```

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?

答:
What we do to avoid this problem: We have custom dedicated JDK's for our development environment (for eclipse and for our products), which are not 'attached' to the system. We're using softlinks e.g. ../app/jdk which links to a specific jdk, for intellij we have a ../app/intellij-jdk softlink.

Not sure who to do it in windows, but in linux you download the gzip and extract it, withing messing up your system, like paths, I think for windows you can only download the installer, but it's possible to only extract the actual software from the executable.

Body:
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?


问:
uncaught TypeError: Cannot read property 'style' of null at frame
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

```<code><a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default">
                <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                    <p class="text-center">0%</p>
                </div>
            </div></a>
            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>
        </div>
        <script type="text/javascript">
            function move() {
                document.getElementById("headerTop").style.cursor = "wait";
                var elem = document.getElementById("myBar");
                var width = 0;
                var id = setInterval(frame, 1000);
                function frame() {
                    if (width >= 99) {
                        var number = random(99, 100)
                        if(number = 99) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' )
                            document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over";
                        }else if (number = 100) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' )
                            document.getElementById("header").title = "download is ready";
                        }
                    } else {
                        width++;
                        elem.style.width = width + '%';
                        elem.innerHTML = width * 1 + '%';
                    }
                }
            }
    </script>
</code>```

F.Y.I i am using bootstrap for the styling

答:
Observation : There is no id with name myBar is available in your DOM.

Statement : var elem = document.getElementById("myBar") will return null.

Hence, you are getting below error as you are trying to access style property of null.

Uncaught TypeError: Cannot read property 'style' of null

Body:
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

0%

            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>

F.Y.I i am using bootstrap for the styling


问:
DbUnit - Warning: AbstractTableMetaData
I am using DbUnit in the latest version 2.4.8 and I get many warnings in my Unit tests with this message:

```<code>WARN : org.dbunit.dataset.AbstractTableMetaData -
Potential problem found: The configured data type factory
    'class org.dbunit.dataset.datatype.DefaultDataTypeFactory'
     might cause problems with the current database 'MySQL' (e.g. some datatypes may
     not be supported properly). In rare cases you might see this message because the
     list of supported database products is incomplete (list=[derby]). If so please
     request a java-class update via the forums.If you are using your own
     IDataTypeFactory extending DefaultDataTypeFactory, ensure that you override
     getValidDbProducts() to specify the supported database products.
</code>```

So I thought I add this (I use a MySQL database):

```<code>protected void setUpDatabaseConfig(DatabaseConfig config) {
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
}
</code>```

But this does not help to avoid these warnings. What's wrong here?

Thank you in advance & Best Regards Tim.

答:
With Spring-Boot you can use such configuration bean

```<code>@Configuration
public class DbUnitConfiguration {

@Autowired
private DataSource dataSource;

@Bean
public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection() {
    DatabaseConfigBean bean = new DatabaseConfigBean();
    bean.setDatatypeFactory(new MySqlDataTypeFactory());

    DatabaseDataSourceConnectionFactoryBean dbConnectionFactory = new DatabaseDataSourceConnectionFactoryBean(dataSource);
    dbConnectionFactory.setDatabaseConfig(bean);
    return dbConnectionFactory;
    }
}
</code>```

Title: DbUnit - Warning: AbstractTableMetaData

Body:
I am using DbUnit in the latest version 2.4.8 and I get many warnings in my Unit tests with this message:

WARN : org.dbunit.dataset.AbstractTableMetaData -
Potential problem found: The configured data type factory
    'class org.dbunit.dataset.datatype.DefaultDataTypeFactory'
     might cause problems with the current database 'MySQL' (e.g. some datatypes may
     not be supported properly). In rare cases you might see this message because the
     list of supported database products is incomplete (list=[derby]). If so please
     request a java-class update via the forums.If you are using your own
     IDataTypeFactory extending DefaultDataTypeFactory, ensure that you override
     getValidDbProducts() to specify the supported database products.

So I thought I add this (I use a MySQL database):

protected void setUpDatabaseConfig(DatabaseConfig config) {
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
}

But this does not help to avoid these warnings. What's wrong here?

Thank you in advance & Best Regards Tim.

Body:
With Spring-Boot you can use such configuration bean

@Configuration
public class DbUnitConfiguration {

@Autowired
private DataSource dataSource;

@Bean
public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection() {
    DatabaseConfigBean bean = new DatabaseConfigBean();
    bean.setDatatypeFactory(new MySqlDataTypeFactory());

    DatabaseDataSourceConnectionFactoryBean dbConnectionFactory = new DatabaseDataSourceConnectionFactoryBean(dataSource);
    dbConnectionFactory.setDatabaseConfig(bean);
    return dbConnectionFactory;
    }
}


问:
Python Selenium webdriver cannot TimeoutException: Message when waiting for an element
I'm using Python and Selenium to automate a test case. The problem is that when I reach test_press_add_to_cart the Webdriver doesn't see the element with the xpath:

```<code>//*[@id="fybAddCartEvent"]
</code>```

What could be the problem ?

The exception is :

"TimeoutException: Message"

The HTML of the element is:

```<code><a href="#" class="button" data-product_id="18542" data-wp_nonce="7c3d595f98" id="fybAddCartEvent">
Add to cart</a>
</code>```

And the script:

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from HTMLTestRunner import HTMLTestRunner

class Fotball_add_to_cart(unittest.TestCase):
    @classmethod
def setUpClass(inst):
    inst.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
    driver = inst.driver
    driver.get("http://ak:akpass@uat.athleticknit.com/football/")
    inst.driver.maximize_window()
    time.sleep(5)

    #click on "View All Fotball Products"
def test_click_on_view_all_fotball_products(self):
    viewProductsXpath = "a.woocommerce-nested-category-layout-see-more"
    self.viewProductsElement = self.driver.find_element_by_css_selector(viewProductsXpath)
    self.viewProductsElement.click()
    time.sleep(7)
    #select a product

def test_select_a_product_and_view_details(self):
    #select product
    tshirtXpath = "//a[@href=\"http://uat.athleticknit.com/product/f810/F810-000/\"]"
    self.tshirtElement = self.driver.find_element_by_xpath(tshirtXpath)
    self.tshirtElement.click()
    time.sleep(60)

def test_press_add_to_cart(self):
    #press add to cart
    driver = self.driver
    addToCartXpath = '//*[@id="fybAddCartEvent"]'
    self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))
    self.addToCartElement.click()
    time.sleep(5)
@classmethod
def tearDownClass(inst):
    inst.driver.stop_client()
    inst.driver.close()
    inst.driver.quit()
</code>```

答:
Actually you have used Explicit wait right here

```<code>self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))
</code>```

So it is waiting for your condition until 20 second and if condition not satisfying then showing TimeoutException.

If your requirement to wait for 'Add To cart' then try the following way -

```<code>element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.xpath, addToCartXpath)))
</code>```

Note :- If you have element id then please locate element by ID instead of xpath

```<code> element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "fybAddCartEvent")))

 element.click()
</code>```

Body:
I'm using Python and Selenium to automate a test case. The problem is that when I reach test_press_add_to_cart the Webdriver doesn't see the element with the xpath:

//*[@id="fybAddCartEvent"]

What could be the problem ?

The exception is :

"TimeoutException: Message"

The HTML of the element is:

Add to cart

And the script:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from HTMLTestRunner import HTMLTestRunner

class Fotball_add_to_cart(unittest.TestCase):
    @classmethod
def setUpClass(inst):
    inst.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
    driver = inst.driver
    driver.get("http://ak:akpass@uat.athleticknit.com/football/")
    inst.driver.maximize_window()
    time.sleep(5)

    #click on "View All Fotball Products"
def test_click_on_view_all_fotball_products(self):
    viewProductsXpath = "a.woocommerce-nested-category-layout-see-more"
    self.viewProductsElement = self.driver.find_element_by_css_selector(viewProductsXpath)
    self.viewProductsElement.click()
    time.sleep(7)
    #select a product

def test_select_a_product_and_view_details(self):
    #select product
    tshirtXpath = "//a[@href=\"http://uat.athleticknit.com/product/f810/F810-000/\"]"
    self.tshirtElement = self.driver.find_element_by_xpath(tshirtXpath)
    self.tshirtElement.click()
    time.sleep(60)

def test_press_add_to_cart(self):
    #press add to cart
    driver = self.driver
    addToCartXpath = '//*[@id="fybAddCartEvent"]'
    self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))
    self.addToCartElement.click()
    time.sleep(5)
@classmethod
def tearDownClass(inst):
    inst.driver.stop_client()
    inst.driver.close()
    inst.driver.quit()

Body:
Actually you have used Explicit wait right here

self.addToCartElement =WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(addToCartXpath))

So it is waiting for your condition until 20 second and if condition not satisfying then showing TimeoutException.

If your requirement to wait for 'Add To cart' then try the following way -

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.xpath, addToCartXpath)))

Note :- If you have element id then please locate element by ID instead of xpath

 element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "fybAddCartEvent")))

 element.click()


问:
Access the URL of an jQuery Ajax Request in the Callback Function
Is there a way that I can see the URL that was requested when I do an Ajax request with jQuery?

e.g.,

```<code>var some_data_object = { ...all sorts of junk... }
$.get('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
   var real_url = ? # <-- How do I get this
})
</code>```

How can I access the URL that jQuery actually used to make the request? Perhaps some method/property of jqHXR? I couldn't find it in the documentation.

Thanks.

答:
FYI, as an addition to airbai's comment -I cannot comment inside his answer,- you can add your own data to the call and retrieve it inside the callbacks. This way you don't have to parse the URL.

In this example JSONP request I have added the variable user_id (tested with jQuery 3.2):

```<code>var request = $.ajax({
    dataType: "json",
    url: "http://example.com/user/" + id + "/tasks?callback=?",
    user_id: id,
    success: function(data) {
        console.log('Success!');
        console.log("User ID: " + this.user_id);
    },
    timeout: 2000
}).fail(function() {
    console.log('Fail!');
    console.log("User ID: " + this.user_id);
});
</code>```

Body:
Is there a way that I can see the URL that was requested when I do an Ajax request with jQuery?

e.g.,

var some_data_object = { ...all sorts of junk... }
$.get('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
   var real_url = ? # <-- How do I get this
})

How can I access the URL that jQuery actually used to make the request? Perhaps some method/property of jqHXR? I couldn't find it in the documentation.

Thanks.

Body:
FYI, as an addition to airbai's comment -I cannot comment inside his answer,- you can add your own data to the call and retrieve it inside the callbacks. This way you don't have to parse the URL.

In this example JSONP request I have added the variable user_id (tested with jQuery 3.2):

var request = $.ajax({
    dataType: "json",
    url: "http://example.com/user/" + id + "/tasks?callback=?",
    user_id: id,
    success: function(data) {
        console.log('Success!');
        console.log("User ID: " + this.user_id);
    },
    timeout: 2000
}).fail(function() {
    console.log('Fail!');
    console.log("User ID: " + this.user_id);
});


问:
Uncaught ReferenceError: Chart is not defined
I've installed chart.js using npm by : npm install chart.js --save-dev, in "resources/assets/js/bootstrap.js"

I refer to it by:
require('chart.js');

Then in my console npm run dev and finally it's successfully compiled in "public/js/app.js", however when I try to use it in my view as follow

```<code><script src="/js/app.js"></script><script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
......... </script>
</code>```

the browser returns

Uncaught ReferenceError: Chart is not defined.

How come it's declared in app.js and can't refer to it ?

Thanks in advance.

答: If you look in app.js, is it wrapped in a function? It sounds like it's not part of the global namespace, despite being present in app.js.</p>

Body:
I've installed chart.js using npm by : npm install chart.js --save-dev, in "resources/assets/js/bootstrap.js"

I refer to it by:
require('chart.js');

Then in my console npm run dev and finally it's successfully compiled in "public/js/app.js", however when I try to use it in my view as follow

the browser returns

Uncaught ReferenceError: Chart is not defined.

How come it's declared in app.js and can't refer to it ?

Thanks in advance.


问:
Change runtime research for a compile time one
I'm trying to implement a generic ECS library in C++ for learning purpose. I was thinking about a lot of way to implement things but I always run into a problem. So if you could help me with this one :

Let say I have a constexpr hana::tuple of hana::type_c Components, something like :

```<code>struct C1 {};
struct C2 {};
struct C3 {};

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
</code>```

And now I have a component storage type, which is not a problem here, so let's call it Storage (the type differ for each component):

```<code>struct Storage {};
</code>```

I want to link each component or each component group, with their Storage type. So the easy way is to do something like that:

```<code>constexpr auto component_storage = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1, C2>), type_c<Storage>),
hana::make_pair(hana::to_tuple(hana::tuple_t<C3>), type_c<Storage>)
);
</code>```

But the problem now is runtime. If I initialize that tuple but with the real Storage and no longer type_c<Storage>, I'll have to loop through the tuple to find the Storage that I need. All of this at runtime no?
And this is really bad, my last version had something like Component::getStorage() and it was free (but more restrictive).

So the question is : how can I manage to have some getStorage<Component>() function which will cost nothing at runtime? Well by nothing I mean just return the reference of the Storage.

EDIT: The only way I have think so far is quite simple (sounds like a good point).

Pseudo-Code

```<code>struct LinkedStorage {

  hana::tuple<...>            storages;
  hana::tuple<hana::pair...>  index;
};
</code>```

At lest something like:

```<code>constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
constexpr auto storage = hana::to_tuple(hana::tuple_t<Storage, Storage>);
constexpr auto index = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1>, 0),
hana::make_pair(hana::to_tuple(hana::tuple_t<C2, C3>, 1)
);
</code>```

Like that I should be able to found the index at compile time and just access the right element at runtime. But I'm new at metaprogramming, so I guess someone could make something far better.

答:
First of all, no need to use to_tuple(tuple_t<...>); you can just use tuple_t<...>. Now, I think what you actually want to do (since you seem to need runtime storage, which makes sense) is:

```<code>// "map" of a set of types to a storage of some type
using StorageMap = hana::tuple<
  hana::pair<hana::tuple<hana::type<C1>, hana::type<C2>>, StorageA>,
  hana::pair<hana::tuple<hana::type<C3>>, StorageB>
>;
// Actual object that contains the runtime storage (and the free mapping between types)
StorageMap map;
</code>```

Now, you can implement your getStorage<Component>() function like this:

```<code>template <typename Component>
decltype(auto) getStorage() {
  auto found = index_if(map, [](auto const& pair) {
    return hana::contains(hana::first(pair), hana::type<Component>{});
  });
  return hana::second(hana::at(map, found));
}
</code>```

where index_if is a trivial variant of the function presented in this answer that would work on an arbitrary predicate instead of a specific element. This functionality will be added to Hana when I get some free time (see related ticket).

Body:
I'm trying to implement a generic ECS library in C++ for learning purpose. I was thinking about a lot of way to implement things but I always run into a problem. So if you could help me with this one :

Let say I have a constexpr hana::tuple of hana::type_c Components, something like :

struct C1 {};
struct C2 {};
struct C3 {};

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);

And now I have a component storage type, which is not a problem here, so let's call it Storage (the type differ for each component):

struct Storage {};

I want to link each component or each component group, with their Storage type. So the easy way is to do something like that:

constexpr auto component_storage = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1, C2>), type_c<Storage>),
hana::make_pair(hana::to_tuple(hana::tuple_t<C3>), type_c<Storage>)
);

But the problem now is runtime. If I initialize that tuple but with the real Storage and no longer type_c<Storage>, I'll have to loop through the tuple to find the Storage that I need. All of this at runtime no?
And this is really bad, my last version had something like Component::getStorage() and it was free (but more restrictive).

So the question is : how can I manage to have some getStorage<Component>() function which will cost nothing at runtime? Well by nothing I mean just return the reference of the Storage.

EDIT: The only way I have think so far is quite simple (sounds like a good point).

Pseudo-Code

struct LinkedStorage {

  hana::tuple<...>            storages;
  hana::tuple<hana::pair...>  index;
};

At lest something like:

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
constexpr auto storage = hana::to_tuple(hana::tuple_t<Storage, Storage>);
constexpr auto index = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1>, 0),
hana::make_pair(hana::to_tuple(hana::tuple_t<C2, C3>, 1)
);

Like that I should be able to found the index at compile time and just access the right element at runtime. But I'm new at metaprogramming, so I guess someone could make something far better.

Body:
First of all, no need to use to_tuple(tuple_t<...>); you can just use tuple_t<...>. Now, I think what you actually want to do (since you seem to need runtime storage, which makes sense) is:

// "map" of a set of types to a storage of some type
using StorageMap = hana::tuple<
  hana::pair<hana::tuple<hana::type<C1>, hana::type<C2>>, StorageA>,
  hana::pair<hana::tuple<hana::type<C3>>, StorageB>
>;
// Actual object that contains the runtime storage (and the free mapping between types)
StorageMap map;

Now, you can implement your getStorage<Component>() function like this:

template <typename Component>
decltype(auto) getStorage() {
  auto found = index_if(map, [](auto const& pair) {
    return hana::contains(hana::first(pair), hana::type<Component>{});
  });
  return hana::second(hana::at(map, found));
}

where index_if is a trivial variant of the function presented in this answer that would work on an arbitrary predicate instead of a specific element. This functionality will be added to Hana when I get some free time (see related ticket).