问:
Find the browsers default value for a CSS property with JavaScript
Is it possible to retrieve the browsers default value for a CSS property, ignoring any inline/imported styles, using JS?

Some context: I'm using JS to in-line all styles on a specific SVG element and its children (which allows me to turn it into a PNG using canvg). At the moment my output is hugely bloated with every single available style, I would like to be able to discard any properties which are using the browser default values from the array of styles that are include in-line.

Demo of what's happening:

$.extend($.fn, {
  makeCssInline: function() {
    this.each(function(idx, el) {
      var style = el.style;
      var properties = [];
      for (var property in style) {
        if ($(this).css(property)) {
          // TODO: Only in-line this style if it's not browser default
          properties.push(property + ':' + $(this).css(property));
        }
      }
      this.style.cssText = properties.join(';');
      $(this).children().makeCssInline();
    });
  }
});

$(document).ready(function() {
  $("#before").text($("svg")[0].outerHTML.length);
  $("svg").makeCssInline();
  $("#after").text($("svg")[0].outerHTML.length);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg circle {
  fill: #080;
}

svg text {
  fill: #FFF;
}</code>```

<svg version="1.1" baseProfile="full" width="300" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="150" cy="50" r="50" />
  <text x="150" y="65" font-size="40" text-anchor="middle">SVG</text>
</svg>

Total characters before in-lining styles:

Total characters after in-lining styles:
```

As you can see, even for a simple SVG this process adds a huge amount of unnecessary data.

答:
You can compute the default style value of a newly created element by using getComputedStyle(). But the new element must be inserted in the DOM for this to work:

```<code>function getDefaultStyleOf(tagName, name)
{
    var element = document.createElement(tagName);

    document.body.appendChild(element);
    var value = getComputedStyle(element)[name];
    document.body.removeChild(element);

    return value;
}

console.log(getDefaultStyleOf('code', 'font-size'));
</code>```

Body:
Is it possible to retrieve the browsers default value for a CSS property, ignoring any inline/imported styles, using JS?

Some context: I'm using JS to in-line all styles on a specific SVG element and its children (which allows me to turn it into a PNG using canvg). At the moment my output is hugely bloated with every single available style, I would like to be able to discard any properties which are using the browser default values from the array of styles that are include in-line.

Demo of what's happening:

$.extend($.fn, {
  makeCssInline: function() {
    this.each(function(idx, el) {
      var style = el.style;
      var properties = [];
      for (var property in style) {
        if ($(this).css(property)) {
          // TODO: Only in-line this style if it's not browser default
          properties.push(property + ':' + $(this).css(property));
        }
      }
      this.style.cssText = properties.join(';');
      $(this).children().makeCssInline();
    });
  }
});

$(document).ready(function() {
  $("#before").text($("svg")[0].outerHTML.length);
  $("svg").makeCssInline();
  $("#after").text($("svg")[0].outerHTML.length);
});

svg circle {
  fill: #080;
}

svg text {
  fill: #FFF;
}

<svg version="1.1" baseProfile="full" width="300" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="150" cy="50" r="50" />
  <text x="150" y="65" font-size="40" text-anchor="middle">SVG</text>
</svg>

Total characters before in-lining styles:

Total characters after in-lining styles:

As you can see, even for a simple SVG this process adds a huge amount of unnecessary data.

Body:
You can compute the default style value of a newly created element by using getComputedStyle(). But the new element must be inserted in the DOM for this to work:

function getDefaultStyleOf(tagName, name)
{
    var element = document.createElement(tagName);

    document.body.appendChild(element);
    var value = getComputedStyle(element)[name];
    document.body.removeChild(element);

    return value;
}

console.log(getDefaultStyleOf('code', 'font-size'));


来源: stackexchange

问:
iPhone SDK: How do I programmatically create squares?
Does anyone know how I can programmatically create a grid of squares. (each square being 10x10) ?

What i'd like to do is to simulate a digital display, so I would need to be able to set the colour of each individual square, after its been defined as well.

I know I could make each individual square in interface builder, but that would be simply impractical with all the required outlets.

Any help is greatly appreciated.

答:
You'd need to create your own UIView class that implemented the necessary abstractions and carried out the relevant drawing within its drawRect method.

Have you looked at the Quartz 2D Programming Guide or Drawing and Printing Guide for iOS? These will provide the necessary background information on the various primative drawing operations and should at least point you in the correct direction.

ContentLicense: CC BY-SA 2.5


问:
How do I set a custom font in an AlertDialog using Support Library 26
I am using revision 26.0.1 of the Android Support Library to set custom fonts in my app. In my app's theme, I added:

```<code><item name="android:fontFamily">@font/my_font</item>
</code>```

It worked like a charm, converting the text in my whole app to my custom font. EXCEPT for my dialogs - specifically their titles, messages, and also their NumberPickers. In those places, fonts were not updated. (Radio buttons and checkboxes worked; so did the yes/no buttons)

Is there something I'm forgetting to add to my themes or styles? Or is this simply not supported yet by the support library?

A little more detail: I am using AppCompatDialogFragment to implement all my dialogs. In their onCreateDialog() methods, I create a dialog using AlertDialog.Builder then return it.

Thanks for the help!

答:
Thank you everybody who answered, but unfortunately none of those solutions worked for me. I hope they will work for someone else.

I've concluded that this is a bug in the support library, and hopefully Google will fix. In the meantime, I developed this hacky workaround:

```<code>public static void applyCustomFontToDialog(Context context, Dialog dialog) {
    Typeface font = ResourcesCompat.getFont(context, R.font.my_font);
    if (font != null) {
        TextView titleView = dialog.findViewById(android.support.v7.appcompat.R.id.alertTitle);
        TextView messageView = dialog.findViewById(android.R.id.message);
        if (titleView != null) titleView.setTypeface(font, Typeface.BOLD);
        if (messageView != null) messageView.setTypeface(font);
    }
}
</code>```

This works by scanning the dialog's view tree for the title and message views by the IDs that the support library gives them. If the support library were to change these IDs, this would no longer work (which is why it's hacky). Hopefully Google fixes this issue and I won't need to do this anymore.

ContentLicense: CC BY-SA 3.0

Body:
I am using revision 26.0.1 of the Android Support Library to set custom fonts in my app. In my app's theme, I added:

<item name="android:fontFamily">@font/my_font</item>

It worked like a charm, converting the text in my whole app to my custom font. EXCEPT for my dialogs - specifically their titles, messages, and also their NumberPickers. In those places, fonts were not updated. (Radio buttons and checkboxes worked; so did the yes/no buttons)

Is there something I'm forgetting to add to my themes or styles? Or is this simply not supported yet by the support library?

A little more detail: I am using AppCompatDialogFragment to implement all my dialogs. In their onCreateDialog() methods, I create a dialog using AlertDialog.Builder then return it.

Thanks for the help!

Body:
Thank you everybody who answered, but unfortunately none of those solutions worked for me. I hope they will work for someone else.

I've concluded that this is a bug in the support library, and hopefully Google will fix. In the meantime, I developed this hacky workaround:

public static void applyCustomFontToDialog(Context context, Dialog dialog) {
    Typeface font = ResourcesCompat.getFont(context, R.font.my_font);
    if (font != null) {
        TextView titleView = dialog.findViewById(android.support.v7.appcompat.R.id.alertTitle);
        TextView messageView = dialog.findViewById(android.R.id.message);
        if (titleView != null) titleView.setTypeface(font, Typeface.BOLD);
        if (messageView != null) messageView.setTypeface(font);
    }
}

This works by scanning the dialog's view tree for the title and message views by the IDs that the support library gives them. If the support library were to change these IDs, this would no longer work (which is why it's hacky). Hopefully Google fixes this issue and I won't need to do this anymore.


问:
Content files auto included by Nuget
The structure of my folder & source codes.

```<code>Areas/**/*.cshtml
Views/**/*.cshtml
</code>```

And those cshtml files were compiled into dlls by generators. So that it does not need to be included into nuget packages. (Only the dll is needed)
So the Nuspec file will be like this.

```<code><files>
</files>
</code>```

Now I want to include additional dlls into Nuget packages.
So i added the following the Nuspec file

```<code><files>
<file src="bin\Release\**\xxxxx.dll" target="lib\net451" />
</files>
</code>```

But this will bring the *.cshtml files into nuget packages.
Is there any way that i could exclude those files?
Thanx!

答:
Thanx to @rohit21agrawal and @jainaashish.
I create an issue in github
https://github.com/NuGet/Home/issues/6265

If you are packing your csproj with a .nuspec next to it, then the content files from your project will be added if one of the condition is met:

There is no nuspec file

There is a nuspec file but no files node.

There is a nuspec file with non-empty files node.

The only way to prevent content files from your project to be added into the package is to specify an empty files node.

Title: Content files auto included by Nuget

Body:
The structure of my folder & source codes.

Areas/**/*.cshtml
Views/**/*.cshtml

And those cshtml files were compiled into dlls by generators. So that it does not need to be included into nuget packages. (Only the dll is needed)
So the Nuspec file will be like this.

<files>
</files>

Now I want to include additional dlls into Nuget packages.
So i added the following the Nuspec file

<files>
<file src="bin\Release\**\xxxxx.dll" target="lib\net451" />
</files>

But this will bring the *.cshtml files into nuget packages.
Is there any way that i could exclude those files?
Thanx!


问:
Capturing items from comma delimited csv with regex
I am trying to capture the starttime, stoptime, tripduration, from_station_id, to_station_id, gender, birthyear from the following data.

trip_id,starttime,stoptime,bikeid,tripduration,from_station_name,to_station_name,from_station_id,to_station_id,usertype,gender,birthyear
431,10/13/2014 10:31,10/13/2014 10:48,SEA00298,985.935,2nd Ave & Spring St,Occidental Park / Occidental Ave S & S Washington St,CBD-06,PS-04,Member,Male,1960
```

I just want to be able to have the regex identify these items from the code.

答:
If you really really really want a regex then you can use the following one:

```<code>([^,]*)(?=,|$)
</code>```

TESTED:

Good luck and let me know if you need some explanations.

Body:
I am trying to capture the starttime, stoptime, tripduration, from_station_id, to_station_id, gender, birthyear from the following data.

trip_id,starttime,stoptime,bikeid,tripduration,from_station_name,to_station_name,from_station_id,to_station_id,usertype,gender,birthyear
431,10/13/2014 10:31,10/13/2014 10:48,SEA00298,985.935,2nd Ave & Spring St,Occidental Park / Occidental Ave S & S Washington St,CBD-06,PS-04,Member,Male,1960

I just want to be able to have the regex identify these items from the code.

Body:
If you really really really want a regex then you can use the following one:

([^,]*)(?=,|$)

TESTED:

Good luck and let me know if you need some explanations.


问:
is it possible to access value from a model databasetable in the application.html.erb?
im trying to make a app

with users
this users can join multiple groups - every group has the same menu on the page
their group page is accessable about group/1 or group/2

so i wanted to put the the menu in the application.html.erb, with lnks depending on the group.id - but i dont know how to acces this id in the application.html.erb

答: i solved my problem in a different way now. i created in the group model a "menu" and this i render partial in the application.html.erb </p>


问:
Trouble removing hidden parts of a string
I'm trying to use a scraped string with BeautifulSoup in a simple calculation. The interpreter gives a base 10 error, indicating that there's hidden characters in the string.

This turned out to be true, because the console outputs the raw string including hidden data as:

2.177
['\n\n2.177']
```

