问:
How to limit the size of disk and memory cache of SDImageCache
I want to limit the size of memory cache and disk cache for SDImageCache.
Below is the code I have used for downloading the images. By default it saves the images in the cache and it is present In the sandbox's Library folder.

my Application
  ID/Library/Caches/com.hackemist.SDWebImageCache.default/

```<code>#import <SDWebImage/UIImageView+WebCache.h>

...

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *MyIdentifier = @"MyIdentifier";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:MyIdentifier] autorelease];
        }

        // Here we use the new provided sd_setImageWithURL: method to load the web image
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                          placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

        cell.textLabel.text = @"My Text";
        return cell;
    }
</code>```

答:
Objective-C

```<code>// Setting disk cache
[[[SDImageCache sharedImageCache] config] setMaxCacheSize:1000000 * 20]; // 20 MB

// Setting memory cache
[[SDImageCache sharedImageCache] setMaxMemoryCost:15 * 1024 * 1024]; // aprox 15 images (1024 x 1024)
</code>```

Swift 4

```<code>// Setting disk cache
SDImageCache.shared().config.maxCacheSize = 1000000 * 20 // 20 MB

// Setting memory cache
SDImageCache.shared().maxMemoryCost = 15 * 1024 * 1024
</code>```

Body:
I want to limit the size of memory cache and disk cache for SDImageCache.
Below is the code I have used for downloading the images. By default it saves the images in the cache and it is present In the sandbox's Library folder.

my Application
  ID/Library/Caches/com.hackemist.SDWebImageCache.default/

#import <SDWebImage/UIImageView+WebCache.h>

...

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *MyIdentifier = @"MyIdentifier";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:MyIdentifier] autorelease];
        }

        // Here we use the new provided sd_setImageWithURL: method to load the web image
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                          placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

        cell.textLabel.text = @"My Text";
        return cell;
    }

Body:
Objective-C

// Setting disk cache
[[[SDImageCache sharedImageCache] config] setMaxCacheSize:1000000 * 20]; // 20 MB

// Setting memory cache
[[SDImageCache sharedImageCache] setMaxMemoryCost:15 * 1024 * 1024]; // aprox 15 images (1024 x 1024)

Swift 4

// Setting disk cache
SDImageCache.shared().config.maxCacheSize = 1000000 * 20 // 20 MB

// Setting memory cache
SDImageCache.shared().maxMemoryCost = 15 * 1024 * 1024


来源: stackexchange

问:
function in rootscope, can't access rootscope variable
In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.

I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.

```<code>function getTourTranslation(key){
    console.log("getTourTranslation", key);
    var lang = $rootScope.language;
    var step = _.get(steps, key);
    return step[lang]
}
</code>```

So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?

I also tried as $rootScope.getTourTranslation = function(key) but no luck

edit:

This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.

```<code>$rootScope.changeLanguage = function (langKey) {
    if(langKey){
        if(langKey.length == 2) {
            $translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
            $rootScope.language = langKey;
        } else if(langKey.length == 5) {
            $translate.use(langKey);
            $rootScope.language = langKey.substring(0,2);
        }
    }
};

$rootScope.$on('$translateChangeSuccess', function () {
    if($translate.use()){
        $rootScope.language = $translate.use().substring(0,2);
        if($state.$current && !$state.$current.self.abstract) {
            $state.reload();
        }
    }
});
$rootScope.changeLanguage($translate.use());
</code>```

答:
It is not possible that variable defined on $rootScope is not available withing the same context.

I can imagine only one case:
it calls getTourTranslation so early so none of changeLanguage or $translateChangeSuccess handler ran

ContentLicense: CC BY-SA 3.0

Body:
In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.

I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.

function getTourTranslation(key){
    console.log("getTourTranslation", key);
    var lang = $rootScope.language;
    var step = _.get(steps, key);
    return step[lang]
}

So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?

I also tried as $rootScope.getTourTranslation = function(key) but no luck

edit:

This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.

$rootScope.changeLanguage = function (langKey) {
    if(langKey){
        if(langKey.length == 2) {
            $translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
            $rootScope.language = langKey;
        } else if(langKey.length == 5) {
            $translate.use(langKey);
            $rootScope.language = langKey.substring(0,2);
        }
    }
};

$rootScope.$on('$translateChangeSuccess', function () {
    if($translate.use()){
        $rootScope.language = $translate.use().substring(0,2);
        if($state.$current && !$state.$current.self.abstract) {
            $state.reload();
        }
    }
});
$rootScope.changeLanguage($translate.use());


问:
Vuejs dynamic routes with variable parameters
I start with vueJs and Webpack and I want to use vue router to create routes for elements of my table.

First i have the code of my table :

```<code>    <table class="table table-condensed">
                <tr style="text-align:left;" v-for="data in metadata">
                    <td>{{data.id}}</td>
                    <td><router-link :to="{ name: 'mixtapesDetails'}">
                        {{data.title}}
                    </router-link></td>
                    <td><router-link :to="{ name: 'mixtapesDetails'}">
                        {{data.artist}}
                    </router-link></td>
                </tr>

        </table>
</code>```

Then i have my Js function to get all my data :

```<code>export default {
  data(){
    return {
        metadata: null
    }
  },
  methods:{
    httpGet(theUrl){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // true for asynchronous request
    xmlHttp.send(null);
    console.log(JSON.parse(xmlHttp.responseText));
    return JSON.parse(xmlHttp.responseText);
    }
  },
  mounted(){
    this.metadata = this.httpGet("urltooJsondata");
  }
}
</code>```

And then i have my routes in JS :

```<code>export default new VueRouter({
routes: [
  {
    path: '/mixtapeList',
    name: 'mixtapeList',
    component: mixtapeList
  },
{
    path: '/mixtapesDetails/:id',
    name: 'mixtapesDetails',
    component: mixtapesDetails
}
]
</code>```

})

The objectif is that when i click on a router-link it goes to a single page with a url like this /mixtapesdetails/id. But the difficult part is that i want the id = {{this.data.id}}.
Sorry for my english, I really need help and i don't find the solution on web.

答:
Use the params object to specify:

```<code><router-link :to="{ name: 'mixtapesDetails', params: { id: data.id } }">
     {{data.title}}
</router-link>
</code>```

When id is 1234 that should send you to /mixtapeDetails/1234 according to your router configuration.

See https://router.vuejs.org/en/api/router-link.html

Body:
I start with vueJs and Webpack and I want to use vue router to create routes for elements of my table.

First i have the code of my table :

                    {{data.id}}
                    <router-link :to="{ name: 'mixtapesDetails'}">
                        {{data.title}}
                    </router-link>
                    <router-link :to="{ name: 'mixtapesDetails'}">
                        {{data.artist}}
                    </router-link>

Then i have my Js function to get all my data :

export default {
  data(){
    return {
        metadata: null
    }
  },
  methods:{
    httpGet(theUrl){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // true for asynchronous request
    xmlHttp.send(null);
    console.log(JSON.parse(xmlHttp.responseText));
    return JSON.parse(xmlHttp.responseText);
    }
  },
  mounted(){
    this.metadata = this.httpGet("urltooJsondata");
  }
}

And then i have my routes in JS :

export default new VueRouter({
routes: [
  {
    path: '/mixtapeList',
    name: 'mixtapeList',
    component: mixtapeList
  },
{
    path: '/mixtapesDetails/:id',
    name: 'mixtapesDetails',
    component: mixtapesDetails
}
]

})

The objectif is that when i click on a router-link it goes to a single page with a url like this /mixtapesdetails/id. But the difficult part is that i want the id = {{this.data.id}}.
Sorry for my english, I really need help and i don't find the solution on web.

Body:
Use the params object to specify:

<router-link :to="{ name: 'mixtapesDetails', params: { id: data.id } }">
     {{data.title}}
</router-link>

When id is 1234 that should send you to /mixtapeDetails/1234 according to your router configuration.

See https://router.vuejs.org/en/api/router-link.html


问:
Wait for promise to complete
I have read some posts regarding this subject but I have still not found the solution for this.

This my scenario:

I have a service: PermissionService, which looks like:

```<code>constructor(private http: HttpClient){}
hasPermission(operation: string, objects: string): Observable<Permission> {
    let queryStr: HttpParams = new HttpParams();
    queryStr = queryStr.set(“operation”,operation);
    queryStr = queryStr.set(“objects”,objects);
    return this.http.get<Permission>(this.url + permissionType, { params: queryStr });
}
</code>```

In my component I have injected the service and I use it like this:

```<code>hasCreatePermission(){
        this.permissionsService.hasPermission("C","Categories").subscribe(
          res => {
              this.canCreate = res.data[0].result;
          }, (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
              console.log('An error occurred:', err.error.message);
          } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    });
}
</code>```

When the promise finalizes the variable canCreate is set with the value of the permission.

This variable is used in my template to hide or show some component such as buttons.

All this stuff is working properly. So my question is.. is there any way in
Angular to make it synchronous?

To be able to call the method like:

This.canCreate = this.servicePermission.hasPermission…. I do not contiune the executing until the promise is resolved so I can get the result before the template is rendered.

I need this because I cannot display a page with buttons that are going to disappear after some seconds due to the permissions.

I agree that some calls to the backend such as getting data from the server need to be async but in this case I need the result to be able to render the page appropriately.

答:
You don't have to wait for it to resolve to be able to render your component that depends on what the resolved value is.

What you should do is use the async pipe in your component markup, and conditionally render buttons etc.

Something like

<button [hidden]="!canCreate | async">Click me if allowed!</button>

Title: Wait for promise to complete

Body:
I have read some posts regarding this subject but I have still not found the solution for this.

This my scenario:

I have a service: PermissionService, which looks like:

constructor(private http: HttpClient){}
hasPermission(operation: string, objects: string): Observable<Permission> {
    let queryStr: HttpParams = new HttpParams();
    queryStr = queryStr.set(“operation”,operation);
    queryStr = queryStr.set(“objects”,objects);
    return this.http.get<Permission>(this.url + permissionType, { params: queryStr });
}

In my component I have injected the service and I use it like this:

hasCreatePermission(){
        this.permissionsService.hasPermission("C","Categories").subscribe(
          res => {
              this.canCreate = res.data[0].result;
          }, (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
              console.log('An error occurred:', err.error.message);
          } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    });
}

When the promise finalizes the variable canCreate is set with the value of the permission.

This variable is used in my template to hide or show some component such as buttons.

All this stuff is working properly. So my question is.. is there any way in
Angular to make it synchronous?

To be able to call the method like:

This.canCreate = this.servicePermission.hasPermission…. I do not contiune the executing until the promise is resolved so I can get the result before the template is rendered.

I need this because I cannot display a page with buttons that are going to disappear after some seconds due to the permissions.

I agree that some calls to the backend such as getting data from the server need to be async but in this case I need the result to be able to render the page appropriately.


问:
Use single Template for multiple Item Sources and render separate combobox in UI
I am new to WPF/XAML so I am stuck in one problem is it possible that if I create one TEMPLATE of combobox in UI and what if is it possible to use one ComboBox to render multi-item sources? For example, I have two item sources A and B and in XAML I have one common template. So is it possible that I can create two different ComboBox in UI for A and B from single template?

I am using below template for creation

```<code><ComboBox x:Name="comboboxtemplate" ItemsSource="{Binding CboItemsource}" SelectedItem="{Binding comboboxSelecteditem, Mode=TwoWay}"
          Visibility="{Binding ShowCombobox, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ComboboxWidth, UpdateSourceTrigger=PropertyChanged}"
          IsEnabled="{Binding FieldValueIsEditable, UpdateSourceTrigger=PropertyChanged}"
          IsTextSearchCaseSensitive="False"
          IsTextSearchEnabled="True"
          TextSearch.TextPath="Description">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Code}" Width="0"/>
                <TextBlock Text= "{Binding Description}" TextWrapping="Wrap" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

答:
You could create a style that you apply to both ComboBoxes, .e.g.:

```<code><Window x:Class="WpfApplication1.Window1"
        ...>
    <Window.Resources>
        <Style x:Key="cmbStyle" TargetType="ComboBox">
            <Setter Property="Visibility" Value="{Binding ShowCombobox, UpdateSourceTrigger=PropertyChanged}" />
            <Setter Property="IsEnabled" Value="{Binding FieldValueIsEditable, UpdateSourceTrigger=PropertyChanged}" />
            <Setter Property="IsTextSearchEnabled" Value="True" />
            <!-- ... -->
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Code}" Width="0"/>
                            <TextBlock Text= "{Binding Description}" TextWrapping="Wrap" />
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <StackPanel>

        <ComboBox x:Name="cmb1" ItemsSource="{Binding CboItemsource}"
                  SelectedItem="{Binding comboboxSelecteditem, Mode=TwoWay}"
                  Style="{StaticResource cmbStyle}" />

        <ComboBox x:Name="cmb2" ItemsSource="{Binding OtherItemsource}"
                  SelectedItem="{Binding OtherSelecteditem, Mode=TwoWay}"
                  Style="{StaticResource cmbStyle}" />
    </StackPanel>
</Window>
</code>```

Body:
I am new to WPF/XAML so I am stuck in one problem is it possible that if I create one TEMPLATE of combobox in UI and what if is it possible to use one ComboBox to render multi-item sources? For example, I have two item sources A and B and in XAML I have one common template. So is it possible that I can create two different ComboBox in UI for A and B from single template?

I am using below template for creation

<ComboBox x:Name="comboboxtemplate" ItemsSource="{Binding CboItemsource}" SelectedItem="{Binding comboboxSelecteditem, Mode=TwoWay}"
          Visibility="{Binding ShowCombobox, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ComboboxWidth, UpdateSourceTrigger=PropertyChanged}"
          IsEnabled="{Binding FieldValueIsEditable, UpdateSourceTrigger=PropertyChanged}"
          IsTextSearchCaseSensitive="False"
          IsTextSearchEnabled="True"
          TextSearch.TextPath="Description">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Code}" Width="0"/>
                <TextBlock Text= "{Binding Description}" TextWrapping="Wrap" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Body:
You could create a style that you apply to both ComboBoxes, .e.g.:

<Window x:Class="WpfApplication1.Window1"
        ...>
    <Window.Resources>
        <Style x:Key="cmbStyle" TargetType="ComboBox">
            <Setter Property="Visibility" Value="{Binding ShowCombobox, UpdateSourceTrigger=PropertyChanged}" />
            <Setter Property="IsEnabled" Value="{Binding FieldValueIsEditable, UpdateSourceTrigger=PropertyChanged}" />
            <Setter Property="IsTextSearchEnabled" Value="True" />
            <!-- ... -->
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Code}" Width="0"/>
                            <TextBlock Text= "{Binding Description}" TextWrapping="Wrap" />
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <StackPanel>

        <ComboBox x:Name="cmb1" ItemsSource="{Binding CboItemsource}"
                  SelectedItem="{Binding comboboxSelecteditem, Mode=TwoWay}"
                  Style="{StaticResource cmbStyle}" />

        <ComboBox x:Name="cmb2" ItemsSource="{Binding OtherItemsource}"
                  SelectedItem="{Binding OtherSelecteditem, Mode=TwoWay}"
                  Style="{StaticResource cmbStyle}" />
    </StackPanel>
</Window>


问:
Need sample javascript object literal
I need a sample js object literal which can be accessed in the following way:

```<code>hist.undo[0].operation[0].x // would print '2' or whatever
hist.undo[0].operation[0].y // would print '21' or whatever
// [...]
hist.undo[2].operation[0].x // would print '32' or whatever
hist.undo[2].operation[0].y // would print '12' or whatever
</code>```

Thanks!

ContentLicense: CC BY-SA 2.5

Title: Need sample javascript object literal

Body:
I need a sample js object literal which can be accessed in the following way:

hist.undo[0].operation[0].x // would print '2' or whatever
hist.undo[0].operation[0].y // would print '21' or whatever
// [...]
hist.undo[2].operation[0].x // would print '32' or whatever
hist.undo[2].operation[0].y // would print '12' or whatever

Thanks!

Body:
hist = { "undo" : [
      {"operation":[
        {"x":2,"y":21},
        {"x":3,"y":31}
      ]},
      {"operation":[
        {"x":4,"y":41},
        {"x":5,"y":51}
      ]},
      {"operation":[
        {"x":6,"y":61},
        {"x":7,"y":71}
      ]}
     ]
    }


问:
How to pass command line arguments to a python file from a script
I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional

For Example.

```<code>.\train.py --counter arg1 --opt optional_arg
</code>```

Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute 'train.py' in 'script.py'

I need to do this as I want to give different set of arguments each time to train.py.

I know we can do this using a shell script. I am curious about how to do it using a python script.

train.py

```<code>import optparse
optparser = optparse.OptionParser()

optparser.add_option(
    "--counter", default = "",
    help = "Counter value"
)

optparser.add_option(
    "--opt", default = "",
    help = "Optinal parameter"
)

'''Do Something'''
</code>```

script.py

```<code>args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    args['--counter'] = counter

    '''run train.py with args as input dictionary'''
</code>```

答:
One approach would be to define the actions in train.py as a function:

```<code>def train(counter, opt=None):
    '''Do Something'''
</code>```

From here, in the same file, you can a check for main and run the function with the command line args.

```<code>if __name__ == '__main__':
    import optparse
    optparser = optparse.OptionParser()

    optparser.add_option(
        "--counter", default = "",
        help = "Counter value"
    )

    optparser.add_option(
        "--opt", default = "",
        help = "Optional parameter"
    )

    train(counter, opt)
</code>```

Now you can import the call and train function as you would any other python package. Assuming the files are in the same directory, that could look something like:

```<code>from train import train

args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    kwargs['--counter'] = counter  # changed to kwargs from OP's args
                                   # for the sake of accurate nomenclature
    train(**kwargs)