2.177 is the number I'm trying to work with here. ['\n\n2.177'] is a hidden part of the string.  Since it won't cast to int because of the hidden values however I can't make any calculations on it.

I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters.

Mine are sadly not special. Does anyone know how to remove this part of the string?

答:
You can use regular expressions:

```<code>import re
s = '\n\n2.177'
new_s = re.findall('[\.\d]+', s)
</code>```

Output:

```<code>['2.177']
</code>```

Body:
I'm trying to use a scraped string with BeautifulSoup in a simple calculation. The interpreter gives a base 10 error, indicating that there's hidden characters in the string.

This turned out to be true, because the console outputs the raw string including hidden data as:

2.177
['\n\n2.177']

2.177 is the number I'm trying to work with here. ['\n\n2.177'] is a hidden part of the string.  Since it won't cast to int because of the hidden values however I can't make any calculations on it.

I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters.

Mine are sadly not special. Does anyone know how to remove this part of the string?

Body:
You can use regular expressions:

import re
s = '\n\n2.177'
new_s = re.findall('[\.\d]+', s)

Output:

['2.177']


问:
R: Suggestion to speed up a function (remove duplicates in data frame)
I run into a bit of trouble with my code and would welcome any suggestion to make it run faster.
I have a data frame that looks like that:

```<code>Name <- c("a","a","a","a","a","b","b","b","b","c")

Category <- c("sun","cat","sun","sun","sea","sun","sea","cat","dog","cat")

More_info <- c("table","table","table","table","table","table","table","table","table","cat")
d <- data.frame(Name,Category,More_info)
</code>```

So I have duplicated entries for each row in column Name (the number of duplicates can vary). For each entry (a,b,...) I want to count the sum of each corresponding element in the Category column and keep the only category that appears the most. If an entry has an equal number of categories, I want to take one of most categories randomly.
So in this case, the output dataframe would look like this:

```<code>Name <- c("a","b","c")

Category <- c("sun","dog","cat")

More_info <- c("table","table","table")
d <- data.frame(Name,Category,More_info)
</code>```

a have sun entry kept because it appears the most, b would be dog or whatever other value as they all appear once with b, and c wouldn't be changed.
My function looks like this:

```<code>    my_choosing_function <- function(x){
      tmp = dbSNP_hapmap[dbSNP_hapmap$refsnp_id==list_of_snps[x],]
      snp_freq <- as.data.frame(table(tmp$consequence_type_tv))
       best_hit <- snp_freq[order(-snp_freq$Freq),]
      best_hit$SNP<-list_of_snps[x]
      top<-best_hit[1,]
      return(top)
    }
    trst <- lapply(1:length(list_of_snps), function(x) my_choosing_function(x))
final <- do.call("rbind",trst)
</code>```

Where I start from a list of unique elements (that would be Name in our case), for each element I do a table of the duplicated entries, I order the table by descending values and keep the top element. I do a lapply for each element of the list of unique values, then do a rbind of the whole thing.

As I have 2500000 rows in my initial data frame and 1500000 unique elements, it takes forever to run. 4 seconds for 100 lines, that would be a total of 34 hours for the lapply.

I'm sure packages like dplyr can do it in a few minutes but can't find a solution to do it. Anyone has an idea?
Thanks a lot for your help!

答:
We can modify the Mode function from here and then do a group by filter

```<code>library(dplyr)

Mode <- function(x) {
 ux <- unique(x)
 fr1 <- tabulate(match(x, ux))
  if(n_distinct(fr1)==1) ux[sample(seq_along(fr1), 1)] else ux[which.max(fr1)]
}

d %>%
  group_by(Name) %>%
  slice(which(Category == Mode(Category))[1])
</code>```

Body:
I run into a bit of trouble with my code and would welcome any suggestion to make it run faster.
I have a data frame that looks like that:

Name <- c("a","a","a","a","a","b","b","b","b","c")

Category <- c("sun","cat","sun","sun","sea","sun","sea","cat","dog","cat")

More_info <- c("table","table","table","table","table","table","table","table","table","cat")
d <- data.frame(Name,Category,More_info)

So I have duplicated entries for each row in column Name (the number of duplicates can vary). For each entry (a,b,...) I want to count the sum of each corresponding element in the Category column and keep the only category that appears the most. If an entry has an equal number of categories, I want to take one of most categories randomly.
So in this case, the output dataframe would look like this:

Name <- c("a","b","c")

Category <- c("sun","dog","cat")

More_info <- c("table","table","table")
d <- data.frame(Name,Category,More_info)

a have sun entry kept because it appears the most, b would be dog or whatever other value as they all appear once with b, and c wouldn't be changed.
My function looks like this:

    my_choosing_function <- function(x){
      tmp = dbSNP_hapmap[dbSNP_hapmap$refsnp_id==list_of_snps[x],]
      snp_freq <- as.data.frame(table(tmp$consequence_type_tv))
       best_hit <- snp_freq[order(-snp_freq$Freq),]
      best_hit$SNP<-list_of_snps[x]
      top<-best_hit[1,]
      return(top)
    }
    trst <- lapply(1:length(list_of_snps), function(x) my_choosing_function(x))
final <- do.call("rbind",trst)

Where I start from a list of unique elements (that would be Name in our case), for each element I do a table of the duplicated entries, I order the table by descending values and keep the top element. I do a lapply for each element of the list of unique values, then do a rbind of the whole thing.

As I have 2500000 rows in my initial data frame and 1500000 unique elements, it takes forever to run. 4 seconds for 100 lines, that would be a total of 34 hours for the lapply.

I'm sure packages like dplyr can do it in a few minutes but can't find a solution to do it. Anyone has an idea?
Thanks a lot for your help!

Body:
We can modify the Mode function from here and then do a group by filter

library(dplyr)

Mode <- function(x) {
 ux <- unique(x)
 fr1 <- tabulate(match(x, ux))
  if(n_distinct(fr1)==1) ux[sample(seq_along(fr1), 1)] else ux[which.max(fr1)]
}

d %>%
  group_by(Name) %>%
  slice(which(Category == Mode(Category))[1])


问:
Does hortonworks support Hue?
Recently i heard that apache Ambari support Hue (which is a Cloudera component) but I'm not sure if I can use it on my HDP 2.5, and if it can work well for my cluster with no problem (I use Ambari 2.5) </p>

<p>Does HDP support Hue?   </p>

答: We believe they officially stopped, but as Hue is compatible with any Hadoop, people still install it the clusters: http://gethue.com/hadoop-hue-3-on-hdp-installation-tutorial/</p>

Title: Does hortonworks support Hue?

Body:
Recently i heard that apache Ambari support Hue (which is a Cloudera component) but I'm not sure if I can use it on my HDP 2.5, and if it can work well for my cluster with no problem (I use Ambari 2.5)

Does HDP support Hue?


问:
Matrix Multiplication of size 100*100 using SSE Intrinsics
```<code>    int MAX_DIM = 100;
    float a[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    float b[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    float d[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    /*
     * I fill these arrays with some values
     */

for(int i=0;i<MAX_DIM;i+=1){

      for(int j=0;j<MAX_DIM;j+=4){

        for(int k=0;k<MAX_DIM;k+=4){

          __m128 result = _mm_load_ps(&d[i][j]);

          __m128 a_line  = _mm_load_ps(&a[i][k]);

          __m128 b_line0 = _mm_load_ps(&b[k][j+0]);

          __m128 b_line1 = _mm_loadu_ps(&b[k][j+1]);

          __m128 b_line2 = _mm_loadu_ps(&b[k][j+2]);

          __m128 b_line3 = _mm_loadu_ps(&b[k][j+3]);

         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0x00), b_line0));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0x55), b_line1));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0xaa), b_line2));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0xff), b_line3));
         _mm_store_ps(&d[i][j],result);
        }
      }
    }
</code>```

the above code I made to make matrix multiplication using SSE. the code runs as flows I take  4 elements from row from a multiply it by 4 elements from a column from b and move to the next 4 elements in the row of a and next 4 elements in column b

I get an error Segmentation fault (core dumped) I don't really know why

I use gcc  5.4.0 on ubuntu 16.04.5

Edit :
The segmentation fault was solved by _mm_loadu_ps
Also there is something wrong with logic i will be greatfull if someone helps me to  find it

答:
The segmentation fault was solved by _mm_loadu_ps Also there is something wrong with logic...

You're loading 4 overlapping windows on b[k][j+0..7].  (This is why you needed loadu).

Perhaps you meant to load b[k][j+0], +4, +8, +12?  If so, you should align b by 64, so all four loads come from the same cache line (for performance).  Strided access is not great, but using all 64 bytes of every cache line you touch is a lot better than getting row-major vs. column-major totally wrong in scalar code with no blocking.

I take 4 elements from row from a multiply it by 4 elements from a column from b

I'm not sure your text description describes your code.

Unless you've already transposed b, you can't load multiple values from the same column with a SIMD load, because they aren't contiguous in memory.

C multidimensional arrays are "row major": the last index is the one that varies most quickly when moving to the next higher memory address.  Did you think that _mm_loadu_ps(&b[k][j+1]) was going to give you b[k+0..3][j+1]?  If so, this is a duplicate of SSE matrix-matrix multiplication (That question is using 32-bit integer, not 32-bit float, but same layout problem.  See that for a working loop structure.)

To debug this, put a simple pattern of values into b[].  Like

```<code>#include <stdalign.>

alignas(64) float b[MAX_DIM][MAX_DIM] = {
    0000, 0001, 0002, 0003, 0004, ...,
    0100, 0101, 0102, ...,
    0200, 0201, 0202, ...,
 };

 // i.e. for (...) b[i][j] = 100 * i + j;
</code>```

Then when you step through your code in the debugger, you can see what values end up in your vectors.

For your a[][] values, maybe use 90000.0 + 100 * i + j so if you're looking at registers (instead of C variables) you can still tell which values are a and which are b.

Related:

Ulrich Drepper's What Every Programmer Should Know About Memory shows an optimized matmul with cache-blocking with SSE instrinsics for double-precision.  Should be straightforward to adapt for float.

How does BLAS get such extreme performance?  (You might want to just use an optimized matmul library; tuning matmul for optimal cache-blocking is non-trivial but important)