</code>```

Please note that unpacking the dictionary with ** only works if the key values are strings whose values are identical to the name of the function parameters.

One benefit from this approach is that you can run train independently from a command script or you can run it from a python program without the os intermediary.

Body:
I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional

For Example.

.\train.py --counter arg1 --opt optional_arg

Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute 'train.py' in 'script.py'

I need to do this as I want to give different set of arguments each time to train.py.

I know we can do this using a shell script. I am curious about how to do it using a python script.

train.py

import optparse
optparser = optparse.OptionParser()

optparser.add_option(
    "--counter", default = "",
    help = "Counter value"
)

optparser.add_option(
    "--opt", default = "",
    help = "Optinal parameter"
)

'''Do Something'''

script.py

args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    args['--counter'] = counter

    '''run train.py with args as input dictionary'''

Body:
One approach would be to define the actions in train.py as a function:

def train(counter, opt=None):
    '''Do Something'''

From here, in the same file, you can a check for main and run the function with the command line args.

if __name__ == '__main__':
    import optparse
    optparser = optparse.OptionParser()

    optparser.add_option(
        "--counter", default = "",
        help = "Counter value"
    )

    optparser.add_option(
        "--opt", default = "",
        help = "Optional parameter"
    )

    train(counter, opt)

Now you can import the call and train function as you would any other python package. Assuming the files are in the same directory, that could look something like:

from train import train

args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    kwargs['--counter'] = counter  # changed to kwargs from OP's args
                                   # for the sake of accurate nomenclature
    train(**kwargs)

Please note that unpacking the dictionary with ** only works if the key values are strings whose values are identical to the name of the function parameters.

One benefit from this approach is that you can run train independently from a command script or you can run it from a python program without the os intermediary.


问:
JS to PHP Sockets?
I have become very comfortable with PHP and mySQL over the past couple months, but I have recently wanted to create a game (with database connections) that needs even better responsiveness then AJAX. This is where I came across sockets. I do not want to branch into Node.js (I am more comfortable with PHP servers) but PHP sockets can't be pushed information via JavaScript, which is crucial for responsive user input.

In short, I am seeking a method with the responsiveness of sockets but that can be pushed by the client in JS and received in PHP on server, similar to AJAX but bidirectional and fast.

Note I may be misunderstanding some of these concepts as a new member to this crazy new set of servers. Just correct and direct me please.

答:
To build a PHP websocket server, Take a look at RatchetPHP: http://socketo.me/

It uses a sub protocol, WAMP so your websocket connection will have channels (topics).

Cons: It still uses the version 1 of WAMP subprotocol, the author suggest to use Thruway.

But RatchetPHP is better documented, and let you learn to implement websockets easily.

Title: JS to PHP Sockets?


问:
How to update data elements within a transition without deleting a re-creating everything?
I'm using d3js v3 have a heat map that upon changing a ratio button selection I would switch the data from one dataset to another. The initialization requires a lot of steps e.g.

```<code>var svg = d3.select("#myId").append("svg");
...
var heatNode = svg.append("g");
heatNode.selectAll(".cellrect")
   .data(data, function(d) { return d.row + ":" + d.col; })
   .enter()
   .append("rect")
   .attr("x", function(d) { return (d.col - 1) * (cellWidth + cellMargin); })
   .attr("y", function(d) { return (d.row - 1) * (cellHeight +  + cellMargin); })
   .attr("class", function(d) { return "cell cell-border cr" + (d.row-1) + " cc" + (d.col-1); })
   .attr("width", cellWidth)
   .attr("height", cellHeight)
   .style("fill", function(d) { return colorScale(d.value); })
   .on("mouseover", function(d) {
       // highlight text
       d3.select(this).classed("cell-hover", true);
       d3.selectAll(id + " .rowLabel").classed("text-highlight", function(r, ri) { return ri == (d.row - 1); });
       d3.selectAll(id + " .colLabel").classed("text-highlight", function(c, ci) { return ci == (d.col - 1); });
            })
   .on("mouseout", function(d) {
       d3.select(this).classed("cell-hover", false);
       d3.selectAll(id + " .rowLabel").classed("text-highlight", false);
       d3.selectAll(id + " .colLabel").classed("text-highlight", false);
   });
</code>```

and now I get new data and would like to update only the fill color and nothing else. So I have tried without succcess:

```<code>   heatNode.selectAll(".cellrect").transition().duration(2000)
       .data(newData, function(d) { return d.row + ":" + d.col; })
       .style("fill", function(d) { return colorScale(d.value); });
</code>```

The only way that has worked for me so far is doing an ugly:

```<code>   heatNode.selectAll("*").transition().duration(2000).remove();
</code>```

and recreating everything again, however, not even then the transition works for me.

答:
The code seems right but you need to add cellrect class to the first selection if you want to use this class to select the elements again

```<code>heatNode.selectAll(".cellrect")
   .data(data, function(d) { return d.row + ":" + d.col; })
   .enter()
   .append("rect")
   .attr("x", function(d) { return (d.col - 1) * (cellWidth + cellMargin);})
   .attr("y", function(d) { return (d.row - 1) * (cellHeight +  + cellMargin); })
   .attr("class", function(d) { return "cellrect cell cell-border cr" + (d.row-1) + " cc" + (d.col-1); })
</code>```

...

Body:
I'm using d3js v3 have a heat map that upon changing a ratio button selection I would switch the data from one dataset to another. The initialization requires a lot of steps e.g.

var svg = d3.select("#myId").append("svg");
...
var heatNode = svg.append("g");
heatNode.selectAll(".cellrect")
   .data(data, function(d) { return d.row + ":" + d.col; })
   .enter()
   .append("rect")
   .attr("x", function(d) { return (d.col - 1) * (cellWidth + cellMargin); })
   .attr("y", function(d) { return (d.row - 1) * (cellHeight +  + cellMargin); })
   .attr("class", function(d) { return "cell cell-border cr" + (d.row-1) + " cc" + (d.col-1); })
   .attr("width", cellWidth)
   .attr("height", cellHeight)
   .style("fill", function(d) { return colorScale(d.value); })
   .on("mouseover", function(d) {
       // highlight text
       d3.select(this).classed("cell-hover", true);
       d3.selectAll(id + " .rowLabel").classed("text-highlight", function(r, ri) { return ri == (d.row - 1); });
       d3.selectAll(id + " .colLabel").classed("text-highlight", function(c, ci) { return ci == (d.col - 1); });
            })
   .on("mouseout", function(d) {
       d3.select(this).classed("cell-hover", false);
       d3.selectAll(id + " .rowLabel").classed("text-highlight", false);
       d3.selectAll(id + " .colLabel").classed("text-highlight", false);
   });

and now I get new data and would like to update only the fill color and nothing else. So I have tried without succcess:

   heatNode.selectAll(".cellrect").transition().duration(2000)
       .data(newData, function(d) { return d.row + ":" + d.col; })
       .style("fill", function(d) { return colorScale(d.value); });

The only way that has worked for me so far is doing an ugly:

   heatNode.selectAll("*").transition().duration(2000).remove();

and recreating everything again, however, not even then the transition works for me.

Body:
The code seems right but you need to add cellrect class to the first selection if you want to use this class to select the elements again

heatNode.selectAll(".cellrect")
   .data(data, function(d) { return d.row + ":" + d.col; })
   .enter()
   .append("rect")
   .attr("x", function(d) { return (d.col - 1) * (cellWidth + cellMargin);})
   .attr("y", function(d) { return (d.row - 1) * (cellHeight +  + cellMargin); })
   .attr("class", function(d) { return "cellrect cell cell-border cr" + (d.row-1) + " cc" + (d.col-1); })

...


问:
Redirect to a specific URL with Javascript
what i want to do is simple, let's say I have a URL like this https://www.example.com/pro?type=oil coming from the URL it could anything like /pro?type=beans or /pro?type=rice and what I want is to get the URL redirect it to something like this https://www.example.com/zpro?type=oil. PLEASE THE FIRST URL is /pro? the redirect location is /zpro? Thank you.

答: So you can use window.location.href to access the string of the current URL. By setting it to a new value, you can change the current URL! So for you, that means setting window.location.href = window.location.href.replace('/pro', '/zpro'). This will take the string /pro in your URL and redirect to /zpro while keeping your query parameters intact!


问:
.next() and .prev() to loop through divs
I want to use simple jQuery to perform slide through div elements. But how do I use next() and prev() to go through slide items?

The problem is when you go next, next, next, next. The div finally stops and doesn't show; it doesn't loop round back to the first div.

This is what I've got so far:

$("p.right").click(function() {
  $(".item.active").removeClass("active").next(".item").addClass("active").show();
});
$("p.left").click(function() {
  $(".item.active").removeClass("active").prev(".item").addClass("active").show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}</code>```

First Item

Second Item

Third Item

Last Item

N

P

```

答:
Below is a working solution to loop around when you get to either end of the list of items -- though the p.left function won't go from first to last here because of the way the SO snippet is coded (using
s).

The p.right function works as intended, and the p.left function would work similarly, in a "normal" web environment.

$("p.right").click(function() {
  if ($("div.active").next("div").text() == "") {
    // if at the last item, loop around
    $("div.active").removeClass("active");
    $("div").first().addClass("active").show();
  } else {
    // else go to the next one
    $("div.active").removeClass("active").next("div").addClass("active").show();
  }
});
$("p.left").click(function() {
  if ($("div.active").prev("div").text() == "") {
    // if at the first item, loop around
    $("div.active").removeClass("active");
    $("div").last().addClass("active").show();
  } else {
    // else go to the previous one
    $("div.active").removeClass("active").prev("div").addClass("active").show();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}</code>```

First Item

Second Item

Third Item

Last Item

N

P

```

Body:
I want to use simple jQuery to perform slide through div elements. But how do I use next() and prev() to go through slide items?

The problem is when you go next, next, next, next. The div finally stops and doesn't show; it doesn't loop round back to the first div.

This is what I've got so far:

$("p.right").click(function() {
  $(".item.active").removeClass("active").next(".item").addClass("active").show();
});
$("p.left").click(function() {
  $(".item.active").removeClass("active").prev(".item").addClass("active").show();
});

Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}

First Item

Second Item

Third Item

Last Item

N

P

Body:
Below is a working solution to loop around when you get to either end of the list of items -- though the p.left function won't go from first to last here because of the way the SO snippet is coded (using <div>s).

The p.right function works as intended, and the p.left function would work similarly, in a "normal" web environment.

$("p.right").click(function() {
  if ($("div.active").next("div").text() == "") {
    // if at the last item, loop around
    $("div.active").removeClass("active");
    $("div").first().addClass("active").show();
  } else {
    // else go to the next one
    $("div.active").removeClass("active").next("div").addClass("active").show();
  }
});
$("p.left").click(function() {
  if ($("div.active").prev("div").text() == "") {
    // if at the first item, loop around
    $("div.active").removeClass("active");
    $("div").last().addClass("active").show();
  } else {
    // else go to the previous one
    $("div.active").removeClass("active").prev("div").addClass("active").show();
  }
});

Section {
  position: relative;
  height: 200px;
  width: 200px;
  text-align: center;
}

p {
  position: absolute;
  margin: 0px;
  padding: 5px 10px;
  background: blue;
  color: #ffffff;
  border-radius: 100%;
}

p.left {
  top: 0px;
  left: 20px;
}

p.right {
  top: 0px;
  right: 20px;
}

div {
  display: none;
}

div.active {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="active">First Item</div>
  <div>Second Item</div>
  <div>Third Item</div>
  <div>Last Item</div>
  <p class="right">N</p>
  <p class="left">P</p>
</section>


问:
How to copy paste a modal
For a school project I want to make modals for every student in my class. My problem is that only the first modal is working.

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 14% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: none;
  width: 80%;
  /* Could be more or less, depending on screen size */
  box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/* Button Design */

#myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
  font-family: Lato-Bold;
  font-size: 20px;
  background-color: rgb(55, 154, 177);
  background-size: cover;
  width: 300px;
  height: 300px;
  margin: 10px;
  float: left;
  text-align: center;
  color: white;
  border: 0;
  cursor: pointer;
}

p.Info {
  font-family: Lato-regular;
  font-size: 15px;
  color: rgb(40, 40, 40);
}</code>```

<button id="myBtn">Anthony</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxxxbr> Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

<button id="myBtn">David</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxx

 Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

```

答:
Here is more generalized approach that relies on the ordering of the dom elements.

In this case if you wanted to add more, all you would have to do is copy the button and modal html and change the content. You wouldn't have to change the code, css, or div id's.

JSFiddle of the same.

// Get the modals
var modals = document.getElementsByClassName('myModal');

// Get the buttons that opens the modals
var btns = document.getElementsByClassName("myBtn");

// Get the  elements that closes the modals
var spans = document.getElementsByClassName("close");

function makeShower(index) {
 return function(event) {
   modals[index].style.display = "block";
  }
}

function makeHider(index) {
 return function(event) {
   modals[index].style.display = "none";
  }
}

for (let i = 0; i < btns.length; i++) {
  btns[i].onclick = makeShower(i);
  spans[i].onclick = makeHider(i);
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target.className == "myModal modal") {
    event.target.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 14% auto; /* 15% from the top and centered */
    padding: 20px;
    border: none;
    width: 80%; /* Could be more or less, depending on screen size */
        box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
/* Button Design */
.myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
   font-family: Lato-Bold;
   font-size: 20px;
   background-color: rgb(55, 154, 177);
   background-size:cover;
   width: 300px;
   height: 300px;
   margin: 10px;
   float: left;
   text-align: center;
   color:white;
   border:0;
   cursor: pointer;
}

p.Info {
     font-family: Lato-regular;
     font-size: 15px;
     color: rgb(40, 40, 40);

}</code>```

<button class="myBtn">Anthony</button>

×

Nachname:König

Vorname:Anthony

Geburtstag:24.12.1998

Herkunft:Deutschland

Adresse:xxxxxxxxxxxxxxxxx

Mobilnummer:xxxxxxxxxxxxxx

E-Mail:xxxxxxxxxxxxxxxxxbr>
Fachlicher Schwerpunkt:Programmieren

Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.

Socialmedia:url Facebook: url Instagram:

Snapcode: anthony.k1ng

<button class="myBtn">David</button>

×

Nachname:David

Vorname:David

Geburtstag:24.12.1998

Herkunft:Deutschland

Adresse:xxxxxxxxxxxxxxxxxxxxxx

Mobilnummer:xxxxxxxxxxxxxxxxxx

E-Mail:xxxxxxxxxxxxxxxx

Fachlicher Schwerpunkt:Programmieren

Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.

Socialmedia:url Facebook: url Instagram:

Snapcode: anthony.k1ng

```

Title: How to copy paste a modal

Body:
For a school project I want to make modals for every student in my class. My problem is that only the first modal is working.

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 14% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: none;
  width: 80%;
  /* Could be more or less, depending on screen size */
  box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/* Button Design */

#myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
  font-family: Lato-Bold;
  font-size: 20px;
  background-color: rgb(55, 154, 177);
  background-size: cover;
  width: 300px;
  height: 300px;
  margin: 10px;
  float: left;
  text-align: center;
  color: white;
  border: 0;
  cursor: pointer;
}

p.Info {
  font-family: Lato-regular;
  font-size: 15px;
  color: rgb(40, 40, 40);
}

<button id="myBtn">Anthony</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxxxbr> Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

<button id="myBtn">David</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxx

 Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

Body:
Here is more generalized approach that relies on the ordering of the dom elements.

In this case if you wanted to add more, all you would have to do is copy the button and modal html and change the content. You wouldn't have to change the code, css, or div id's.

JSFiddle of the same.

// Get the modals
var modals = document.getElementsByClassName('myModal');

// Get the buttons that opens the modals
var btns = document.getElementsByClassName("myBtn");

// Get the <span> elements that closes the modals
var spans = document.getElementsByClassName("close");

function makeShower(index) {
 return function(event) {
   modals[index].style.display = "block";
  }
}

function makeHider(index) {
 return function(event) {
   modals[index].style.display = "none";
  }
}

for (let i = 0; i < btns.length; i++) {
  btns[i].onclick = makeShower(i);
  spans[i].onclick = makeHider(i);
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target.className == "myModal modal") {
    event.target.style.display = "none";
  }
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 14% auto; /* 15% from the top and centered */
    padding: 20px;
    border: none;
    width: 80%; /* Could be more or less, depending on screen size */
        box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
/* Button Design */
.myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
   font-family: Lato-Bold;
   font-size: 20px;
   background-color: rgb(55, 154, 177);
   background-size:cover;
   width: 300px;
   height: 300px;
   margin: 10px;
   float: left;
   text-align: center;
   color:white;
   border:0;
   cursor: pointer;
}

p.Info {
     font-family: Lato-regular;
     font-size: 15px;
     color: rgb(40, 40, 40);

}

  <!-- Trigger/Open The Modal -->
<button class="myBtn">Anthony</button>

<!-- The Modal -->
<div class="myModal modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p class="Info">
Nachname:König<br>
Vorname:Anthony<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxxxbr>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>
 <!-- Trigger/Open The Modal -->
<button class="myBtn">David</button>

<!-- The Modal -->
<div class="myModal modal" >

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p class="Info">
Nachname:David<br>
Vorname:David<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxx<br>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>


问:
how to test braintree webhooks with different notification types
I want to test my webhook functionality with different notifications. Right now I am able to test it only for canceling subscriptions (by cancelling the subscription from the backend of braintree).

```<code>$webhookNotification = Braintree_WebhookNotification::parse($sampleNotification["bt_signature"], $sampleNotification["bt_payload"]);
</code>```

I have also tried https://www.braintreepayments.com/docs/php/webhooks/testing:

```<code>$sampleNotification = Braintree_WebhookTesting::sampleNotification(Braintree_WebhookNotification::SUBSCRIPTION_WENT_ACTIVE,'1234qwe');
$webhookNotification = Braintree_WebhookNotification::parse($sampleNotification["bt_signature"], $sampleNotification["bt_payload"]);
</code>```

But the result the API returns is not satisfactory. It always returns the same array for all notification types whether the subscription id exists or not.

答:
Here is my testing script that send example testing post data to localhost webhook URL:

```<code><?php
require_once __DIR__ . '/vendor/autoload.php';

// your sandbox data
\Braintree\Configuration::environment('env...');
\Braintree\Configuration::merchantId('id');
\Braintree\Configuration::publicKey('your key');
\Braintree\Configuration::privateKey('your key');

$kind = isset($argv[1]) ? $argv[1] : \Braintree\WebhookNotification::CHECK;
$id = isset($argv[2]) ? $argv[2] : null;

$sampleNotification = \Braintree\WebhookTesting::sampleNotification($kind, $id);
$signature = $sampleNotification['bt_signature'];
$payload = $sampleNotification['bt_payload'];

// Submit a payload and signature to handler
$ch = curl_init('http://localhost/braintree.hook.php'); // Your URL
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
  ['bt_signature' => $signature, 'bt_payload' => $payload]
);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