Matrix Multiplication with blocks

Poor maths performance in C vs Python/numpy has some links to other questions

how to optimize matrix multiplication (matmul) code to run fast on a single processor core

Body:
    int MAX_DIM = 100;
    float a[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    float b[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    float d[MAX_DIM][MAX_DIM]__attribute__   ((aligned(16)));
    /*
     * I fill these arrays with some values
     */

for(int i=0;i<MAX_DIM;i+=1){

      for(int j=0;j<MAX_DIM;j+=4){

        for(int k=0;k<MAX_DIM;k+=4){

          __m128 result = _mm_load_ps(&d[i][j]);

          __m128 a_line  = _mm_load_ps(&a[i][k]);

          __m128 b_line0 = _mm_load_ps(&b[k][j+0]);

          __m128 b_line1 = _mm_loadu_ps(&b[k][j+1]);

          __m128 b_line2 = _mm_loadu_ps(&b[k][j+2]);

          __m128 b_line3 = _mm_loadu_ps(&b[k][j+3]);

         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0x00), b_line0));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0x55), b_line1));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0xaa), b_line2));
         result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a_line, a_line, 0xff), b_line3));
         _mm_store_ps(&d[i][j],result);
        }
      }
    }

the above code I made to make matrix multiplication using SSE. the code runs as flows I take  4 elements from row from a multiply it by 4 elements from a column from b and move to the next 4 elements in the row of a and next 4 elements in column b

I get an error Segmentation fault (core dumped) I don't really know why

I use gcc  5.4.0 on ubuntu 16.04.5

Edit :
The segmentation fault was solved by _mm_loadu_ps
Also there is something wrong with logic i will be greatfull if someone helps me to  find it

Body:
The segmentation fault was solved by _mm_loadu_ps Also there is something wrong with logic...

You're loading 4 overlapping windows on b[k][j+0..7].  (This is why you needed loadu).

Perhaps you meant to load b[k][j+0], +4, +8, +12?  If so, you should align b by 64, so all four loads come from the same cache line (for performance).  Strided access is not great, but using all 64 bytes of every cache line you touch is a lot better than getting row-major vs. column-major totally wrong in scalar code with no blocking.

I take 4 elements from row from a multiply it by 4 elements from a column from b

I'm not sure your text description describes your code.

Unless you've already transposed b, you can't load multiple values from the same column with a SIMD load, because they aren't contiguous in memory.

C multidimensional arrays are "row major": the last index is the one that varies most quickly when moving to the next higher memory address.  Did you think that _mm_loadu_ps(&b[k][j+1]) was going to give you b[k+0..3][j+1]?  If so, this is a duplicate of SSE matrix-matrix multiplication (That question is using 32-bit integer, not 32-bit float, but same layout problem.  See that for a working loop structure.)

To debug this, put a simple pattern of values into b[].  Like

#include <stdalign.>

alignas(64) float b[MAX_DIM][MAX_DIM] = {
    0000, 0001, 0002, 0003, 0004, ...,
    0100, 0101, 0102, ...,
    0200, 0201, 0202, ...,
 };

 // i.e. for (...) b[i][j] = 100 * i + j;

Then when you step through your code in the debugger, you can see what values end up in your vectors.

For your a[][] values, maybe use 90000.0 + 100 * i + j so if you're looking at registers (instead of C variables) you can still tell which values are a and which are b.

Related:

Ulrich Drepper's What Every Programmer Should Know About Memory shows an optimized matmul with cache-blocking with SSE instrinsics for double-precision.  Should be straightforward to adapt for float.

How does BLAS get such extreme performance?  (You might want to just use an optimized matmul library; tuning matmul for optimal cache-blocking is non-trivial but important)

Matrix Multiplication with blocks

Poor maths performance in C vs Python/numpy has some links to other questions

how to optimize matrix multiplication (matmul) code to run fast on a single processor core


问:
Swift 3 GCD lock variable and block_and_release error
I am using Swift 3 GCD in order to perform some operations in my code. But I'm getting _dispatch_call_block_and_release error often. I suppose the reason behind this error is because different threads modify same variable, but I'm not sure how to fix problem. Here is my code and explanations:

I have one variable which is accessed and modified in different threads:

```<code>var queueMsgSent: Dictionary<Date,BTCommand>? = nil

func lock(obj: AnyObject, blk:() -> ()) {
    objc_sync_enter(obj)
    blk()
    objc_sync_exit(obj)
}

func addMsgSentToQueue(msg: BTCommands) {

    if queueMsgSent == nil {
        queueMsgSent = Dictionary.init()
    }
    let currentDate = Date()
    lock(obj: queueMsgSent as AnyObject) {
        queueMsgSent?.updateValue(msg, forKey: currentDate)
    }
}

func deleteMsgSentWithId(id: Int) {

    if queueMsgSent == nil { return }

    for (date, msg) in queueMsgSent! {

        if msg.isAck() == false && msg.getId()! == id {
            lock(obj: queueMsgSent as AnyObject) {
                queueMsgSent?.removeValue(forKey: date)
            }
        }
   }
}

func runSent() -> Void {

    while(true) {
        if queueMsgSent == nil { continue }

        for (date, msg) in queueMsgSent! {

            if msg.isSent() == false {
                 mainSearchView?.btCom?.write(str: msg.getCommand()!)
                 msg.setSent(val: true)
                lastMsgSent = Date()
                continue
            }

            if msg.isAck() == true {
                lock(obj: queueMsgSent as AnyObject) {
                    queueMsgSent?.removeValue(forKey: date)
                }
                continue
            }

        }
   }

}
</code>```

I start runSent method as:

```<code>  DispatchQueue.global().async(execute: runSent)
</code>```

I need that runSent continuously check some conditions withinn queueMsgSent, and other functions addMsgSentToQueueue and deleteMsgSentWithId are called in main thread id necessary. I am using some locking mechanism but its not working properly

答:
If you're uncomfortable with the objc mechanisms, you might take a look here. Using that, you create a PThreadMutex for the specific synchronizations you want to coordinate, then use mutex.fastsync{ *your code* } to segregate accesses. It's a simple, very lightweight mechanism using OS-level calls, but you'll have to watch out for creating deadlocks.

The example you provide depends on the object always being the same physical entity, because the objc lock uses the address as the ID of what's being synchronized. Because you seem to have to check everywhere for the existence of queueMsgSent, I'm wondering what the update value routine is doing - if it ever deletes the dictionary, expecting it to be created later, you'll have a potential race as different threads can be looking at different synchronizers.

Separately, your loop in runSent is a spin loop - if there's nothing to do, it's just going to burn CPU rather than waiting for work. Perhaps you could consider revising this to use semaphores or some more appropriate mechanism that would allow the workers to block when there's nothing to do?

Body:
I am using Swift 3 GCD in order to perform some operations in my code. But I'm getting _dispatch_call_block_and_release error often. I suppose the reason behind this error is because different threads modify same variable, but I'm not sure how to fix problem. Here is my code and explanations:

I have one variable which is accessed and modified in different threads:

var queueMsgSent: Dictionary<Date,BTCommand>? = nil

func lock(obj: AnyObject, blk:() -> ()) {
    objc_sync_enter(obj)
    blk()
    objc_sync_exit(obj)
}

func addMsgSentToQueue(msg: BTCommands) {

    if queueMsgSent == nil {
        queueMsgSent = Dictionary.init()
    }
    let currentDate = Date()
    lock(obj: queueMsgSent as AnyObject) {
        queueMsgSent?.updateValue(msg, forKey: currentDate)
    }
}

func deleteMsgSentWithId(id: Int) {

    if queueMsgSent == nil { return }

    for (date, msg) in queueMsgSent! {

        if msg.isAck() == false && msg.getId()! == id {
            lock(obj: queueMsgSent as AnyObject) {
                queueMsgSent?.removeValue(forKey: date)
            }
        }
   }
}

func runSent() -> Void {

    while(true) {
        if queueMsgSent == nil { continue }

        for (date, msg) in queueMsgSent! {

            if msg.isSent() == false {
                 mainSearchView?.btCom?.write(str: msg.getCommand()!)
                 msg.setSent(val: true)
                lastMsgSent = Date()
                continue
            }

            if msg.isAck() == true {
                lock(obj: queueMsgSent as AnyObject) {
                    queueMsgSent?.removeValue(forKey: date)
                }
                continue
            }

        }
   }

}

I start runSent method as:

  DispatchQueue.global().async(execute: runSent)

I need that runSent continuously check some conditions withinn queueMsgSent, and other functions addMsgSentToQueueue and deleteMsgSentWithId are called in main thread id necessary. I am using some locking mechanism but its not working properly


问:
How to overload a function when you only need to change a parameter data type
I have a function SelectNext() that takes a collection parameter (of type IEnumerable) and it selects the next item in the collection and return that item.

```<code>'BaseListTypes is an Enum
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of Object)) As Object
    Dim res As Object

   'function body here....

    Return res
End Function
</code>```

The above function works great for any List(Of T) where T is an object or string.

However it fails when I pass it a List(Of My_STRUCTURE) (custom structure I have, which contains 3 string variables)

Obviously since Structure is like integer and other base types are a value types.
While objects are reference types. I can see why I am getting an error at runtime.

My question is, is there a better way than just overloading my function into something like:

```<code>Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of My_STRUCTURE)) As Object
</code>```

答:
In theory, this should work for any type, whether it be reference type or value type:

Function SelectNext(Of T)(listType As BaseListTypes, lst As IEnumerable(Of T)) As T
    Dim res As T
   'function body here....

    Return res
End Function
```

I'd need more information to know for sure though.  Your question is actually a bit vague.  For one thing, what does "selects the next item in the collection" actually mean?  You should edit your question to make it more complete, with a better description of what you're doing and what errors occur and where.

Body:
I have a function SelectNext() that takes a collection parameter (of type IEnumerable) and it selects the next item in the collection and return that item.

'BaseListTypes is an Enum
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of Object)) As Object
    Dim res As Object

   'function body here....

    Return res
End Function

The above function works great for any List(Of T) where T is an object or string.

However it fails when I pass it a List(Of My_STRUCTURE) (custom structure I have, which contains 3 string variables)

Obviously since Structure is like integer and other base types are a value types.
While objects are reference types. I can see why I am getting an error at runtime.

My question is, is there a better way than just overloading my function into something like:

Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of My_STRUCTURE)) As Object

Body:
In theory, this should work for any type, whether it be reference type or value type:

Function SelectNext(Of T)(listType As BaseListTypes, lst As IEnumerable(Of T)) As T
    Dim res As T
   'function body here....

    Return res
End Function

I'd need more information to know for sure though.  Your question is actually a bit vague.  For one thing, what does "selects the next item in the collection" actually mean?  You should edit your question to make it more complete, with a better description of what you're doing and what errors occur and where.


问:
Chaining searching and sorting together in rails using serachlogic
My code is very similar to that in railscasts #240

The differences are that I am using rails 2.3.10 so I am not using 'where'.  Instead I am using serachlogic and my model looks like this...

```<code>//Model.rb
def self.search(search)
      if search
        Model.column_name_like(search)
      else
        find(:all)
      end
    end
</code>```

(I am using search logic because I need case insensitivity because I am deploying to heroku(postgres))

When I try and chain my methods together like in the railscast and in other tutorials I get an error such as "method order not found"

My controller is here...

```<code> @objects=Model.search(params[:search]).order(sort_order('created_at'))
</code>```

This is with a slightly different column sort method which was working for me before I stuck the search in.

Why does this method work in some tutorials but throwing an error in this case.  Is it because the tutorials are in rails 3?

答:
I found an optimal solution myself a few days later.  I had to make a change in my model. Instead of returning a find(:all) in the else I returned a new "empty"search object

```<code>@search=Model.column_name_like("")
</code>```

Fore reference my model and controller which now supports sorting,searching, and pagination looks like...

```<code>def self.search(search)
      if search
        Model.column_name_like(search)
      else
        @search=Model.column_name_like("")
      end
    end

def index
  @per_page = params[:per_page] || Lease.per_page || 20
  @search=Lease.search(params[:search])
  @objects=@search.find(:all, :order=>(sort_column + " "+ sort_direction)).paginate(:per_page => @per_page, :page => params[:page])
end

private
def sort_column
  Model.column_names.include?(params[:sort]) ? params[:sort] : "default_column_name"
end

def sort_direction
  %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
</code>```

Don't forget to put hidden form helpers in your view to pass in the column name and direction.

```<code><p>
<% form_tag leases_path, :method => 'get' do %>
<p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
</p>
<%=hidden_field_tag :direction, params[:direction]%>
<%=hidden_field_tag :sort, params[:sort]%>

<% end %>
</code>```

Body:
My code is very similar to that in railscasts #240

The differences are that I am using rails 2.3.10 so I am not using 'where'.  Instead I am using serachlogic and my model looks like this...

//Model.rb
def self.search(search)
      if search
        Model.column_name_like(search)
      else
        find(:all)
      end
    end

(I am using search logic because I need case insensitivity because I am deploying to heroku(postgres))

When I try and chain my methods together like in the railscast and in other tutorials I get an error such as "method order not found"

My controller is here...

 @objects=Model.search(params[:search]).order(sort_order('created_at'))

This is with a slightly different column sort method which was working for me before I stuck the search in.

Why does this method work in some tutorials but throwing an error in this case.  Is it because the tutorials are in rails 3?

Body:
I found an optimal solution myself a few days later.  I had to make a change in my model. Instead of returning a find(:all) in the else I returned a new "empty"search object

@search=Model.column_name_like("")

Fore reference my model and controller which now supports sorting,searching, and pagination looks like...

def self.search(search)
      if search
        Model.column_name_like(search)
      else
        @search=Model.column_name_like("")
      end
    end

def index
  @per_page = params[:per_page] || Lease.per_page || 20
  @search=Lease.search(params[:search])
  @objects=@search.find(:all, :order=>(sort_column + " "+ sort_direction)).paginate(:per_page => @per_page, :page => params[:page])
end

private
def sort_column
  Model.column_names.include?(params[:sort]) ? params[:sort] : "default_column_name"
end

def sort_direction
  %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end

Don't forget to put hidden form helpers in your view to pass in the column name and direction.

<p>
<% form_tag leases_path, :method => 'get' do %>
<p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
</p>
<%=hidden_field_tag :direction, params[:direction]%>
<%=hidden_field_tag :sort, params[:sort]%>

<% end %>


问:
How to prevent a hacker from reading/writing on firebase database
I have some questions about securing firebase database for mobile applications.

For example, after decompiling Android application a hacker can get firebase api key and then get access to firebase database, is this correct?

Let's assume, I added some security rules like for example an app can read/write on firebase only if auth!=null, this means that the authentication is protecting my firebase database, but this put me to ask the same question, if I configure facebook/google/ or even firebase email authentication I'm gonna need some api keys for those providers in my application, If a hacker got access to those keys, will he be able to use my authentication in his own application and get access to my firebase data?

I want to understand what to do in Android applications to make sure only my application will get access to firebase datatabase.

答:
after decompiling Android application a hacker can get firebase api
  key and then get access to firebase database, is this correct?

Only if your database does not use any security rules that limit access to only authenticated users.

if I configure facebook/google/ or even firebase email authentication
  I'm gonna need some api keys for those providers in my application, If
  a hacker got access to those keys, will he be able to use my
  authentication in his own application and get access to my firebase
  data?

No, it doesn't work that way.

Each user authenticated with Firebase is issued a token that's used to identify the user when they access protected services, such as Realtime Database, Firestore, or Storage.  This token is valid 1 hour and must be refreshed after that, which the SDK will do automatically.

For a hacker to gain control of that user's data, they would have to obtain this token, and they would have no more than an hour to work with it.  After that, they would have to obtain the next token obtained by the SDK.  All this would have to happen on the user's device.

ContentLicense: CC BY-SA 4.0


问:
R: how to handle dynamically generated inputs in Shiny
I'm struggling in dealing with the inputs I generate using the insertUI function.

Goal

I need to fill a XML file using one or more textInput I generate with add button (the first input is already generated when the app starts). The add button create a new empty node in the XML; the remove button remove it. The information in generated textInput should be copied in the respective node as in the following example:

First item: _____txt1_______

Item 2: _____txt2_______

Item 3: _____txt3_______

XML file:

```<code><items>
 <item>txt1<item>
 <item>txt2<item>
 <item>txt3<item>
</items>
</code>```

My attempt

Using the following code I'm able to add/remove textInput element as well as nodes in the XML file. I have no idea how to fill the nodes with the textInput.

```<code>library(shiny)
library(xml2)

xml <-
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><items><item/></items>"
doc <- read_xml(xml)

# Define UI ----
ui <- fluidPage(
  # Create the first Text input
  tags$div(
    id = 'items',
    textInput(
      inputId = "item1",
      label = "First item",
      width = "100%"
    )
  ),
  # Create the add/remove buttons
  actionButton("addBtn", "Add"),
  actionButton("removeBtn", "Remove"),

  # Output XML
  h4("XML Code"),
  htmlOutput("xml")
)