echo curl_exec($ch);
</code>```

You can send two params to this script first kind and second id. That allow you to change event kind - check out documentation. Follow an example, how to generate subscription_canceled event:

```<code>php webhook.tests.php subscription_canceled 123456 > output.txt
</code>```

Body:
I want to test my webhook functionality with different notifications. Right now I am able to test it only for canceling subscriptions (by cancelling the subscription from the backend of braintree).

$webhookNotification = Braintree_WebhookNotification::parse($sampleNotification["bt_signature"], $sampleNotification["bt_payload"]);

I have also tried https://www.braintreepayments.com/docs/php/webhooks/testing:

$sampleNotification = Braintree_WebhookTesting::sampleNotification(Braintree_WebhookNotification::SUBSCRIPTION_WENT_ACTIVE,'1234qwe');
$webhookNotification = Braintree_WebhookNotification::parse($sampleNotification["bt_signature"], $sampleNotification["bt_payload"]);

But the result the API returns is not satisfactory. It always returns the same array for all notification types whether the subscription id exists or not.

Body:
Here is my testing script that send example testing post data to localhost webhook URL:

<?php
require_once __DIR__ . '/vendor/autoload.php';

// your sandbox data
\Braintree\Configuration::environment('env...');
\Braintree\Configuration::merchantId('id');
\Braintree\Configuration::publicKey('your key');
\Braintree\Configuration::privateKey('your key');

$kind = isset($argv[1]) ? $argv[1] : \Braintree\WebhookNotification::CHECK;
$id = isset($argv[2]) ? $argv[2] : null;

$sampleNotification = \Braintree\WebhookTesting::sampleNotification($kind, $id);
$signature = $sampleNotification['bt_signature'];
$payload = $sampleNotification['bt_payload'];

// Submit a payload and signature to handler
$ch = curl_init('http://localhost/braintree.hook.php'); // Your URL
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
  ['bt_signature' => $signature, 'bt_payload' => $payload]
);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

echo curl_exec($ch);

You can send two params to this script first kind and second id. That allow you to change event kind - check out documentation. Follow an example, how to generate subscription_canceled event:

php webhook.tests.php subscription_canceled 123456 > output.txt


问:
Blas SGEMM error in tensorflow
When I try to run my model i got

```<code>InternalError (see above for traceback): Blas SGEMM launch failed : m=3686400, n=2, k=1
</code>```

Runnin under Windows 10, Cuda 8.0, with gpu wih compute compatibility 3.0 (Ge Force 760m)

code:

```<code> with tf.name_scope('input'):
        x = tf.placeholder(tf.float16, shape=[None, 720, 1280, 1], name='x-input')
        y_ = tf.placeholder(tf.uint8, shape=[None, ], name='y-input')

    y_onehot = tf.one_hot(y_, depth=2)

    conv1 = tf.layers.conv2d(
        inputs=x,
        filters=1,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)

    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=2,
        kernel_size=[1, 1],
        padding="same",
        activation=tf.nn.relu)

    logits = tf.reduce_mean(conv2, axis=[1, 2])

    y = tf.argmax(logits, axis=1)

    loss_op = tf.losses.softmax_cross_entropy(onehot_labels=y_onehot, logits=logits)
    train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss_op, global_step=tf.train.get_global_step())

    acc_op = tf.metrics.accuracy(labels=y_, predictions=tf.cast(y, tf.uint8))
</code>```

答: by some reason float16 are not supported, use float32 instead</p>

Title: Blas SGEMM error in tensorflow

Body:
When I try to run my model i got

InternalError (see above for traceback): Blas SGEMM launch failed : m=3686400, n=2, k=1

Runnin under Windows 10, Cuda 8.0, with gpu wih compute compatibility 3.0 (Ge Force 760m)

code:

 with tf.name_scope('input'):
        x = tf.placeholder(tf.float16, shape=[None, 720, 1280, 1], name='x-input')
        y_ = tf.placeholder(tf.uint8, shape=[None, ], name='y-input')

    y_onehot = tf.one_hot(y_, depth=2)

    conv1 = tf.layers.conv2d(
        inputs=x,
        filters=1,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)

    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=2,
        kernel_size=[1, 1],
        padding="same",
        activation=tf.nn.relu)

    logits = tf.reduce_mean(conv2, axis=[1, 2])

    y = tf.argmax(logits, axis=1)

    loss_op = tf.losses.softmax_cross_entropy(onehot_labels=y_onehot, logits=logits)
    train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss_op, global_step=tf.train.get_global_step())

    acc_op = tf.metrics.accuracy(labels=y_, predictions=tf.cast(y, tf.uint8))


问:
adding same class to div using another divs class
i need your help. I´m totally new to javascript but i was able to make a website using some functions. Now my question is:

All in all i got 77 divs and 77 paths. I want every path to get the same class as the div that belongs to the path. Every div and every path has its own ID. My index markup looks like this:

```<code><div id="div_1" class="div_class_1"></div>
<div id="div_2" class="div_class_2"></div>
<div id="div_3" class="div_class_3"></div>
<div id="div_4" class="div_class_4"></div>
  ....
<div id="div-77"></div>

<div id="map">
  <path id="path_1" class="get class from #div_1"></path>
  <path id="path_2" class="get class from #div_2"></path>
  <path id="path_3" class="get class from #div_3"></path>
  <path id="path_4" class="get class from #div_4"></path>
    ...
  <path id="path_77" class="get class from #div_77"></path>
</div>
</code>```

So basically when the page is loaded i want the function to read the class of #div_1 to add it as class for #path_1.

答:
You can use .each method to iterate over div elements and update your path class elements based on the div id, here is a working example:

$( document ).ready(function() {

    $('#divs').children('div').each( function () {

      var index = $(this).attr('id').split('_')[1];
      console.log(index);

      $('#path_' + index).addClass($(this).attr("class"));

    });

    console.log($('#map').html());

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="divs">
  <div id="div_1" class="div_class_1"></div>
  <div id="div_2" class="div_class_2"></div>
  <div id="div_3" class="div_class_3"></div>
  <div id="div_4" class="div_class_4"></div>
  <div id="div_77" class="div_class_77"></div>
</div>

<div id="map">
  <path id="path_1" class=""></path>
  <path id="path_2" class=""></path>
  <path id="path_3" class=""></path>
  <path id="path_4" class=""></path>
  <path id="path_77" class=""></path>
</div></code>```

Body:
i need your help. I´m totally new to javascript but i was able to make a website using some functions. Now my question is:

All in all i got 77 divs and 77 paths. I want every path to get the same class as the div that belongs to the path. Every div and every path has its own ID. My index markup looks like this:

  ....

  <path id="path_1" class="get class from #div_1"></path>
  <path id="path_2" class="get class from #div_2"></path>
  <path id="path_3" class="get class from #div_3"></path>
  <path id="path_4" class="get class from #div_4"></path>
    ...
  <path id="path_77" class="get class from #div_77"></path>

So basically when the page is loaded i want the function to read the class of #div_1 to add it as class for #path_1.

Body:
You can use .each method to iterate over div elements and update your path class elements based on the div id, here is a working example:

$( document ).ready(function() {

    $('#divs').children('div').each( function () {

      var index = $(this).attr('id').split('_')[1];
      console.log(index);

      $('#path_' + index).addClass($(this).attr("class"));

    });

    console.log($('#map').html());

});

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

<div id="divs">
  <div id="div_1" class="div_class_1"></div>
  <div id="div_2" class="div_class_2"></div>
  <div id="div_3" class="div_class_3"></div>
  <div id="div_4" class="div_class_4"></div>
  <div id="div_77" class="div_class_77"></div>
</div>

<div id="map">
  <path id="path_1" class=""></path>
  <path id="path_2" class=""></path>
  <path id="path_3" class=""></path>
  <path id="path_4" class=""></path>
  <path id="path_77" class=""></path>
</div>


问:
Selenium Exception : No sessionId Provided
I am working on getting rid of many Selenium exceptions I have been getting from quite some time(Which mostly turn out to be false positives). One of the many exceptions I have been getting is the exception Selenium.SeleniumException : No SessionId provided.Due to which all the tests after that are not carried out.

The details of the exception say the following :

SetUp method failed.
  Selenium.SeleniumException : ERROR:
  ERROR: No sessionId provided. Most
  likely your original newBrowserSession
  command failed. at
  Selenium.HttpCommandProcessor.DoCommand(String
  command, String[] args) in
  c:\hudson\workspace\selenium-rc-trunk-win-headless\trunk\clients\dotnet\src\Core\HttpCommandProcessor.cs:line
  98 at
  Selenium.HttpCommandProcessor.Stop()
  in
  c:\hudson\workspace\selenium-rc-trunk-win-headless\trunk\clients\dotnet\src\Core\HttpCommandProcessor.cs:line
  171 at Selenium.DefaultSelenium.Stop()
  in
  c:\hudson\workspace\selenium-rc-trunk-win-headless\trunk\clients\dotnet\src\Core\DefaultSelenium.cs:line
  154 at
  ProductionDiagnostics.TestAttributes.TearDownUseCase()
  in
  C:\BuildAgent\work\11a8046c96ca46b\ProductionDiagnostics\NUnitTests\TestAttributes.vb:line
  121 at
  ProductionDiagnostics.TestAttributes.SetupUseCase()
  in
  C:\BuildAgent\work\11a8046c96ca46b\ProductionDiagnostics\NUnitTests\TestAttributes.vb:line
  99