# Define server logic ----
server <- function(input, output) {
  inserted <<- c("item1")
  btn <<- 2
  # Observe the add button
  observeEvent(input$addBtn, {
    itemID <- paste0("item", btn)
    insertUI(selector = "#items",
             ui = tags$div(
               id = itemID,
               textInput(
                 inputId = itemID,
                 label = paste("Item", btn),
                 width = "100%"
               )
             ))
    xml_add_sibling(xml_find_all(doc, "item[last()]"), "item")
    btn <<- btn + 1
    inserted <<- c(inserted, itemID)
  })

  # Observe the remove button
  observeEvent(input$removeBtn, {
    itemID <- paste0("item",btn-1)
    cat(itemID, sep="\n")
    if (length(inserted) > 1) {
      removeUI(selector = paste0("#", itemID))

      xml_remove(xml_find_all(doc, "item[last()]"))
      inserted <<- inserted[-(btn - 1)]
      btn <<- btn - 1
    }
  })

  # Render the xml output
  output$xml <- renderText({
    # ugly way to update each press button
    input$addBtn
    input$removeBtn

    # XML convertion to print it in ui
    docConv <- as.character(doc)
    docConv <- gsub("<", "<", docConv)
    docConv <- gsub(">", ">", docConv)
    docConv <- gsub(" ", " ", docConv, fixed = T)
    docConv <- gsub("\\n", "<br/>", docConv)
    HTML(docConv)
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

Any hint (functions, examples, etc.)?

Thank you

答:
I think this is more of an xml2 than Shiny thing.

I just barely modified your example, leveraging

xml_new_root to fix up the root doc

xml_add_child with an extra arg for text (itemID) to add child nodes easier

```<code>library(shiny)
library(xml2)

doc <- xml_new_root("items")

# Define UI ----
ui <- fluidPage(
  # Create the first Text input
  tags$div(id = 'items'),
  # Create the add/remove buttons
  actionButton("addBtn", "Add"),
  actionButton("removeBtn", "Remove"),

  # Output XML
  h4("XML Code"),
  htmlOutput("xml")
)

# Define server logic ----
server <- function(input, output) {
  inserted <<- c()
  btn <<- 1
  # Observe the add button
  observeEvent(input$addBtn, {
    itemID <- paste0("item", btn)
    insertUI(selector = "#items",
             ui = tags$div(
               id = itemID,
               textInput(
                 inputId = itemID,
                 label = paste("Item", btn),
                 width = "100%"
               )
             ))
    xml_add_child(doc, "item", itemID)
    btn <<- btn + 1
    inserted <<- c(inserted, itemID)
  })

  # Observe the remove button
  observeEvent(input$removeBtn, {
    itemID <- paste0("item", btn-1)
    cat(itemID, sep="\n")
    if (length(inserted) > 0) {
      removeUI(selector = paste0("#", itemID))

      xml_remove(xml_find_all(doc, "item[last()]"))
      inserted <<- inserted[-(btn - 1)]
      btn <<- btn - 1
    }
  })

  # Render the xml output
  output$xml <- renderText({
    # ugly way to update each press button
    input$addBtn
    input$removeBtn

    # XML convertion to print it in ui
    docConv <- as.character(doc)
    docConv <- gsub("<", "<", docConv)
    docConv <- gsub(">", ">", docConv)
    docConv <- gsub(" ", " ", docConv, fixed = T)
    docConv <- gsub("\\n", "<br/>", docConv)
    HTML(docConv)
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

Body:
I'm struggling in dealing with the inputs I generate using the insertUI function.

Goal

I need to fill a XML file using one or more textInput I generate with add button (the first input is already generated when the app starts). The add button create a new empty node in the XML; the remove button remove it. The information in generated textInput should be copied in the respective node as in the following example:

First item: _____txt1_______

Item 2: _____txt2_______

Item 3: _____txt3_______

XML file:

<items>
 <item>txt1<item>
 <item>txt2<item>
 <item>txt3<item>
</items>

My attempt

Using the following code I'm able to add/remove textInput element as well as nodes in the XML file. I have no idea how to fill the nodes with the textInput.

library(shiny)
library(xml2)

xml <-
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><items><item/></items>"
doc <- read_xml(xml)

# Define UI ----
ui <- fluidPage(
  # Create the first Text input
  tags$div(
    id = 'items',
    textInput(
      inputId = "item1",
      label = "First item",
      width = "100%"
    )
  ),
  # Create the add/remove buttons
  actionButton("addBtn", "Add"),
  actionButton("removeBtn", "Remove"),

  # Output XML
  h4("XML Code"),
  htmlOutput("xml")
)

# Define server logic ----
server <- function(input, output) {
  inserted <<- c("item1")
  btn <<- 2
  # Observe the add button
  observeEvent(input$addBtn, {
    itemID <- paste0("item", btn)
    insertUI(selector = "#items",
             ui = tags$div(
               id = itemID,
               textInput(
                 inputId = itemID,
                 label = paste("Item", btn),
                 width = "100%"
               )
             ))
    xml_add_sibling(xml_find_all(doc, "item[last()]"), "item")
    btn <<- btn + 1
    inserted <<- c(inserted, itemID)
  })

  # Observe the remove button
  observeEvent(input$removeBtn, {
    itemID <- paste0("item",btn-1)
    cat(itemID, sep="\n")
    if (length(inserted) > 1) {
      removeUI(selector = paste0("#", itemID))

      xml_remove(xml_find_all(doc, "item[last()]"))
      inserted <<- inserted[-(btn - 1)]
      btn <<- btn - 1
    }
  })

  # Render the xml output
  output$xml <- renderText({
    # ugly way to update each press button
    input$addBtn
    input$removeBtn

    # XML convertion to print it in ui
    docConv <- as.character(doc)
    docConv <- gsub("<", "<", docConv)
    docConv <- gsub(">", ">", docConv)
    docConv <- gsub(" ", " ", docConv, fixed = T)
    docConv <- gsub("\\n", "
", docConv)
    HTML(docConv)
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)

Any hint (functions, examples, etc.)?

Thank you

Body:
I think this is more of an xml2 than Shiny thing.

I just barely modified your example, leveraging

xml_new_root to fix up the root doc

xml_add_child with an extra arg for text (itemID) to add child nodes easier

library(shiny)
library(xml2)

doc <- xml_new_root("items")

# Define UI ----
ui <- fluidPage(
  # Create the first Text input
  tags$div(id = 'items'),
  # Create the add/remove buttons
  actionButton("addBtn", "Add"),
  actionButton("removeBtn", "Remove"),

  # Output XML
  h4("XML Code"),
  htmlOutput("xml")
)

# Define server logic ----
server <- function(input, output) {
  inserted <<- c()
  btn <<- 1
  # Observe the add button
  observeEvent(input$addBtn, {
    itemID <- paste0("item", btn)
    insertUI(selector = "#items",
             ui = tags$div(
               id = itemID,
               textInput(
                 inputId = itemID,
                 label = paste("Item", btn),
                 width = "100%"
               )
             ))
    xml_add_child(doc, "item", itemID)
    btn <<- btn + 1
    inserted <<- c(inserted, itemID)
  })

  # Observe the remove button
  observeEvent(input$removeBtn, {
    itemID <- paste0("item", btn-1)
    cat(itemID, sep="\n")
    if (length(inserted) > 0) {
      removeUI(selector = paste0("#", itemID))

      xml_remove(xml_find_all(doc, "item[last()]"))
      inserted <<- inserted[-(btn - 1)]
      btn <<- btn - 1
    }
  })

  # Render the xml output
  output$xml <- renderText({
    # ugly way to update each press button
    input$addBtn
    input$removeBtn

    # XML convertion to print it in ui
    docConv <- as.character(doc)
    docConv <- gsub("<", "&lt;", docConv)
    docConv <- gsub(">", "&gt;", docConv)
    docConv <- gsub(" ", "&nbsp;", docConv, fixed = T)
    docConv <- gsub("\\n", "<br/>", docConv)
    HTML(docConv)
  })
}

# Run the app ----
shinyApp(ui = ui, server = server)


问:
Watir ChromeDriver Can NOT click Element in Jenkins-AWS-Ubuntu
I have the following screen

And this is my ruby steps for clicking the "STATUS" tab.

```<code>And(/^Click The Status Tab$/) do
# statusTab = driver.link(id: "tab3")
statusTab = driver.link visible_text: "STATUS"
statusTab.wait_until_present
if statusTab.exists?
    statusTab.click
    puts "Status Tab Clicked"
else
    fail "Could NOT locate Status Tab"
end
end
</code>```

As you can see in my code above, I have tried using the locator "link" by 'id' and 'visible_text'.
The code above works fine in my local computer. I have tried running it using chromedriver and chromedriver in headless mode. I have tried using Jenkins in my local computer, too.

But, it failed when running it in Jenkins server in the AWS.
I got the following error in my cucumber report:

```<code>unknown error: Element <em>...</em> is not clickable at point (146, 16). Other element would receive the click: <li>...</li>
</code>```

(Session info: headless chrome=62.0.3202.62)
(Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.4.0-1039-aws x86_64) (Selenium::WebDriver::Error::UnknownError)

Is there a way to tackle this issue?

答:
Most of the time that something works in a real browser, but not headless is due to a difference in the size of the actual browser window.  Headless seems to open in a smaller window, which can cause two things to happen

1) element may be off-screen  and can't be scrolled to for some reason

2) (especially typical of reactive sites that arrange to fit space allowed) the site ends up arranged such that another element is covering the one you are trying to click.

The clue to which is the case is usually in the error message.  In your case the text Other element would receive the click is telling you that something else has covered up the thing you are trying to click on.

Try setting the browser window size right after you create your browser/driver object.  If you are using Watir the command usually looks something like this

```<code>browser.window.resize_to(1024, 768)
</code>```

Generally I talk to the PO and ask what the minimum supported screen size (assuming a maximized browser window) is, and set the browser to that size.  Often if tablet browsing is to be supported without a special mobile site, the smallest supported screen size will beo 1024x786 or 768x1024 (depending if portrait or landscape orientation is assumed)

Body:
I have the following screen

And this is my ruby steps for clicking the "STATUS" tab.

And(/^Click The Status Tab$/) do
# statusTab = driver.link(id: "tab3")
statusTab = driver.link visible_text: "STATUS"
statusTab.wait_until_present
if statusTab.exists?
    statusTab.click
    puts "Status Tab Clicked"
else
    fail "Could NOT locate Status Tab"
end
end

As you can see in my code above, I have tried using the locator "link" by 'id' and 'visible_text'.
The code above works fine in my local computer. I have tried running it using chromedriver and chromedriver in headless mode. I have tried using Jenkins in my local computer, too.

But, it failed when running it in Jenkins server in the AWS.
I got the following error in my cucumber report:

unknown error: Element ... is not clickable at point (146, 16). Other element would receive the click:
...

(Session info: headless chrome=62.0.3202.62)
(Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.4.0-1039-aws x86_64) (Selenium::WebDriver::Error::UnknownError)

Is there a way to tackle this issue?

Body:
Most of the time that something works in a real browser, but not headless is due to a difference in the size of the actual browser window.  Headless seems to open in a smaller window, which can cause two things to happen

1) element may be off-screen  and can't be scrolled to for some reason

2) (especially typical of reactive sites that arrange to fit space allowed) the site ends up arranged such that another element is covering the one you are trying to click.

The clue to which is the case is usually in the error message.  In your case the text Other element would receive the click is telling you that something else has covered up the thing you are trying to click on.

Try setting the browser window size right after you create your browser/driver object.  If you are using Watir the command usually looks something like this

browser.window.resize_to(1024, 768)

Generally I talk to the PO and ask what the minimum supported screen size (assuming a maximized browser window) is, and set the browser to that size.  Often if tablet browsing is to be supported without a special mobile site, the smallest supported screen size will beo 1024x786 or 768x1024 (depending if portrait or landscape orientation is assumed)


答:
You should have a look at the Apple sample project for example of drawing (square, circles, elipse, etc)

QuartzDemo

Hope this helps.

Title: iPhone SDK: How do I programmatically create squares?

Body:
Does anyone know how I can programmatically create a grid of squares. (each square being 10x10) ?

What i'd like to do is to simulate a digital display, so I would need to be able to set the colour of each individual square, after its been defined as well.

I know I could make each individual square in interface builder, but that would be simply impractical with all the required outlets.

Any help is greatly appreciated.


问:
Lazy load pages random error:ERROR Error: Uncaught (in promise): invalid link:
I run into the following error every now and then.

```<code>ERROR Error: Uncaught (in promise): invalid link:MenuPage
    at d (polyfills.js:3)
    at l (polyfills.js:3)
    at Object.reject (polyfills.js:3)
    at NavControllerBase._fireError (nav-controller-base.js:322)
    at NavControllerBase._failed (nav-controller-base.js:310)
    at nav-controller-base.js:365
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.es5.js:4125)
    at t.invoke (polyfills.js:3)
    at n.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4116)
    at t.invokeTask (polyfills.js:3)
    at n.runTask (polyfills.js:3)
</code>```

I'm not aware of any steps to reproduce and this error is not causing any problem at all The app is working normally and the Menu Page is displayed correctly.

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Nav, Platform } from 'ionic-angular';

@IonicPage({
  name: "menu",
  segment: "app"
}
)
@Component({
  selector: 'page-menu',
  templateUrl: 'menu.html'
})
export class MenuPage {}
```

I had checked my project and the menu page is only used by its IonicPage name "menu".

There is already an ionic forum post but I am already following the proposed accepted solution which is about giving a name to the IonicPage annotation.

答:
In MenuPage.ts :
add this over the class MenuPage:

```<code>@IonicPage(
{
  name: 'tabs-page'
})
</code>```

In app.components.ts

```<code>rootPage: string = 'tabs-page';
</code>```

Please try it!

Body:
I run into the following error every now and then.

ERROR Error: Uncaught (in promise): invalid link:MenuPage
    at d (polyfills.js:3)
    at l (polyfills.js:3)
    at Object.reject (polyfills.js:3)
    at NavControllerBase._fireError (nav-controller-base.js:322)
    at NavControllerBase._failed (nav-controller-base.js:310)
    at nav-controller-base.js:365
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.es5.js:4125)
    at t.invoke (polyfills.js:3)
    at n.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4116)
    at t.invokeTask (polyfills.js:3)
    at n.runTask (polyfills.js:3)

I'm not aware of any steps to reproduce and this error is not causing any problem at all The app is working normally and the Menu Page is displayed correctly.

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Nav, Platform } from 'ionic-angular';

@IonicPage({
  name: "menu",
  segment: "app"
}
)
@Component({
  selector: 'page-menu',
  templateUrl: 'menu.html'
})
export class MenuPage {}

I had checked my project and the menu page is only used by its IonicPage name "menu".

There is already an ionic forum post but I am already following the proposed accepted solution which is about giving a name to the IonicPage annotation.

Body:
In MenuPage.ts :
add this over the class MenuPage:

@IonicPage(
{
  name: 'tabs-page'
})

In app.components.ts

rootPage: string = 'tabs-page';

Please try it!


问:
Laravel 5.4 External user email notification queue not being sent
I'm using Laravel Notifications with ShouldQueue implementation to send email to external user as follows:

App\Http\Controllers\ActionController.php:

```<code>...
use App\Notifications\ExternalUserNotified;

class ActionController extends Controller
{
...

    public function send()
    {
        $notified_user = (new User)->forceFill([
            'name'=> 'External User',
            'email'=> 'test@email.com'
        ]);

        $notified_user->notify(new ExternalUserNotified($data));
        ...
    }
}
</code>```

App/Notifications/ExternalUserNotified.php class:

```<code>...
class ExternalUserNotified extends Notification implements ShouldQueue
{
    use Queueable;

    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {

        return (new MailMessage)
                    ->subject('Test Subject')
                    ->line('Dear User,')
                    ->line('Test notification content...')
                    ->line('Thank you for using our application!');
    }
}
</code>```

The queue job was successfully created and run without any error with command:

```<code>php artisan queue:work
</code>```

However, there was no email sent to test@email.com (I am using MailTrap for testing). The email was successfully sent if the notification class does not implement ShouldQueue.

All conditions work if user instance is a model instance:

```<code>$notified_user = User::find(1);
$notified_user->notify(new ExternalUserNotified($data));
</code>```

I suspected that the temporary new user instance:

```<code>$notified_user = (new User)->forceFill([
   'name'=> 'External User',
   'email'=> 'test@email.com'
]);
</code>```

could not be recognized by the queue.

Appreciate and thank you very much in advance for your help.

答:
this is how i solved the problem.

Dont use ShouldQueue

```<code>            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
</code>```

Instead use the basis ->queue

```<code>            Mail::to('test@gmail.com')->queue(new VerificationNewAccount($ran));
</code>```

now the email is sent to gmail

The weird part is that now the email is not printed in log.
Well i dont care. It woks!

Laravel 5.4

Body:
I'm using Laravel Notifications with ShouldQueue implementation to send email to external user as follows:

App\Http\Controllers\ActionController.php:

...
use App\Notifications\ExternalUserNotified;

class ActionController extends Controller
{
...

    public function send()
    {
        $notified_user = (new User)->forceFill([
            'name'=> 'External User',
            'email'=> 'test@email.com'
        ]);

        $notified_user->notify(new ExternalUserNotified($data));
        ...
    }
}

App/Notifications/ExternalUserNotified.php class:

...
class ExternalUserNotified extends Notification implements ShouldQueue
{
    use Queueable;

    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {

        return (new MailMessage)
                    ->subject('Test Subject')
                    ->line('Dear User,')
                    ->line('Test notification content...')
                    ->line('Thank you for using our application!');
    }
}

The queue job was successfully created and run without any error with command:

php artisan queue:work

However, there was no email sent to test@email.com (I am using MailTrap for testing). The email was successfully sent if the notification class does not implement ShouldQueue.

All conditions work if user instance is a model instance:

$notified_user = User::find(1);
$notified_user->notify(new ExternalUserNotified($data));

I suspected that the temporary new user instance:

$notified_user = (new User)->forceFill([
   'name'=> 'External User',
   'email'=> 'test@email.com'
]);

could not be recognized by the queue.

Appreciate and thank you very much in advance for your help.

Body:
this is how i solved the problem.

Dont use ShouldQueue

            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }

Instead use the basis ->queue

            Mail::to('test@gmail.com')->queue(new VerificationNewAccount($ran));

now the email is sent to gmail

The weird part is that now the email is not printed in log.
Well i dont care. It woks!

Laravel 5.4


问:
How to link data records in pandas?
I have a csv file which I can read into a pandas data frame. The data is like:

+--------+---------+------+----------------+
|  Name  | Address |  ID  |   Linked_To    |
+--------+---------+------+----------------+
| Name 1 | ABC     | 1233 | 1234;1235      |
| Name 2 | DEF     | 1234 | 1233;1236;1237 |
| Name 3 | GHI     | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+
```

How do I run analysis on the linkage between ID and the Linked_To columns. For example, should I be turning the Linked_To values into a list and doing a VLOOKUP type analysis on the ID column? I know there must be an obvious way to do this but I am stumped.

Ideally the end result should be a list or dictionary which has the entire attributes of the row, including all of the other records its linked to.

OR is this a problem where I should be transforming the data into an SQL database?

答:
for the unique and non-unique cases, a dictionary of IDs in linked_to for each ID could be obtained via:</p>

```<code>def linked_ids(df):
    #set up the dictionary
    dict = {}
    #iterate through the rows
    for row in df.index:
        #separate the semi-colon delimited linked to field
        linked_to = df.ix[row,'Linked_to'].split(";")

        if df.ix[row,'ID'] not in dict.keys():
            dict[df.ix[row,'ID']] = []

            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)
        else:
            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)

    return dict
</code>```

Title: How to link data records in pandas?

Body:
I have a csv file which I can read into a pandas data frame. The data is like:

+--------+---------+------+----------------+
|  Name  | Address |  ID  |   Linked_To    |
+--------+---------+------+----------------+
| Name 1 | ABC     | 1233 | 1234;1235      |
| Name 2 | DEF     | 1234 | 1233;1236;1237 |
| Name 3 | GHI     | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+

How do I run analysis on the linkage between ID and the Linked_To columns. For example, should I be turning the Linked_To values into a list and doing a VLOOKUP type analysis on the ID column? I know there must be an obvious way to do this but I am stumped.

Ideally the end result should be a list or dictionary which has the entire attributes of the row, including all of the other records its linked to.

OR is this a problem where I should be transforming the data into an SQL database?

Body:
for the unique and non-unique cases, a dictionary of IDs in linked_to for each ID could be obtained via:

def linked_ids(df):
    #set up the dictionary
    dict = {}
    #iterate through the rows
    for row in df.index:
        #separate the semi-colon delimited linked to field
        linked_to = df.ix[row,'Linked_to'].split(";")

        if df.ix[row,'ID'] not in dict.keys():
            dict[df.ix[row,'ID']] = []

            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)
        else:
            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)

    return dict


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

OwnerDisplayName: kvphxga

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

Body:
char c;
c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b));
printf("a %c b",c);


问:
Cannot install Rails3 on fresh Ubuntu 10.10
Trying to install rails on a fresh copy of Ubuntu 10.10 and each time at gem install rails I get Error installing rails: mail requires i18n

I'm using the rvm approach to the install if that helps.  I've successfully got ruby 1.9.2 running and now this.

Thoughts?  Suggestions?

答:
http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you/

I used Ryan Bigg's "Ubuntu, Ruby, RVM, Rails, and You" blog post to install ruby & rails on my new ubuntu box.


问:
OnBindViewHolder no suitable method found to override using with await to method
In class ContactsAdapter I have method OnBindViewHolder, inside of that I call await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage). await method makes the OnBindViewHolder be formed to that:

```<code>public class ContactsAdapter: RecyclerView.Adapter, View.IOnClickListener
    {

    public override async System.Threading.Tasks.Task OnBindViewHolderAsync(RecyclerView.ViewHolder holder, int position)
    {
    ...
    await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage);
    ...
    }

    private async System.Threading.Tasks.Task DirectToLoadImageAsync(string stringURL, CircleImageView vImage)
            {
                var resultImg = await LoadImageAsync(stringURL);
                vImage.SetImageBitmap(resultImg);

            }

    private System.Threading.Tasks.Task<Bitmap> LoadImageAsync(string stringURL)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(() => LoadImage(stringURL));
            }

    private Bitmap LoadImage(string stringURL)
            {
             ...
            }
    }
</code>```

how to make not to get error: OnBindViewHolder no suitable method found to override using with await to method ?

答:
OnBindViewHolder no suitable method found to override using with await to method ?

Can’t use await keyword in this method as you can’t use async keyword in method signature due to incompatible return type, and please note that your OnBindViewHolder has renamed to OnBindViewHolderAsync.

An async method has to return either void, Task, or Task<T>, and returning void should only be used when making an event handler async.  In the case of the OnBindViewHolder method noted above, its return type is void, which can’t be changed to return Task as the OS method that calls it obviously does not use the await keyword and so can’t handle a Taskbeing returned. Thus you can’t add the async keyword to the above method and therefore can’t use the await keyword when calling an async method from the above method.

Solution :

Modify your code like this :

```<code>public override void OnBindViewHolder (RecyclerView.ViewHolder holder, int position)
{
    ...
    Task.Run(async () => {
        try
        {
            await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage);
        }
        // Catch any other exceptinons that may have occured
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    });
    ...
}
</code>```

Body:
In class ContactsAdapter I have method OnBindViewHolder, inside of that I call await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage). await method makes the OnBindViewHolder be formed to that:

public class ContactsAdapter: RecyclerView.Adapter, View.IOnClickListener
    {

    public override async System.Threading.Tasks.Task OnBindViewHolderAsync(RecyclerView.ViewHolder holder, int position)
    {
    ...
    await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage);
    ...
    }

    private async System.Threading.Tasks.Task DirectToLoadImageAsync(string stringURL, CircleImageView vImage)
            {
                var resultImg = await LoadImageAsync(stringURL);
                vImage.SetImageBitmap(resultImg);

            }

    private System.Threading.Tasks.Task<Bitmap> LoadImageAsync(string stringURL)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(() => LoadImage(stringURL));
            }

    private Bitmap LoadImage(string stringURL)
            {
             ...
            }
    }

how to make not to get error: OnBindViewHolder no suitable method found to override using with await to method ?

Body:
OnBindViewHolder no suitable method found to override using with await to method ?

Can’t use await keyword in this method as you can’t use async keyword in method signature due to incompatible return type, and please note that your OnBindViewHolder has renamed to OnBindViewHolderAsync.

An async method has to return either void, Task, or Task<T>, and returning void should only be used when making an event handler async.  In the case of the OnBindViewHolder method noted above, its return type is void, which can’t be changed to return Task as the OS method that calls it obviously does not use the await keyword and so can’t handle a Taskbeing returned. Thus you can’t add the async keyword to the above method and therefore can’t use the await keyword when calling an async method from the above method.

Solution :

Modify your code like this :

public override void OnBindViewHolder (RecyclerView.ViewHolder holder, int position)
{
    ...
    Task.Run(async () => {
        try
        {
            await DirectToLoadImageAsync(stringURL, my_contacts_view.vImage);
        }
        // Catch any other exceptinons that may have occured
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    });
    ...
}


问:
jQuery don't work inside PHP echo
Value of $qty is in my database. I've read few similar questions and I already added $(document).ready but it's still not working.

```<code>echo "<div class='sp-quantity'>
    <div class='sp-minus fff'><a class='ddd' href='#' data-multi='-1'>-</a></div>
    <div class='col-xs-3 sp-input'>
    <input type='text' class='quntity-input form-control qty' pid='$bookid' id='qty-$bookid' value='$qty'/>
    </div>
    <div class='sp-plus fff'><a class='ddd' href='#' data-multi='1'>+</a></div>
    </div>";

echo "<script>";
echo "$(document).ready(function(){";
echo "$('.ddd').on('click', function() {";
echo "var $button = $(this);";
echo "var $input = $button.closest('.sp-quantity').find('input.quntity-input');";
echo "$input.val(function(i, value) {";
echo "return +value + (1 * +$button.data('multi'));";
echo "});";
echo "});";
echo "});";
echo "</script>";
</code>```

答:
You're getting your PHP & Javascript variable syntax confused. PHP uses $ as the start of every variable name. Javascript doesn't, plus jquery uses $ in a special way. On top of that, PHP does automatic string substitution of anything starting with a $ that can be a valid variable name as long as the string uses " instead of '. So the result of your code is:

```<code><script>
$(document).ready(function(){
   $('.ddd').on('click', function() {
      var $button = $(this);
      var $input = $button.closest('.sp-quantity').find('input.quntity-input');
      $input.val(function(i, value) {
         return +value + (1 * +$button.data('multi'));
      });
   });
});
</script>
</code>```

$button and $input will be substituted with the contents of the PHP variables of those names. I suspect that's not what you want - though I have done things like that at times myself. What I think you want is:

```<code><script>
$(document).ready(function(){
   $('.ddd').on('click', function() {
      var button = $(this);
      var input = button.closest('.sp-quantity').find('input.quntity-input');
      input.val(function(i, value) {
         return +value + (1 * + button.data('multi'));
      });
   });
});
</script>
</code>```

Two other suggestions:

1 - If you have absolutely no PHP values within a bunch of Javascript (or plain HTML) echo lines, you can exit out of PHP code mode by using ?> and not use echo and avoid any issues of string substitution.

2 - Personally, I prefer using {$string} for my variables inside strings as it makes the substitution more obvious and sometimes less ambiguous.

Title: jQuery don't work inside PHP echo

Body:
Value of $qty is in my database. I've read few similar questions and I already added $(document).ready but it's still not working.

echo "

-

    <input type='text' class='quntity-input form-control qty' pid='$bookid' id='qty-$bookid' value='$qty'/>

+

";

echo "";

Body:
You're getting your PHP & Javascript variable syntax confused. PHP uses $ as the start of every variable name. Javascript doesn't, plus jquery uses $ in a special way. On top of that, PHP does automatic string substitution of anything starting with a $ that can be a valid variable name as long as the string uses " instead of '. So the result of your code is:

<script>
$(document).ready(function(){
   $('.ddd').on('click', function() {
      var $button = $(this);
      var $input = $button.closest('.sp-quantity').find('input.quntity-input');
      $input.val(function(i, value) {
         return +value + (1 * +$button.data('multi'));
      });
   });
});
</script>

$button and $input will be substituted with the contents of the PHP variables of those names. I suspect that's not what you want - though I have done things like that at times myself. What I think you want is:

<script>
$(document).ready(function(){
   $('.ddd').on('click', function() {
      var button = $(this);
      var input = button.closest('.sp-quantity').find('input.quntity-input');
      input.val(function(i, value) {
         return +value + (1 * + button.data('multi'));
      });
   });
});
</script>

Two other suggestions:

1 - If you have absolutely no PHP values within a bunch of Javascript (or plain HTML) echo lines, you can exit out of PHP code mode by using ?> and not use echo and avoid any issues of string substitution.

2 - Personally, I prefer using {$string} for my variables inside strings as it makes the substitution more obvious and sometimes less ambiguous.


问:
Using a Word2Vec model pre-trained on wikipedia
I need to use gensim to get vector representations of words, and I figure the best thing to use would be a word2vec module that's pre-trained on the english wikipedia corpus. Does anyone know where to download it, how to install it, and how to use gensim to create the vectors?</p>

答:
You can check WebVectors to find Word2Vec models trained on various corpora. Models come with readme covering the training details.
You'll have to be a bit careful using these models, though. I'm not sure about all of them, but at least in Wikipedia's case, the model is not a binary file that you can straightforwardly load using e.g. gensim's functionality, but a txt version, i.e. file with words and corresponding vectors. Keep in mind, though, that the words are appended by their part-of-speech (POS) tags, so for example, if you'd like to use the model to find out similarities for word vacation, you'll get a KeyError if you type vacation as is, since the model stores this word as vacation_NOUN.
An example snippet of how you could use the wiki model (perhaps others as well if they're in the same format) and an output is below

```<code>import gensim.models

model = "./WebVectors/3/enwiki_5_ner.txt"

word_vectors = gensim.models.KeyedVectors.load_word2vec_format(model, binary=False)
print(word_vectors.most_similar("vacation_NOUN"))
print(word_vectors.most_similar(positive=['woman_NOUN', 'king_NOUN'], negative=['man_NOUN']))
</code>```

and the output

```<code>▶ python3 wiki_model.py
[('vacation_VERB', 0.6829521656036377), ('honeymoon_NOUN', 0.6811978816986084), ('holiday_NOUN', 0.6588436365127563), ('vacationer_NOUN', 0.6212040781974792), ('resort_NOUN', 0.5720850825309753), ('trip_NOUN', 0.5585346817970276), ('holiday_VERB', 0.5482848882675171), ('week-end_NOUN', 0.5174300670623779), ('newlywed_NOUN', 0.5146450996398926), ('honeymoon_VERB', 0.5135983228683472)]
[('monarch_NOUN', 0.6679952144622803), ('ruler_NOUN', 0.6257176995277405), ('regnant_NOUN', 0.6217397451400757), ('royal_ADJ', 0.6212111115455627), ('princess_NOUN', 0.6133661866188049), ('queen_NOUN', 0.6015778183937073), ('kingship_NOUN', 0.5986001491546631), ('prince_NOUN', 0.5900266170501709), ('royal_NOUN', 0.5886058807373047), ('throne_NOUN', 0.5855424404144287)]
</code>```

UPDATE
Here are some useful links to binary models:

Pretrained word embedding models:

Fasttext models:

crawl-300d-2M.vec.zip: 2 million word vectors trained on Common Crawl (600B tokens).

wiki-news-300d-1M.vec.zip: 1 million word vectors trained on Wikipedia 2017, UMBC webbase corpus and statmt.org news dataset (16B tokens).

wiki-news-300d-1M-subword.vec.zip: 1 million word vectors trained with subword infomation on Wikipedia 2017, UMBC webbase corpus and statmt.org news dataset (16B tokens).

Wiki word vectors, dim=300: wiki.en.zip: bin+text model

Google Word2Vec

Pretrained word/phrase vectors:

GoogleNews-vectors-negative300.bin.gz

GoogleNews-vectors-negative300-SLIM.bin.gz: slim version with app. 300k words

Pretrained entity vectors:

freebase-vectors-skipgram1000.bin.gz: Entity vectors trained on 100B words from various news articles

freebase-vectors-skipgram1000-en.bin.gz: Entity vectors trained on 100B words from various news articles, using the deprecated /en/ naming (more easily readable); the vectors are sorted by frequency

GloVe: Global Vectors for Word Representation

glove.6B.zip: Wikipedia 2014 + Gigaword 5 (6B tokens, 400K vocab, uncased, 50d, 100d, 200d, & 300d vectors, 822 MB download). Here's an example in action.

glove.840B.300d.zip: Common Crawl (840B tokens, 2.2M vocab, cased, 300d vectors, 2.03 GB download)

WebVectors

models trained on various corpora, augmented by Part-of-Speech (POS) tags

Body:
You can check WebVectors to find Word2Vec models trained on various corpora. Models come with readme covering the training details.
You'll have to be a bit careful using these models, though. I'm not sure about all of them, but at least in Wikipedia's case, the model is not a binary file that you can straightforwardly load using e.g. gensim's functionality, but a txt version, i.e. file with words and corresponding vectors. Keep in mind, though, that the words are appended by their part-of-speech (POS) tags, so for example, if you'd like to use the model to find out similarities for word vacation, you'll get a KeyError if you type vacation as is, since the model stores this word as vacation_NOUN.
An example snippet of how you could use the wiki model (perhaps others as well if they're in the same format) and an output is below

import gensim.models

model = "./WebVectors/3/enwiki_5_ner.txt"

word_vectors = gensim.models.KeyedVectors.load_word2vec_format(model, binary=False)
print(word_vectors.most_similar("vacation_NOUN"))
print(word_vectors.most_similar(positive=['woman_NOUN', 'king_NOUN'], negative=['man_NOUN']))

and the output

▶ python3 wiki_model.py
[('vacation_VERB', 0.6829521656036377), ('honeymoon_NOUN', 0.6811978816986084), ('holiday_NOUN', 0.6588436365127563), ('vacationer_NOUN', 0.6212040781974792), ('resort_NOUN', 0.5720850825309753), ('trip_NOUN', 0.5585346817970276), ('holiday_VERB', 0.5482848882675171), ('week-end_NOUN', 0.5174300670623779), ('newlywed_NOUN', 0.5146450996398926), ('honeymoon_VERB', 0.5135983228683472)]
[('monarch_NOUN', 0.6679952144622803), ('ruler_NOUN', 0.6257176995277405), ('regnant_NOUN', 0.6217397451400757), ('royal_ADJ', 0.6212111115455627), ('princess_NOUN', 0.6133661866188049), ('queen_NOUN', 0.6015778183937073), ('kingship_NOUN', 0.5986001491546631), ('prince_NOUN', 0.5900266170501709), ('royal_NOUN', 0.5886058807373047), ('throne_NOUN', 0.5855424404144287)]

UPDATE
Here are some useful links to binary models:

Pretrained word embedding models:

Fasttext models:

crawl-300d-2M.vec.zip: 2 million word vectors trained on Common Crawl (600B tokens).

wiki-news-300d-1M.vec.zip: 1 million word vectors trained on Wikipedia 2017, UMBC webbase corpus and statmt.org news dataset (16B tokens).

wiki-news-300d-1M-subword.vec.zip: 1 million word vectors trained with subword infomation on Wikipedia 2017, UMBC webbase corpus and statmt.org news dataset (16B tokens).

Wiki word vectors, dim=300: wiki.en.zip: bin+text model

Google Word2Vec

Pretrained word/phrase vectors:

GoogleNews-vectors-negative300.bin.gz

GoogleNews-vectors-negative300-SLIM.bin.gz: slim version with app. 300k words

Pretrained entity vectors:

freebase-vectors-skipgram1000.bin.gz: Entity vectors trained on 100B words from various news articles

freebase-vectors-skipgram1000-en.bin.gz: Entity vectors trained on 100B words from various news articles, using the deprecated /en/ naming (more easily readable); the vectors are sorted by frequency

GloVe: Global Vectors for Word Representation

glove.6B.zip: Wikipedia 2014 + Gigaword 5 (6B tokens, 400K vocab, uncased, 50d, 100d, 200d, & 300d vectors, 822 MB download). Here's an example in action.

glove.840B.300d.zip: Common Crawl (840B tokens, 2.2M vocab, cased, 300d vectors, 2.03 GB download)

WebVectors

models trained on various corpora, augmented by Part-of-Speech (POS) tags


问:
Eloquent - Search ID in column like ['4','6','8'] (PHP Laravel)
I'm lost... I can't fetch my datas inside database...

So I have a table with name : preparation and with fields

ID, ..., ..., participants,.., ... .

I store IDs of another table in participants field with json_encode function like this : ['4','6','8'].

I would like to retrieve all results with an ID given. So for example if I had :

```<code>ID---name---participants--------otherfield
1---Step1---['6','8']-----------lorem1
2---Step2---['4','7','8']-------lorem2
3---Step3---['2','3','6','9']---lorem3
</code>```

I would like to retrieve all lines with the number 6 so line 1 and 3.
I did several tests with eloquent, or querybuilder but without result.
For example I tried this :

```<code>$idToFind = 6;
$query = PreparationStep::
      whereRaw("JSON_CONTAINS(participants, ".$idToFind.")")
    ->get();