What can help me in going ahead is that why is the newbrowserSession command failing and what can be the probable causes for the same ??

Also, we recently updated the grid to 1.0.8 from 1.0.7 . Should that be a cause of trouble ??

答:
I'm pretty sure its not a hardware problem.

You did not provide any of the code etc and but from the file path in your error syntac I can see it's Hudson who executes the tests and you will run into problem when there are several instances of Selenium RC started from Hudson as they are not thread safe then.

You need to look into using this class: ThreadSafeSeleniumSessionStorage

Update
Have a look on this one:
 http://old.nabble.com/Problem,-Selenium-RC--sessionId--doesn't-exist--perhaps-this-session-was-already-stopped--td17633858.html


问:
jQuery change background color with fade and return back to original with delay
I have the following function, that is supposed to change the background color with fade, then using delay return back to the original color. And endlessly repeat.

```<code>$(function () {
    $('div').animate({background-color: 'blue'}, 'slow', function () {
    $(this).delay(500).animate({background-color: 'red'}, 'slow');
 });
});
</code>```

However it doesn't seem to work...
Any thoughts how to fix it?

答:
Please do not forget to include jquery-ui library. Else it does not work

$(document).ready(function() {

  $('.sample').click(function() {

    $(this).animate({
      backgroundColor: "green"
    }, 1000).delay(2000).queue(function() {
      $(this).animate({
        backgroundColor: "red"
      }, 1000).dequeue();
    });

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sample {
  font: normal 12px/18px 'Arial';
  color: #fff;
  background: red;
  padding: 20px;
  cursor: pointer
}</code>```

Click Me to see smooth background color transition and back to original background

```

Body:
I have the following function, that is supposed to change the background color with fade, then using delay return back to the original color. And endlessly repeat.

$(function () {
    $('div').animate({background-color: 'blue'}, 'slow', function () {
    $(this).delay(500).animate({background-color: 'red'}, 'slow');
 });
});

However it doesn't seem to work...
Any thoughts how to fix it?

Body:
Please do not forget to include jquery-ui library. Else it does not work

$(document).ready(function() {

  $('.sample').click(function() {

    $(this).animate({
      backgroundColor: "green"
    }, 1000).delay(2000).queue(function() {
      $(this).animate({
        backgroundColor: "red"
      }, 1000).dequeue();
    });

  });

});

.sample {
  font: normal 12px/18px 'Arial';
  color: #fff;
  background: red;
  padding: 20px;
  cursor: pointer
}

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="sample">
Click Me to see smooth background color transition and back to original background
</div>
</body>


问:
Execute an array of promises when it is ready
How do I get the promises to execute only after concatenation is done?</p>

```<code>var fs = require('fs');
var testFolder = './lib/';
var files = ['hello.txt', 'goodbye.txt'];
var contents = '';
//creating array of promises
let promises = files.map(async e => {
    return await fs.readFile(testFolder + e, "utf8", function (err, content) {
            contents += content + ".\n";
        });
 }
);
    console.log(promises);
    //this should happen last but "contents" is still empty string?
    Promise.all(promises).then(()=> console.log(contents));
</code>```

答:
fs.readFile doesn't return a promise.

You should use util.promisify to make it do so.

Furthermore, as mentioned by Patrick Hübl-Neschkudla in the comment below, there's no need to use async/await since readFile already returns a promise now and we're not processing the results until later.

Bergi also pointed out in the comments that fs.readFile callbacks aren't guaranteed to return in the order of creation. In fact that's the case for most fs operations because other processes can always interfere with yours by manipulating files at the same time - for example, what if somebody writes to a file you're about to read?.

You should perform the concatenation once all reads are finished instead of doing it while they are happening (as they might get out of sync).

This will also make sure all rejections are properly caught no matter which promise (file read) fails.

```<code>const readFile = util.promisify(fs.readFile);

Promise.all(
  files.map(e => readFile(testFolder + e, "utf8"))
)
.then(contentArray => contentArray.join('.\n'))
.then(console.log);
</code>```

Body:
How do I get the promises to execute only after concatenation is done?

var fs = require('fs');
var testFolder = './lib/';
var files = ['hello.txt', 'goodbye.txt'];
var contents = '';
//creating array of promises
let promises = files.map(async e => {
    return await fs.readFile(testFolder + e, "utf8", function (err, content) {
            contents += content + ".\n";
        });
 }
);
    console.log(promises);
    //this should happen last but "contents" is still empty string?
    Promise.all(promises).then(()=> console.log(contents));

Body:
fs.readFile doesn't return a promise.

You should use util.promisify to make it do so.

Furthermore, as mentioned by Patrick Hübl-Neschkudla in the comment below, there's no need to use async/await since readFile already returns a promise now and we're not processing the results until later.

Bergi also pointed out in the comments that fs.readFile callbacks aren't guaranteed to return in the order of creation. In fact that's the case for most fs operations because other processes can always interfere with yours by manipulating files at the same time - for example, what if somebody writes to a file you're about to read?.

You should perform the concatenation once all reads are finished instead of doing it while they are happening (as they might get out of sync).

This will also make sure all rejections are properly caught no matter which promise (file read) fails.

const readFile = util.promisify(fs.readFile);

Promise.all(
  files.map(e => readFile(testFolder + e, "utf8"))
)
.then(contentArray => contentArray.join('.\n'))
.then(console.log);


问:
Inconsistent results in cuda GPU accelerated code
I was trying to compute Local Binary Patterns for a image on my GPU, utilising cuda module in python for the same. But the results produced by execution of similar algorithm on CPU and GPU is producing different results. Can you help me figure out the problem ?

Below is the snippet of code I was trying to execute :

```<code>from __future__ import division
from skimage.io import imread, imshow
from numba import cuda
import time
import math
import numpy

# CUDA Kernel
@cuda.jit
def pointKernelLBP(imgGPU, histVec, pos) :
    ''' Computes Point Local Binary Pattern '''
    row, col = cuda.grid(2)
    if row+1 < imgGPU.shape[0] and col+1 < imgGPU.shape[1] and col-1>=0 and row-1>=0 :
        curPos = 0
        mask = 0
        for i in xrange(-1, 2) :
            for j in xrange(-1, 2) :
                if i==0 and j==0 :
                    continue
                if imgGPU[row+i][col+j] > imgGPU[row][col] :
                    mask |= (1<<curPos)
                curPos+=1
        histVec[mask]+=1

#Host Code for computing LBP
def pointLBP(x, y, img) :
    ''' Computes Local Binary Pattern around a point (x,y),
    considering 8 nearest neighbours '''
    pos = [0, 1, 2, 7, 3, 6, 5, 4]
    curPos = 0
    mask = 0
    for i in xrange(-1, 2) :
        for j in xrange(-1, 2) :
            if i==0 and j==0 :
                continue
            if img[x+i][y+j] > img[x][y] :
                mask |= (1<<curPos)
            curPos+=1
    return mask

def LBPHistogram(img, n, m) :
    ''' Computes LBP Histogram for given image '''
    HistVec = [0] * 256
    for i in xrange(1, n-1) :
        for j in xrange(1, m-1) :
            HistVec[ pointLBP(i, j, img) ]+=1
    return HistVec

if __name__ == '__main__' :

    # Reading Image
    img = imread('cat.jpg', as_grey=True)
    n, m = img.shape

    start = time.time()
    imgHist = LBPHistogram(img, n, m)
    print "Computation time incurred on CPU : %s seconds.\n" % (time.time() - start)

    print "LBP Hisogram Vector Using CPU :\n"
    print imgHist

    print type(img)

    pos = numpy.ndarray( [0, 1, 2, 7, 3, 6, 5, 4] )

    img_global_mem = cuda.to_device(img)
    imgHist_global_mem = cuda.to_device(numpy.full(256, 0, numpy.uint8))
    pos_global_mem = cuda.to_device(pos)

    threadsperblock = (32, 32)
    blockspergrid_x = int(math.ceil(img.shape[0] / threadsperblock[0]))
    blockspergrid_y = int(math.ceil(img.shape[1] / threadsperblock[1]))
    blockspergrid = (blockspergrid_x, blockspergrid_y)

    start = time.time()
    pointKernelLBP[blockspergrid, threadsperblock](img_global_mem, imgHist_global_mem, pos_global_mem)
    print "Computation time incurred on GPU : %s seconds.\n" % (time.time() - start)

    imgHist = imgHist_global_mem.copy_to_host()

    print "LBP Histogram as computed on GPU's : \n"
    print imgHist, len(imgHist)
</code>```

答:
Now that you have fixed the glaringly obvious mistake in the original kernel code you posted, there are two problems which are preventing this code from working correctly.

The first, and most serious, is a memory race in the kernel. This update of the histogram bins:

```<code>histVec[mask]+=1
</code>```

is not safe. Multiple threads in multiple blocks will attempt to read and write the same bin counters in global memory simultaneously. CUDA offers no guarantees of either correctness or repeatability in such circumstances.

The simplest (but not necessarily the most performant, depending on your hardware) solution to this is to use atomic memory transactions. These do guarantee that the increment operation will be serialized, but of course that serialization implies some performance penalty. You can do this by changing the update code to something like:

```<code>cuda.atomic.add(histVec,mask,1)
</code>```

Note that CUDA only supports 32 and 64 bit atomic memory transactions, so you will need to ensure the type of histVec is a compatible 32 or 64 bit integer type.

This leads to the second problem, which is that you have defined the bin counter vector to be numpy.uint8. That means that even if you didn't have a memory race, you would only have 8 bits to store the counts, and they would quickly overflow for images of any meaningful size. So for both compatibility with atomic memory transactions and to prevent counter rollover, you will need to change the type of your counters.

When I changed these things in the code you posted (and fixed the early missing code problem), I could get exact agreement between GPU and host code calculated histograms for a random 8 bit input array.

The underlying parallel histogram problem is very well described for CUDA and there are a lot of examples and codebases you can study when you get to the point of worrying about performance, for example here.

Body:
I was trying to compute Local Binary Patterns for a image on my GPU, utilising cuda module in python for the same. But the results produced by execution of similar algorithm on CPU and GPU is producing different results. Can you help me figure out the problem ?

Below is the snippet of code I was trying to execute :

from __future__ import division
from skimage.io import imread, imshow
from numba import cuda
import time
import math
import numpy

# CUDA Kernel
@cuda.jit
def pointKernelLBP(imgGPU, histVec, pos) :
    ''' Computes Point Local Binary Pattern '''
    row, col = cuda.grid(2)
    if row+1 < imgGPU.shape[0] and col+1 < imgGPU.shape[1] and col-1>=0 and row-1>=0 :
        curPos = 0
        mask = 0
        for i in xrange(-1, 2) :
            for j in xrange(-1, 2) :
                if i==0 and j==0 :
                    continue
                if imgGPU[row+i][col+j] > imgGPU[row][col] :
                    mask |= (1<<curPos)
                curPos+=1
        histVec[mask]+=1

#Host Code for computing LBP
def pointLBP(x, y, img) :
    ''' Computes Local Binary Pattern around a point (x,y),
    considering 8 nearest neighbours '''
    pos = [0, 1, 2, 7, 3, 6, 5, 4]
    curPos = 0
    mask = 0
    for i in xrange(-1, 2) :
        for j in xrange(-1, 2) :
            if i==0 and j==0 :
                continue
            if img[x+i][y+j] > img[x][y] :
                mask |= (1<<curPos)
            curPos+=1
    return mask

def LBPHistogram(img, n, m) :
    ''' Computes LBP Histogram for given image '''
    HistVec = [0] * 256
    for i in xrange(1, n-1) :
        for j in xrange(1, m-1) :
            HistVec[ pointLBP(i, j, img) ]+=1
    return HistVec

if __name__ == '__main__' :

    # Reading Image
    img = imread('cat.jpg', as_grey=True)
    n, m = img.shape

    start = time.time()
    imgHist = LBPHistogram(img, n, m)
    print "Computation time incurred on CPU : %s seconds.\n" % (time.time() - start)

    print "LBP Hisogram Vector Using CPU :\n"
    print imgHist

    print type(img)

    pos = numpy.ndarray( [0, 1, 2, 7, 3, 6, 5, 4] )

    img_global_mem = cuda.to_device(img)
    imgHist_global_mem = cuda.to_device(numpy.full(256, 0, numpy.uint8))
    pos_global_mem = cuda.to_device(pos)

    threadsperblock = (32, 32)
    blockspergrid_x = int(math.ceil(img.shape[0] / threadsperblock[0]))
    blockspergrid_y = int(math.ceil(img.shape[1] / threadsperblock[1]))
    blockspergrid = (blockspergrid_x, blockspergrid_y)

    start = time.time()
    pointKernelLBP[blockspergrid, threadsperblock](img_global_mem, imgHist_global_mem, pos_global_mem)
    print "Computation time incurred on GPU : %s seconds.\n" % (time.time() - start)

    imgHist = imgHist_global_mem.copy_to_host()

    print "LBP Histogram as computed on GPU's : \n"
    print imgHist, len(imgHist)

Body:
Now that you have fixed the glaringly obvious mistake in the original kernel code you posted, there are two problems which are preventing this code from working correctly.

The first, and most serious, is a memory race in the kernel. This update of the histogram bins:

histVec[mask]+=1

is not safe. Multiple threads in multiple blocks will attempt to read and write the same bin counters in global memory simultaneously. CUDA offers no guarantees of either correctness or repeatability in such circumstances.

The simplest (but not necessarily the most performant, depending on your hardware) solution to this is to use atomic memory transactions. These do guarantee that the increment operation will be serialized, but of course that serialization implies some performance penalty. You can do this by changing the update code to something like:

cuda.atomic.add(histVec,mask,1)

Note that CUDA only supports 32 and 64 bit atomic memory transactions, so you will need to ensure the type of histVec is a compatible 32 or 64 bit integer type.

This leads to the second problem, which is that you have defined the bin counter vector to be numpy.uint8. That means that even if you didn't have a memory race, you would only have 8 bits to store the counts, and they would quickly overflow for images of any meaningful size. So for both compatibility with atomic memory transactions and to prevent counter rollover, you will need to change the type of your counters.

When I changed these things in the code you posted (and fixed the early missing code problem), I could get exact agreement between GPU and host code calculated histograms for a random 8 bit input array.

The underlying parallel histogram problem is very well described for CUDA and there are a lot of examples and codebases you can study when you get to the point of worrying about performance, for example here.


问:
Implementation of std::disjunction in the Standard Library
I've seen the implementation of std::disjunction in the Standard Library (source):

```<code>template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };
</code>```

I am curious about the need to specialize disjunction<B1> as B1. Why is it better than my naive implementation of it?

```<code>template<class...>              struct or_t
    : std::false_type {};
template<class B1, class... Bn> struct or_t<B1, Bn...>
    : std::integral_constant<bool, bool(B1::value) || bool(or_t<Bn...>::value)> {};
</code>```

答:
moreover, disjunction<B1,...,BN> is required resulting in the last given type (BN) if all of them are falsy (see [meta.logical#10.2]).

The unary specialization disjunction<B1> implements this behaviour in the tail of the recursive sequence.

For example, without the unary specialization, disjunction<B1> would give B1 if B1::value is true, and std::false_type otherwise.

Since all Bs might have different types, std::disjunction returns the first type whose ::value member converts to true. Isn't that a bit strange? It might be useful to make a funny selector

indeed, I've never used this family of traits(yet), but it seems quite a flexible abstraction:

```<code>template<class T>
struct some_condition: std::bool_constant</*whatever*/>
{
  using payload = T;
};

// take the first T satisfying some_condition, or last T if none does
disjunction<some_condition<T>...>::payload

// take the first T satisfying some_condition, or none
disjunction<some_condition<T>...,none_type>::payload
</code>```

the only thing I hate about disjunction is its name ...

Body:
I've seen the implementation of std::disjunction in the Standard Library (source):

template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };

I am curious about the need to specialize disjunction<B1> as B1. Why is it better than my naive implementation of it?

template<class...>              struct or_t
    : std::false_type {};
template<class B1, class... Bn> struct or_t<B1, Bn...>
    : std::integral_constant<bool, bool(B1::value) || bool(or_t<Bn...>::value)> {};

Body:
moreover, disjunction<B1,...,BN> is required resulting in the last given type (BN) if all of them are falsy (see [meta.logical#10.2]).

The unary specialization disjunction<B1> implements this behaviour in the tail of the recursive sequence.

For example, without the unary specialization, disjunction<B1> would give B1 if B1::value is true, and std::false_type otherwise.

Since all Bs might have different types, std::disjunction returns the first type whose ::value member converts to true. Isn't that a bit strange? It might be useful to make a funny selector

indeed, I've never used this family of traits(yet), but it seems quite a flexible abstraction:

template<class T>
struct some_condition: std::bool_constant</*whatever*/>
{
  using payload = T;
};

// take the first T satisfying some_condition, or last T if none does
disjunction<some_condition<T>...>::payload

// take the first T satisfying some_condition, or none
disjunction<some_condition<T>...,none_type>::payload

the only thing I hate about disjunction is its name ...


问:
Jenkins: Execute AWS CLI command inside a pipeline Jenkins file
Do you know how to execute AWS CLI command inside a Jenkinsfile in order to build a pipeline? I didn't find any plugins

答:
First of all you need to install AWS CLI in Jenkins instance in order to perform calls to your environment.

To setup it you need to create a new user to Jenkins in AWS and configure properly the keys. Take a look here: http://docs.aws.amazon.com/systems-manager/latest/userguide/automation-jenkins.html

After that you can do calls inside your Jenkins jobs using 'Shell commands' to AWS CLI:

```<code>aws ec2 describe-security-groups
</code>```

If you are using Ansible as your automation tool, take a look here:
https://aws.amazon.com/blogs/apn/getting-started-with-ansible-and-dynamic-amazon-ec2-inventory-management/

ContentLicense: CC BY-SA 4.0

Body:
First of all you need to install AWS CLI in Jenkins instance in order to perform calls to your environment.

To setup it you need to create a new user to Jenkins in AWS and configure properly the keys. Take a look here: http://docs.aws.amazon.com/systems-manager/latest/userguide/automation-jenkins.html

After that you can do calls inside your Jenkins jobs using 'Shell commands' to AWS CLI:

aws ec2 describe-security-groups

If you are using Ansible as your automation tool, take a look here:
https://aws.amazon.com/blogs/apn/getting-started-with-ansible-and-dynamic-amazon-ec2-inventory-management/


问:
how to pass date via url parameter - junit test with dates
I want to pass my Date via parameter, and I dont exactly know how to do it. I have tried EncodeUrl.encode(), but it didnt work (it is possible that I did something wrong)

```<code>@Test
public void getUsageCountersParam2Test() throws Exception {
    Date date = new Date(2017, 06, 23, 12, 39, 20);
    MvcResult result = mockMvc.perform(get(getUri("/usages?apiConsumerId=[1,2]&serviceId=1&dateFrom=" + date)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn();
    ObjectMapper mapper = new ObjectMapper();

    List<UsageCounterDetailsDto> list = mapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<UsageCounterDetailsDto>>() {
    });

    assertNotNull(list);
    assertEquals(3, list.size());
}
</code>```

I have an error such as:

```<code>org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value 'Mon Jul 23 12:39:20 CEST 3917'; nested exception is java.lang.IllegalArgumentException
</code>```

Hope you could helped me.

答:
Try something like this:</p>

```<code>    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
    String dateParam = sdf.format(date);
    MvcResult result = mockMvc.perform(get("/usages")
            .param("date", dateParam))
            .andExpect(status().isOk()).andReturn();
</code>```

Body:
I want to pass my Date via parameter, and I dont exactly know how to do it. I have tried EncodeUrl.encode(), but it didnt work (it is possible that I did something wrong)

@Test
public void getUsageCountersParam2Test() throws Exception {
    Date date = new Date(2017, 06, 23, 12, 39, 20);
    MvcResult result = mockMvc.perform(get(getUri("/usages?apiConsumerId=[1,2]&serviceId=1&dateFrom=" + date)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn();
    ObjectMapper mapper = new ObjectMapper();

    List<UsageCounterDetailsDto> list = mapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<UsageCounterDetailsDto>>() {
    });

    assertNotNull(list);
    assertEquals(3, list.size());
}

I have an error such as:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value 'Mon Jul 23 12:39:20 CEST 3917'; nested exception is java.lang.IllegalArgumentException

Hope you could helped me.

Body:
Try something like this:

    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
    String dateParam = sdf.format(date);
    MvcResult result = mockMvc.perform(get("/usages")
            .param("date", dateParam))
            .andExpect(status().isOk()).andReturn();


问:
Bash change number to another value on specific line
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

```<code><InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>
</code>```

答:
A solution using an XML parsing tool:

```<code>{ echo '<root>'; cat foo.config; echo '</root>'; } |
  xmlstarlet ed -O -P -u //UpdateInterval -v 0 |
  sed '1d;$d' |
  sponge foo.config
</code>```

The first line is to make the config file into a proper XML file.

The second line updates the value.

The third line removes the root tags.

The last line rewrites the config file. Need to install the moreutils package.

Body:
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

<InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>

Body:
A solution using an XML parsing tool:

{ echo '<root>'; cat foo.config; echo '</root>'; } |
  xmlstarlet ed -O -P -u //UpdateInterval -v 0 |
  sed '1d;$d' |
  sponge foo.config

The first line is to make the config file into a proper XML file.

The second line updates the value.

The third line removes the root tags.

The last line rewrites the config file. Need to install the moreutils package.


问:
Import <template> Element From Another Website
tl;dr: Trying to get <template> element hosted somewhere else, how do?

I have an html page locally, which has the following template in the  (The point is that it's some stuff within a template tag):

```<code>  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>
</code>```

As expected, this code doesn't template until I attach the template to some shadow-root, e.g.:

```<code><script>
  var template = document.querySelector('template');
  var containerHost = document.querySelector('.containerHost');
  var shadowRoot = containerHost.createShadowRoot();
  shadowRoot.appendChild(document.importNode(template.content, true));
</script>
</code>```

When I run the code above, my template displays. Great. Now I am trying to move my web component to a website hosted somewhere else. So I created a github page that I confirmed works: https://myusername.github.io/webcomponent/.

That is a complete html page, that has my template (same as above) in the head. I then try to pull in the html from the github page into my html using:

```<code>  <link rel="import" href="https://myusername.github.io/webcomponent/">
</code>```

This throws no errors, but the <template> is NOT visible to my page and I get the following error:

Uncaught TypeError: Cannot read property 'content' of null
      at web-component2.html:31

Because var template = document.querySelector('template'); returns null.

What gives? How do I get to my template?

P.S.
Using this page as a guide

Got the html import statement from here

Edit:

I see a request going out to my site and coming back with a 304, this is the response:

```<code><html>
<head>

  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>

</head>
<body>
</body>
</html>
</code>```

So the html I expect comes back fine (but is not accessible from my local page) - I am not sure if I need to isolate the <template> or am missing something equally simple.

答:
In case the linked article about imports goes away: once your imported content is fetched, you have to grab the content from the <link> element, not from document:

```<code>function getTemplate(e) {
  let template = e.target.import.querySelector("template");
  shadowRoot.appendChild(document.importNode(template.content, true));
}
...

<link rel=import href="http://what.ever" onload="getTemplate(event)">
</code>```

for example. The <link> element has an "import" property that serves as the root of the document that's been imported, and you can then use querySelector() (and presumably other document style APIs) to dig around and find stuff in what was imported.

Body:
tl;dr: Trying to get <template> element hosted somewhere else, how do?

I have an html page locally, which has the following template in the  (The point is that it's some stuff within a template tag):

  <template>

1

  </template>

As expected, this code doesn't template until I attach the template to some shadow-root, e.g.:

When I run the code above, my template displays. Great. Now I am trying to move my web component to a website hosted somewhere else. So I created a github page that I confirmed works: https://myusername.github.io/webcomponent/.

That is a complete html page, that has my template (same as above) in the head. I then try to pull in the html from the github page into my html using:

  <link rel="import" href="https://myusername.github.io/webcomponent/">

This throws no errors, but the <template> is NOT visible to my page and I get the following error:

Uncaught TypeError: Cannot read property 'content' of null
      at web-component2.html:31

Because var template = document.querySelector('template'); returns null.

What gives? How do I get to my template?

P.S.
Using this page as a guide

Got the html import statement from here

Edit:

I see a request going out to my site and coming back with a 304, this is the response:

  <template>

1

  </template>

So the html I expect comes back fine (but is not accessible from my local page) - I am not sure if I need to isolate the <template> or am missing something equally simple.

Body:
In case the linked article about imports goes away: once your imported content is fetched, you have to grab the content from the <link> element, not from document:

function getTemplate(e) {
  let template = e.target.import.querySelector("template");
  shadowRoot.appendChild(document.importNode(template.content, true));
}
...

<link rel=import href="http://what.ever" onload="getTemplate(event)">

for example. The <link> element has an "import" property that serves as the root of the document that's been imported, and you can then use querySelector() (and presumably other document style APIs) to dig around and find stuff in what was imported.


问:
QBO3 Attachment Templates - header images from a URL
We have hundreds of attachment templates in QBO that are based on Microsoft Word templates, and each embed our company logo in the header.

Rather than having the template show the header and footer in each document we would like to consider the possibility of saving the Headers & Footers as Images in QBO and just having the Template reference the saved image when it generates the letters.

We are not sure how or where the image would be stored and how the reference in the attachment template would work.

答:
Word is capable of using images from any URL in the document, as described here and in a video. For your use case, consider using images stored on your corporate website, rather than storing the images in QBO.

As with all records in QBO, users must log in to access them, so images stored in QBO would require the user (in this case, the person opening the merged Word document) to log in to view the header.


问:
Django bug - auto_now_add field is Null
My model has a custom primary key and a DateTimefield with auto_now_add = True:

```<code>slug = models.CharField(max_length=5, primary_key=True)
created_on = models.DateTimeField(auto_now_add=True)
</code>```

I noticed that a handful of objects out of several hundred have a value of Null for "created_on", even though this field does not allow Null values. Any ideas how this is possible?

This key is randomly generated via this custom save override:

```<code>def save(self, *args, **kwargs):
    if self.slug == '':
        self.slug = generate_random_slug()
    while True:
        try:
            super(MyClass, self).save(*args, **kwargs)
            break
        except IntegrityError:
            self.slug = generate_random_slug()
</code>```

答:
If you try to save an object that has a field with primary_key=True and another with auto_now_add=True where there is already an object in the db with the same primary key value it will cause an error to be thrown by the DB or possibly just set it null. Looks like you most likely are getting a collision in your slug (looks like it is 5 chars long which is going to create collisions pretty easily). You probably want to use a generate_random_slug with lower collision probability. Something like uuid could be useful.

This is a hypothesis and would need to see more code to confirm.

Title: Django bug - auto_now_add field is Null

Body:
My model has a custom primary key and a DateTimefield with auto_now_add = True:

slug = models.CharField(max_length=5, primary_key=True)
created_on = models.DateTimeField(auto_now_add=True)

I noticed that a handful of objects out of several hundred have a value of Null for "created_on", even though this field does not allow Null values. Any ideas how this is possible?

This key is randomly generated via this custom save override:

def save(self, *args, **kwargs):
    if self.slug == '':
        self.slug = generate_random_slug()
    while True:
        try:
            super(MyClass, self).save(*args, **kwargs)
            break
        except IntegrityError:
            self.slug = generate_random_slug()