</code>```

Please help me.

答:
You're almost there! Since JSON_CONTAINS returns 1 if it finds a match and 0 if not, you have to change your whereRaw statement like this (parameterize your raw statements to prevent sql injections)

```<code>$idToFind = 6;
$query = PreparationStep::whereRaw("JSON_CONTAINS(participants, ?) = 1", [$idToFind])->get();
</code>```

Body:
I'm lost... I can't fetch my datas inside database...

So I have a table with name : preparation and with fields

ID, ..., ..., participants,.., ... .

I store IDs of another table in participants field with json_encode function like this : ['4','6','8'].

I would like to retrieve all results with an ID given. So for example if I had :

ID---name---participants--------otherfield
1---Step1---['6','8']-----------lorem1
2---Step2---['4','7','8']-------lorem2
3---Step3---['2','3','6','9']---lorem3

I would like to retrieve all lines with the number 6 so line 1 and 3.
I did several tests with eloquent, or querybuilder but without result.
For example I tried this :

$idToFind = 6;
$query = PreparationStep::
      whereRaw("JSON_CONTAINS(participants, ".$idToFind.")")
    ->get();

Please help me.

Body:
You're almost there! Since JSON_CONTAINS returns 1 if it finds a match and 0 if not, you have to change your whereRaw statement like this (parameterize your raw statements to prevent sql injections)

$idToFind = 6;
$query = PreparationStep::whereRaw("JSON_CONTAINS(participants, ?) = 1", [$idToFind])->get();


问:
specifying a list as a command line argument in python
I am using getopt to process a command line optional argument, which should accept a list. Something like this:

```<code>foo.py --my_list=[1, 2, 3, 4,5]
</code>```

But this trims everything after "[1,"

My questions are:
A) Is there a way to specify a list without converting it into a string? (using getopt)

B) If I am to convert the list into a string, how to convert this list to a string? e.g. something like  mylist.split("?") to get rid of square brackets ?? is there a better way?

Thank you

答:
An updated way is to use the argparse library and add the list as a command line argument. This way, you don't have to do any manual parsing.

Example:

```<code>parser = argparse.ArgumentParser()
parser.add_argument(
        "-values",
        nargs="*",  # expects ≥ 0 arguments
        type=int,
        default=[35, 40, 50, 60, 70, 80, 90],  # default list if no arg value
    )
</code>```

Which you would then call like this:

```<code>python3 someprogram.py -values 1 2 3
</code>```

Body:
I am using getopt to process a command line optional argument, which should accept a list. Something like this:

foo.py --my_list=[1, 2, 3, 4,5]

But this trims everything after "[1,"

My questions are:
A) Is there a way to specify a list without converting it into a string? (using getopt)

B) If I am to convert the list into a string, how to convert this list to a string? e.g. something like  mylist.split("?") to get rid of square brackets ?? is there a better way?

Thank you

Body:
An updated way is to use the argparse library and add the list as a command line argument. This way, you don't have to do any manual parsing.

Example:

parser = argparse.ArgumentParser()
parser.add_argument(
        "-values",
        nargs="*",  # expects ≥ 0 arguments
        type=int,
        default=[35, 40, 50, 60, 70, 80, 90],  # default list if no arg value
    )

Which you would then call like this:

python3 someprogram.py -values 1 2 3


问:
what do texture2D().r and texture2D().a mean?
I am using OpenGL ES in Android programming, when I transform YUV(NV21) to RGB in shader, like:

```<code>vec3 yuv = vec3(
        (texture2D(u_TextureY, vTextureCoord).r - 0.0625),
        texture2D(u_TextureUV, vTextureCoord).a - 0.5,
        texture2D(u_TextureUV, vTextureCoord).r - 0.5
    );
</code>```

then I'll get YUV data that seperating from u_TextureY and u_TextureUV.

I know that NV21 format is like: YYYYYY...UVUV... BUT how can I transform YUYV422 to RGB?
So, my problem is what do "r" and "a" mean in texture2D(u_TextureY, vTextureCoord).r and .a ? then I can find the way to do YUYV422->RGB.

答:
OK, I have solved it.
The answer from @Rabbid76 is great, so we know .r and .a are from {r, g, b, a}.
My question is not just what is .r.a, it's why is .r.a .

I solved the problem starting from this answer enter link description here

```<code>glTexImage2D(GL20.GL_TEXTURE_2D, 0, GL20.GL_LUMINANCE,
width, height, 0, GL20.GL_LUMINANCE, GL20.GL_UNSIGNED_BYTE, buffer_y);
</code>```

by setting GL_LUMINANCE, OpenGL puts this byte into R,G and B components of the texture. So we can use .r to get Y values, also .g or .b.

```<code>glTexImage2D(GL20.GL_TEXTURE_2D, 0, GL20.GL_LUMINANCE_ALPHA,
width/2, height/2, 0, GL20.GL_LUMINANCE_ALPHA, GL20.GL_UNSIGNED_BYTE,
buffer_uv);
</code>```

by setting GL_LUMINANCE_ALPHA, OpenGL puts the first byte 'V' into r/g/b components, and puts the second byte 'U' into a component. So we can use .a to get U, and .r to get V(.g or .b is ok).

As we know that NV21 format is like YYYY...UVUV... It seems like 'U' is the first byte in UV texture.

```<code>buffer_uv = ByteBuffer.allocateDirect(width * height * 4)
            .order(ByteOrder.nativeOrder());
</code>```

buffer_uv is order with ByteOrder.nativeOrder(), retrieves the native byte order of the underlying platform. From enter link description here
That means the UV values(...UVUV...) are read from native buffer by native byte order like ...VUVU... , it's reverse.

Body:
I am using OpenGL ES in Android programming, when I transform YUV(NV21) to RGB in shader, like:

vec3 yuv = vec3(
        (texture2D(u_TextureY, vTextureCoord).r - 0.0625),
        texture2D(u_TextureUV, vTextureCoord).a - 0.5,
        texture2D(u_TextureUV, vTextureCoord).r - 0.5
    );

then I'll get YUV data that seperating from u_TextureY and u_TextureUV.

I know that NV21 format is like: YYYYYY...UVUV... BUT how can I transform YUYV422 to RGB?
So, my problem is what do "r" and "a" mean in texture2D(u_TextureY, vTextureCoord).r and .a ? then I can find the way to do YUYV422->RGB.

Body:
OK, I have solved it.
The answer from @Rabbid76 is great, so we know .r and .a are from {r, g, b, a}.
My question is not just what is .r.a, it's why is .r.a .

I solved the problem starting from this answer enter link description here

glTexImage2D(GL20.GL_TEXTURE_2D, 0, GL20.GL_LUMINANCE,
width, height, 0, GL20.GL_LUMINANCE, GL20.GL_UNSIGNED_BYTE, buffer_y);

by setting GL_LUMINANCE, OpenGL puts this byte into R,G and B components of the texture. So we can use .r to get Y values, also .g or .b.

glTexImage2D(GL20.GL_TEXTURE_2D, 0, GL20.GL_LUMINANCE_ALPHA,
width/2, height/2, 0, GL20.GL_LUMINANCE_ALPHA, GL20.GL_UNSIGNED_BYTE,
buffer_uv);

by setting GL_LUMINANCE_ALPHA, OpenGL puts the first byte 'V' into r/g/b components, and puts the second byte 'U' into a component. So we can use .a to get U, and .r to get V(.g or .b is ok).

As we know that NV21 format is like YYYY...UVUV... It seems like 'U' is the first byte in UV texture.

buffer_uv = ByteBuffer.allocateDirect(width * height * 4)
            .order(ByteOrder.nativeOrder());

buffer_uv is order with ByteOrder.nativeOrder(), retrieves the native byte order of the underlying platform. From enter link description here
That means the UV values(...UVUV...) are read from native buffer by native byte order like ...VUVU... , it's reverse.


问:
Input string was not in a correct format using c# windows form
I tried many solutions but i can't figure out what i am doing wrong?

I find this solution from everywhere but it's not working

```<code> try
 {
 if (lbl_Unit.Text == "0")
 {
   lbl_Profit.Text = "0";
 }
 else
 {
   double a = double.Parse(lbl_TotalSold.Text);
   double b = double.Parse(lbl_Unit.Text);
   double total = a - b;
   lbl_Profit.Text = total.ToString();
 }
}
catch (Exception se)
{
   MessageBox.Show(se.Message);
}
</code>```

This was my old code

```<code>try
 {
 if (lbl_Unit.Text == "0")
 {
   lbl_Profit.Text = "0";
 }
 else
 {
   int a = Convert.ToInt32(lbl_TotalSold.Text);
   int b = Convert.ToInt32(lbl_Unit.Text);
   int total = a - b;
   lbl_Profit.Text = total.ToString();
 }
}
catch (Exception se)
{
   MessageBox.Show(se.Message);
}
</code>```

答:
You can use TryParse unless Parse
For validate the number format. I recommend to review the decimal separator too</p>

Body:
I tried many solutions but i can't figure out what i am doing wrong?

I find this solution from everywhere but it's not working

 try
 {
 if (lbl_Unit.Text == "0")
 {
   lbl_Profit.Text = "0";
 }
 else
 {
   double a = double.Parse(lbl_TotalSold.Text);
   double b = double.Parse(lbl_Unit.Text);
   double total = a - b;
   lbl_Profit.Text = total.ToString();
 }
}
catch (Exception se)
{
   MessageBox.Show(se.Message);
}

This was my old code

try
 {
 if (lbl_Unit.Text == "0")
 {
   lbl_Profit.Text = "0";
 }
 else
 {
   int a = Convert.ToInt32(lbl_TotalSold.Text);
   int b = Convert.ToInt32(lbl_Unit.Text);
   int total = a - b;
   lbl_Profit.Text = total.ToString();
 }
}
catch (Exception se)
{
   MessageBox.Show(se.Message);
}