问:
Make a hash table using smart pointers?
I'm trying to make a hashtable by using smart pointers, but I'm not sure if I am doing it right. I've been trying to play with two combinations of them, but I am afraid I don't know how to initialize the table to be empty? Maybe that is the wrong verbage, but I am stuck and I need to be pointed in the right direction.

My hashNode:

```<code>struct{
    hashNode(int k, std::string i) : key(k), item(i){};

    int key;
    std::string item;
}
</code>```

My hashtable:

```<code>class Hashtable
{
public:

    Hashtable(); //not sure how to build the constructor build an empty table.

    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item);
    void remove(int key);

private:

    int tableSize = 10;
    std::shared_ptr<std::shared_ptr<hashNode>> hashTable;
    //std::vector<std::shared_ptr<hashNode>> hashTable;
};
</code>```

I am stuck here, as I don't know if I am implementing my hashTable correctly or not. Or, if this is just a bad idea to go with. Any advice would do.

答:
Example of HashTable with containers

```<code>class Hashtable
{
public:
    Hashtable(): hashTable(10) // initial size set here
    {
        // does nothing
    }
    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item); // this gets a bit more complicated
                                            // due to copying during rehash
    void remove(int key);

private:
    std::vector<std::vector<hashNode>> hashTable; // vector knows its size
};
</code>```

This slightly complicates the rehashing as now you have to copy instead of moving pointers around, but on the upside there are zero memory management woes or difficulties with copying something that contains a unique_ptr. It wouldn't be unique if you copied it, would it?

Title: Make a hash table using smart pointers?

Body:
I'm trying to make a hashtable by using smart pointers, but I'm not sure if I am doing it right. I've been trying to play with two combinations of them, but I am afraid I don't know how to initialize the table to be empty? Maybe that is the wrong verbage, but I am stuck and I need to be pointed in the right direction.

My hashNode:

struct{
    hashNode(int k, std::string i) : key(k), item(i){};

    int key;
    std::string item;
}

My hashtable:

class Hashtable
{
public:

    Hashtable(); //not sure how to build the constructor build an empty table.

    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item);
    void remove(int key);

private:

    int tableSize = 10;
    std::shared_ptr<std::shared_ptr<hashNode>> hashTable;
    //std::vector<std::shared_ptr<hashNode>> hashTable;
};

I am stuck here, as I don't know if I am implementing my hashTable correctly or not. Or, if this is just a bad idea to go with. Any advice would do.

Body:
Example of HashTable with containers

class Hashtable
{
public:
    Hashtable(): hashTable(10) // initial size set here
    {
        // does nothing
    }
    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item); // this gets a bit more complicated
                                            // due to copying during rehash
    void remove(int key);

private:
    std::vector<std::vector<hashNode>> hashTable; // vector knows its size
};

This slightly complicates the rehashing as now you have to copy instead of moving pointers around, but on the upside there are zero memory management woes or difficulties with copying something that contains a unique_ptr. It wouldn't be unique if you copied it, would it?


来源: stackexchange

问:
JS: Resolve a Formula for x
I have a formula with several components, let's say w = x * y / z^2 + c. Now I have an input-field for each variable. My goal is, to calculate the missing one as soon, as all the others were entered. Difficulty is, that you can choose which fields you fill and which you want to leave free.

The easy (naive) way would of course be to resolve it for each variable by hand, detect the missing var, and have seperate js functions for each case. But I even have linked formulas (like x in the above formula is x = a + b, too) as well and the options are almost infinitive. Is there any option in JS to solve a formula by a specified variable? I could then replace each variable string with the assigned value and then eval the string.

First I thought Nerdamer would be the thing, but it turned out that it can only evaluate expressions and can't handle equations.

Is this possible? Any better idea?

Thanks in advance!

P.S.: My actual set of formula is:

```<code>dR = c * I^2 / A
R = L * dR
P = I * U
DV = R * I
DW = DV * I
</code>```

It's for calculating losses in a cable due to ohm's resistance. Each Variable has a corresponding input field.

答:
The following solution can be built for finding "R" using nerdamer. The logic can be extended to solve for the remaining variables. Do keep in mind that the current limitation is that nerdamer can currently only solve up to cubic functions algebraically. Higher order functions will be solved numerically.

//You can then take care of the non linear containing I. I is quadratic
var dR = nerdamer('R=L*dR').solveFor('dR');
var I = nerdamer('dR=c*I^2/A').sub('dR', dR).solveFor('I');
//You can first start by reducing the first few equations since they are linear and you can solve them as a linear system
var solutions = nerdamer.solveEquations(['P = I * U', 'DV = R * I', 'DW = DV * I'], ['I', 'DW', 'P']);
//the solutions come back as an array arrays in the form of [variable, value]
//you can see what they look like. In your case all your solutions will be in terns of DV & U since these are the only actual knowns
//You can see what the solutions look like
solutions.map(function(x) {
    console.log('-'+x[0]+' = '+x[1]);
});
console.log('------------------ R ----------------');
var R = nerdamer.setEquation(I[0], solutions[0][1]).solveFor('R');
//I will have 3 solutions since it's cubic. You can console.log them below
R.map(function(x) {
    console.log('R = '+x.toString());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/nerdamer.core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Algebra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Calculus.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Extra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Solve.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Title: JS: Resolve a Formula for x

Body:
I have a formula with several components, let's say w = x * y / z^2 + c. Now I have an input-field for each variable. My goal is, to calculate the missing one as soon, as all the others were entered. Difficulty is, that you can choose which fields you fill and which you want to leave free.

The easy (naive) way would of course be to resolve it for each variable by hand, detect the missing var, and have seperate js functions for each case. But I even have linked formulas (like x in the above formula is x = a + b, too) as well and the options are almost infinitive. Is there any option in JS to solve a formula by a specified variable? I could then replace each variable string with the assigned value and then eval the string.

First I thought Nerdamer would be the thing, but it turned out that it can only evaluate expressions and can't handle equations.

Is this possible? Any better idea?

Thanks in advance!

P.S.: My actual set of formula is:

dR = c * I^2 / A
R = L * dR
P = I * U
DV = R * I
DW = DV * I

It's for calculating losses in a cable due to ohm's resistance. Each Variable has a corresponding input field.

Body:
The following solution can be built for finding "R" using nerdamer. The logic can be extended to solve for the remaining variables. Do keep in mind that the current limitation is that nerdamer can currently only solve up to cubic functions algebraically. Higher order functions will be solved numerically.

//You can then take care of the non linear containing I. I is quadratic
var dR = nerdamer('R=L*dR').solveFor('dR');
var I = nerdamer('dR=c*I^2/A').sub('dR', dR).solveFor('I');
//You can first start by reducing the first few equations since they are linear and you can solve them as a linear system
var solutions = nerdamer.solveEquations(['P = I * U', 'DV = R * I', 'DW = DV * I'], ['I', 'DW', 'P']);
//the solutions come back as an array arrays in the form of [variable, value]
//you can see what they look like. In your case all your solutions will be in terns of DV & U since these are the only actual knowns
//You can see what the solutions look like
solutions.map(function(x) {
    console.log('-'+x[0]+' = '+x[1]);
});
console.log('------------------ R ----------------');
var R = nerdamer.setEquation(I[0], solutions[0][1]).solveFor('R');
//I will have 3 solutions since it's cubic. You can console.log them below
R.map(function(x) {
    console.log('R = '+x.toString());
});

<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/nerdamer.core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Algebra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Calculus.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Extra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Solve.js"></script>

ContentLicense: CC BY-SA 4.0


问:
want to hide image when image is not found at the src location?
```<code>jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>
```

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

答:
On both jQuery(document).ready() and jQuery(window).onload() the img will have already had the error, so you are binding to error too late.  Try using:

```<code>jQuery('img').live('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>```

before jQuery(document).ready();

I haven't tried this code yet (and wouldn't have time too for a while)  Let me know if it works.

ContentLicense: CC BY-SA 2.5

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

Body:
On both jQuery(document).ready() and jQuery(window).onload() the img will have already had the error, so you are binding to error too late.  Try using:

jQuery('img').live('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

before jQuery(document).ready();

I haven't tried this code yet (and wouldn't have time too for a while)  Let me know if it works.


问:
Twilio Send SMS throw exeption Salesforce
I am trying to send and SMS using Twilio but getting an error. Earlier it was working fine but now I am getting an exception : TwilioRestException: Script-thrown exception.

I suspect its a enhancement in Salesforce but don't know how to fix it. Any suggestion is appreciated.

Thanks!

答:
There is a Twilio<>Salesforce Library you can use that doesn't have the issue:

https://github.com/twilio/twilio-salesforce


问:
Check if string contains a character with for loop?
I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.

My current code

```<code>import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}
</code>```

}

As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is

0.5
0.25
0.25
0.0

Any help would be appreciated!

答:
The problem is that S.contains returns true if the whole string contains the given character. S.charAt should solve your problem:

```<code>for (int i = 0; i < S.length(); i++) {
    if (S.charAt(i) == 'G') G++;
    else if (S.charAt(i) == 'R') R++;
    else if (S.charAt(i) == 'Y') Y++;
    else if (S.charAt(i) == 'B') B++;
}
</code>```

Also, dividing integers will return an integer (rounded down). As such your output would always be 0 unless all the characters are the same. Just cast them to double before printing:

```<code>System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);
</code>```

Edit: As pointed out by Sumit Gulati in a comment, a switch statement will have better performance in Java 7. Also, as David Conrad pointed out using only ifs in the for loop would work too as the conditions are mutually exclusive.

Body:
I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.

My current code

import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}

}

As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is

0.5
0.25
0.25
0.0

Any help would be appreciated!

Body:
The problem is that S.contains returns true if the whole string contains the given character. S.charAt should solve your problem:

for (int i = 0; i < S.length(); i++) {
    if (S.charAt(i) == 'G') G++;
    else if (S.charAt(i) == 'R') R++;
    else if (S.charAt(i) == 'Y') Y++;
    else if (S.charAt(i) == 'B') B++;
}

Also, dividing integers will return an integer (rounded down). As such your output would always be 0 unless all the characters are the same. Just cast them to double before printing:

System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);

Edit: As pointed out by Sumit Gulati in a comment, a switch statement will have better performance in Java 7. Also, as David Conrad pointed out using only ifs in the for loop would work too as the conditions are mutually exclusive.


问:
Unicode "not equal" notation in Coq (≠)
The following text is mentioned in SF book:

This is how we use not to state that 0 and 1 are different elements of nat:

```<code>Theorem zero_not_one : ~(0 = 1).
Proof.
  intros contra. inversion contra.
Qed.
</code>```

Such inequality statements are frequent enough to warrant a special
  notation, x ≠ y:

```<code>Check (0 ≠ 1).
(* ===> Prop *)
</code>```

But when I actually do this in Coq:

```<code>Check (0 ≠ 1).
</code>```

It gives me this error:

```<code>Syntax Error: Lexer: Undefined token
</code>```

In fact, looking at the standard
library, I
cannot seem to find any notation for that. So, what is the proper
notation for it ?

答: Not familiar with Coq typed language, but looking at the standard library, not equal to would be written as <>.

Title: Unicode "not equal" notation in Coq (≠)

Body:
The following text is mentioned in SF book:

This is how we use not to state that 0 and 1 are different elements of nat:

Theorem zero_not_one : ~(0 = 1).
Proof.
  intros contra. inversion contra.
Qed.

Such inequality statements are frequent enough to warrant a special
  notation, x ≠ y:

Check (0 ≠ 1).
(* ===> Prop *)

But when I actually do this in Coq:

Check (0 ≠ 1).

It gives me this error:

Syntax Error: Lexer: Undefined token

In fact, looking at the standard
library, I
cannot seem to find any notation for that. So, what is the proper
notation for it ?


问:
os.popen() variables
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

```<code>file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)
</code>```

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

答:
Your problem is you don't pass a string as your command. Fixed call to popen():

```<code>os.popen('sudo tcpdump -c5 -vvv -w {0} host wiki or host wiki2'.format(file_name))
</code>```

Title: os.popen() variables

Body:
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

Body:
Your problem is you don't pass a string as your command. Fixed call to popen():

os.popen('sudo tcpdump -c5 -vvv -w {0} host wiki or host wiki2'.format(file_name))


问:
Append dataframe on a existing dataframe in shiny
I am trying to make an app that according to the selection of the user will subsetting the dataframe of the data. After that I want to create a new dataframe with unique values of col1 abd and the new dataframes added as new columns to the existing dataframe depending on users choice (like from a long shape of the dates making them in wide).
Any thoughts???
my dataset is that

```<code>col1<-rep(c(1:4),3)
col2<-c('a','b','c','a','b','c','a','b','c','a','b','c')
col3<-c(1,2,3,NA,NA,14,15,NA,NA,20,21,22)
col4<-c(NA,NA,1,2,3,14,15,20,21,22,NA,NA)
df<-data.table(col1,col2,col3,col4)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   selectInput('Ind', 'Index',choices = c(unique(df$col2))),
   dataTableOutput('Table')
)
# Define server logic required to draw a histogram
server <- function(input, output) {

 dfsel<-reactive({dfnew<-subset(df,col2==input$Ind)
 dfnew
 })
 output$Table<-renderDataTable(dfsel())

}

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

what ia am trying to achive is when first the user selects 'a'

the results to be this

```<code> col1   col2    col3    col4
    1    a       1
    2    a      20      22
    3    a      15      15
    4    a               2
</code>```

Then if the user selects c the new dataframe will be

```<code> col1   col2    col3    col4    col2    col3    col4
    1    a       1                c               21
    2    a      20      22        c      14       14
    3    a      15      15        c       3       1
    4    a               2        c      22
</code>```

and so on

答:
Ok, I think I understand what you want. This does it I believe.

I made the following changes to your example

added a new datatable (rv$dfnew) as reactiveValues to keep track of our data table as it grows

Changed the display to show the currently selected part of the data frame as well as the growing dfnew table

Added a count variable that is appended to the columns as we proceed to keep them all unique.

Added an actionButton doAppendCols to append the columns.

Here is the code:

```<code>library(shiny)
library(data.table)
col1<-rep(c(1:4),3)

col2<-c('a','b','c','a','b','c','a','b','c','a','b','c')
col3<-c(1,2,3,NA,NA,14,15,NA,NA,20,21,22)
col4<-c(NA,NA,1,2,3,14,15,20,21,22,NA,NA)
df<-data.table(col1,col2,col3,col4)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Append Columns"),

  selectInput('Ind', 'Index',choices = c(unique(df$col2))),
  actionButton("doAppendCols","Append Columns"),
  h2("Selected Data"),
  dataTableOutput('selTable'),
  h2("New Table"),
  dataTableOutput('newTable')
)
# Define server logic required to draw a histogram
server <- function(input, output) {

  rv <- reactiveValues(dfnew=NULL,count=0)

  observeEvent(input$doAppendCols,{
    rv$count <- rv$count+1
    dfs <- dfsel()
    # add a running number as suffix to column names to make the columns unique
    newsuffix <- paste0(".",rv$count)
    ncols <- ncol(dfs)
    names(dfs)[2:ncols] <- paste0( names(dfs)[2:ncols],newsuffix )
    if(is.null(rv$dfnew)){
      rv$dfnew <- dfs
    } else {
      rv$dfnew <- merge(rv$dfnew,dfs,by="col1")
    }
  })

  dfsel<-reactive({
    df<-subset(df,col2==input$Ind)
    df <- df[order(df$col1),]
  })
  output$selTable<-renderDataTable(dfsel())
  output$newTable<-renderDataTable(rv$dfnew)

}

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

And here is the sample output:

Body:
I am trying to make an app that according to the selection of the user will subsetting the dataframe of the data. After that I want to create a new dataframe with unique values of col1 abd and the new dataframes added as new columns to the existing dataframe depending on users choice (like from a long shape of the dates making them in wide).
Any thoughts???
my dataset is that

col1<-rep(c(1:4),3)
col2<-c('a','b','c','a','b','c','a','b','c','a','b','c')
col3<-c(1,2,3,NA,NA,14,15,NA,NA,20,21,22)
col4<-c(NA,NA,1,2,3,14,15,20,21,22,NA,NA)
df<-data.table(col1,col2,col3,col4)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   selectInput('Ind', 'Index',choices = c(unique(df$col2))),
   dataTableOutput('Table')
)
# Define server logic required to draw a histogram
server <- function(input, output) {

 dfsel<-reactive({dfnew<-subset(df,col2==input$Ind)
 dfnew
 })
 output$Table<-renderDataTable(dfsel())

}

# Run the application
shinyApp(ui = ui, server = server)

what ia am trying to achive is when first the user selects 'a'

the results to be this

 col1   col2    col3    col4
    1    a       1
    2    a      20      22
    3    a      15      15
    4    a               2

Then if the user selects c the new dataframe will be

 col1   col2    col3    col4    col2    col3    col4
    1    a       1                c               21
    2    a      20      22        c      14       14
    3    a      15      15        c       3       1
    4    a               2        c      22

and so on

Body:
Ok, I think I understand what you want. This does it I believe.

I made the following changes to your example

added a new datatable (rv$dfnew) as reactiveValues to keep track of our data table as it grows

Changed the display to show the currently selected part of the data frame as well as the growing dfnew table

Added a count variable that is appended to the columns as we proceed to keep them all unique.

Added an actionButton doAppendCols to append the columns.

Here is the code:

library(shiny)
library(data.table)
col1<-rep(c(1:4),3)

col2<-c('a','b','c','a','b','c','a','b','c','a','b','c')
col3<-c(1,2,3,NA,NA,14,15,NA,NA,20,21,22)
col4<-c(NA,NA,1,2,3,14,15,20,21,22,NA,NA)
df<-data.table(col1,col2,col3,col4)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Append Columns"),

  selectInput('Ind', 'Index',choices = c(unique(df$col2))),
  actionButton("doAppendCols","Append Columns"),
  h2("Selected Data"),
  dataTableOutput('selTable'),
  h2("New Table"),
  dataTableOutput('newTable')
)
# Define server logic required to draw a histogram
server <- function(input, output) {

  rv <- reactiveValues(dfnew=NULL,count=0)

  observeEvent(input$doAppendCols,{
    rv$count <- rv$count+1
    dfs <- dfsel()
    # add a running number as suffix to column names to make the columns unique
    newsuffix <- paste0(".",rv$count)
    ncols <- ncol(dfs)
    names(dfs)[2:ncols] <- paste0( names(dfs)[2:ncols],newsuffix )
    if(is.null(rv$dfnew)){
      rv$dfnew <- dfs
    } else {
      rv$dfnew <- merge(rv$dfnew,dfs,by="col1")
    }
  })

  dfsel<-reactive({
    df<-subset(df,col2==input$Ind)
    df <- df[order(df$col1),]
  })
  output$selTable<-renderDataTable(dfsel())
  output$newTable<-renderDataTable(rv$dfnew)

}

# Run the application
shinyApp(ui = ui, server = server)

And here is the sample output:


问:
Split paragraph into sentences with Python3
I'm programming a telegram Bot helping me learn German.

Instead of translating the entire paragraph, I would like to translate step by step each sentence, with its translation following immediately, so that I can confront words and learn, instead of keep scrolling up and down.

I'm a regex newbie.

I would like to know if there exist such one.

My text to split into sentences could be like this:

```<code>This is a sentence.
This is another. And here one another, same line, starting with space.
this sentence starts with lowercase letter.
Here is a site you may know: google.com.
</code>```

I would like to get an array containing something like (I'm here writing one element of the array per row you are seeing now):

```<code>This is a sentence.
This is another.
And here one another,same line, starting with space.
this sentence starts with lowercase letter.
Here is a site you may know: google.com.
</code>```

Thanks indeed in advance.

答:
This is very likely better handled with nltk (having installed it correctly, that is):

```<code>from nltk.tokenize import sent_tokenize

string = "This is a sentence. This is another. And here one another, same line, starting with space. this sentence starts with lowercase letter. Here is a site you may know: google.com."

sent_tokenize_list = sent_tokenize(string)
print(sent_tokenize_list)
# ['This is a sentence.', 'This is another.', 'And here one another, same line, starting with space.', 'this sentence starts with lowercase letter.', 'Here is a site you may know: google.com.']
</code>```

Body:
I'm programming a telegram Bot helping me learn German.

Instead of translating the entire paragraph, I would like to translate step by step each sentence, with its translation following immediately, so that I can confront words and learn, instead of keep scrolling up and down.

I'm a regex newbie.

I would like to know if there exist such one.

My text to split into sentences could be like this:

This is a sentence.
This is another. And here one another, same line, starting with space.
this sentence starts with lowercase letter.
Here is a site you may know: google.com.

I would like to get an array containing something like (I'm here writing one element of the array per row you are seeing now):

This is a sentence.
This is another.
And here one another,same line, starting with space.
this sentence starts with lowercase letter.
Here is a site you may know: google.com.

Thanks indeed in advance.

Body:
This is very likely better handled with nltk (having installed it correctly, that is):

from nltk.tokenize import sent_tokenize

string = "This is a sentence. This is another. And here one another, same line, starting with space. this sentence starts with lowercase letter. Here is a site you may know: google.com."

sent_tokenize_list = sent_tokenize(string)
print(sent_tokenize_list)
# ['This is a sentence.', 'This is another.', 'And here one another, same line, starting with space.', 'this sentence starts with lowercase letter.', 'Here is a site you may know: google.com.']


问:
Efficient Multi-threading in C
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

```<code> for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

```<code> for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?

答:
Parallel computing (OpenCL and also vectorization) is the best way to do multiple tasks on the same object. Maybe one of the best usage examples of multithreading is a typical "Client-Server chat communication&I/O". An MT server is a lot more efficient than a multiprocess server because each operation of communication does not costs enough to be handled by a single process.

If I consider your matrix problem I would approach it by using GPU power and parallel computing with OpenCL because with it every single element in the matrix can be processed at the same time than the others.

Here is an example of matrix addition with OpenCL

If I must use threads I will break the problem by creating n threads (where n are the number of physical (or even logic) cores of your CPU and dividing the computation of the matrix in n parts just as you have done. Obviously, there's a mutual exclusion to be handled by semaphores. Please note that by using pointer arithmetic the matrix will be attacked contemporary by the threads.

EDIT: Please note that the multithread solution will work efficiently only if the CPU is multicore, in the case of a single core CPU, arithmetic multithread operations are more efficient than mono thread solution.

If this does not answer your question, please be more precise about what you're looking for.

Title: Efficient Multi-threading in C

Body:
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

 for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

 for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?


问:
Swift 3 - Pulling images from mySQL database
I am currently in the process of designing an application that has a newsfeed. Images and text are stored in our database but I am having trouble pulling the image and displaying it. The code I have should work but I am getting a fatal error saying "THREAD 1: EXC_BAD_INSTRUCTION" around

```<code>let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
</code>```

and the compiler displays this message - "fatal error: unexpectedly found nil while unwrapping an Optional value".

I'm getting the error in this snippet of code:

```<code>if!path!.isEmpty {
    let url = URL(string: path!)!
    let imageData = try? Data(contentsOf: url)
    let image = UIImage(data: imageData!)!
    self.images.append(image)
} else {
    let image = UIImage()
    self.images.append(image)
}
</code>```

Being very new to programming, I've been stuck on this for quite a while now. If there is anything you suggest, let me know! Thanks!

Also, the photo I am trying to retrieve is a .jpg, not sure if that may be important.

(Here's the rest of the code if it is needed)

```<code>import UIKit

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var activities = [AnyObject]()
var images = [UIImage]()

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    //tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return activities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell

    let post = activities[indexPath.row]
    let image = images[indexPath.row]
    let username = post["username"] as? String
    let text = post["text"] as? String

    cell.titleLbl.text = text
    cell.userLbl.text = username
    cell.activityImage.image! = image
    //cell.dateLbl.text = activities[indexPath.row]
    //cell.activityImage.image = images[indexPath.row]

    return cell
}

override func viewWillAppear(_ animated: Bool) {
    loadActivities()
}

func loadActivities() {
    let id = user!["id"] as! String
    let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "id=\(id)&text=&uuid="
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in
        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    // clean up
                    self.activities.removeAll(keepingCapacity: false)
                    self.images.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let posts = parseJSON["posts"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                    }

                    self.activities = posts

                    for i in 0 ..< self.activities.count {

                        let path = self.activities[i]["path"] as? String

                        if !path!.isEmpty {
                            let url = URL(string: path!)!
                            let imageData = try? Data(contentsOf: url)
                            let image = UIImage(data: imageData!)!
                            self.images.append(image)
                        } else {
                            let image = UIImage()
                            self.images.append(image)
                        }

                    }

                    self.tableView.reloadData()

                } catch {
                }

            } else {
            }

        })

        }.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension NSMutableData {

func appendString(_ string : String) {

    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    append(data!)

}

}
</code>```

答:
Why are you doing all of this ? Get the URLs of the images from your server and then load them asynchronously in cellForRowAtIndexPath using SDWebImage. It is a library you can find it here. https://github.com/rs/SDWebImage. This way you won't need to store your images in an array and it will be faster to load.

Or you can also implement your own async loading of images.

Body:
I am currently in the process of designing an application that has a newsfeed. Images and text are stored in our database but I am having trouble pulling the image and displaying it. The code I have should work but I am getting a fatal error saying "THREAD 1: EXC_BAD_INSTRUCTION" around

let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!

and the compiler displays this message - "fatal error: unexpectedly found nil while unwrapping an Optional value".

I'm getting the error in this snippet of code:

if!path!.isEmpty {
    let url = URL(string: path!)!
    let imageData = try? Data(contentsOf: url)
    let image = UIImage(data: imageData!)!
    self.images.append(image)
} else {
    let image = UIImage()
    self.images.append(image)
}

Being very new to programming, I've been stuck on this for quite a while now. If there is anything you suggest, let me know! Thanks!

Also, the photo I am trying to retrieve is a .jpg, not sure if that may be important.

(Here's the rest of the code if it is needed)

import UIKit

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var activities = [AnyObject]()
var images = [UIImage]()

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    //tableView.contentInset = UIEdgeInsetsMake(2, 0, 0, 0)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return activities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath) as! CustomCell

    let post = activities[indexPath.row]
    let image = images[indexPath.row]
    let username = post["username"] as? String
    let text = post["text"] as? String

    cell.titleLbl.text = text
    cell.userLbl.text = username
    cell.activityImage.image! = image
    //cell.dateLbl.text = activities[indexPath.row]
    //cell.activityImage.image = images[indexPath.row]

    return cell
}

override func viewWillAppear(_ animated: Bool) {
    loadActivities()
}

func loadActivities() {
    let id = user!["id"] as! String
    let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "id=\(id)&text=&uuid="
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in
        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    // clean up
                    self.activities.removeAll(keepingCapacity: false)
                    self.images.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let posts = parseJSON["posts"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                    }

                    self.activities = posts

                    for i in 0 ..< self.activities.count {

                        let path = self.activities[i]["path"] as? String

                        if !path!.isEmpty {
                            let url = URL(string: path!)!
                            let imageData = try? Data(contentsOf: url)
                            let image = UIImage(data: imageData!)!
                            self.images.append(image)
                        } else {
                            let image = UIImage()
                            self.images.append(image)
                        }

                    }

                    self.tableView.reloadData()

                } catch {
                }

            } else {
            }

        })

        }.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension NSMutableData {

func appendString(_ string : String) {

    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    append(data!)

}

}


问:
HTML Favicon.ico won't show on Google Chrome
I am making a HTML page and one of the things I wanted was a favicon appearing next to the title.

I'm using Google Chrome, I see favicons working on other websites, but the favicon on my website won't show up.  The site is in a folder on my desktop named site.

The favicon.ico file is 16x16, and I used an online generator to make it.

This is the code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="shortcut icon" href="/favicon.ico" />
    </head>
    <body>
    </body>
</html>
</code>```

答: I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.

Body:
I am making a HTML page and one of the things I wanted was a favicon appearing next to the title.

I'm using Google Chrome, I see favicons working on other websites, but the favicon on my website won't show up.  The site is in a folder on my desktop named site.

The favicon.ico file is 16x16, and I used an online generator to make it.

This is the code:

<!DOCTYPE html>

        <title></title>
        <link rel="shortcut icon" href="/favicon.ico" />


问:
Vue.js 2: set a prop value via http.get before the component is mounted
I want to get data from my server to populate a prop or data in vuejs.

Basically I need to pass the data as a parameter of my component.

```<code>    data() {
        return {
            recursos_data : [
                    { id: 'a', title: 'Room A' },
                    { id: 'b', title: 'Room B', eventColor: 'green' },
                    { id: 'c', title: 'Room C', eventColor: 'orange' },
                    { id: 'd', title: 'Room D', eventColor: 'red' }
                ],
            meus_recursos: []
        }
    },
    methods: {
        getResources: function() {
            var self = this;
            Vue.http.get('/admin/getResources').then((response) => {
                _.forEach(response.data.resources,function(item){
                    self.meus_recursos.push(item);
                });
                console.log(self.meus_recursos);
                return self.meus_recursos;
            });
        },
    },
    mounted() {
        const cal = $(this.$el),
            self = this;

        self.getResources();

        cal.fullCalendar({
            header: this.header,
            defaultView: this.defaultView,
            editable: this.editable,
            selectable: this.selectable,
            selectHelper: this.selectHelper,
            aspectRatio: 2,
            slotDuration: '00:10:00',
            timeFormat: 'HH:mm',
            eventSources: self.eventSources,
            events: self.events,
            resources: self.recursos_data,
            fixedWeekCount: false,
            firstDay: 1
         });
     }
</code>```

I need to get the data from the url but I don't know how to make it work.
I've tried computed, props, and method, but they don't work...

I need to get the data from the value returned from my server instead of from the variable recursos_data. How can one achieve this in vuejs?

答:
The answer is: you can't.

You need to switch your mindset. Every component is reactive and should display itself accordingly to it's model. You can't "stop" the component while downloading your data from the server. I see 2 solutions in your this situation:

Handle "data not ready" state by displaying some throbber or just empty list. It doesn't matter if you are changing data internaly or changing props from the parent component. You can add a flag like dataReady to data and set it to true after your ajax has finished. In your template you will have some if statement using this flag to display the throbber or data.

Control it from its parent component and display the component one only after the data is ready.

No other ways.

Body:
I want to get data from my server to populate a prop or data in vuejs.

Basically I need to pass the data as a parameter of my component.

    data() {
        return {
            recursos_data : [
                    { id: 'a', title: 'Room A' },
                    { id: 'b', title: 'Room B', eventColor: 'green' },
                    { id: 'c', title: 'Room C', eventColor: 'orange' },
                    { id: 'd', title: 'Room D', eventColor: 'red' }
                ],
            meus_recursos: []
        }
    },
    methods: {
        getResources: function() {
            var self = this;
            Vue.http.get('/admin/getResources').then((response) => {
                _.forEach(response.data.resources,function(item){
                    self.meus_recursos.push(item);
                });
                console.log(self.meus_recursos);
                return self.meus_recursos;
            });
        },
    },
    mounted() {
        const cal = $(this.$el),
            self = this;

        self.getResources();

        cal.fullCalendar({
            header: this.header,
            defaultView: this.defaultView,
            editable: this.editable,
            selectable: this.selectable,
            selectHelper: this.selectHelper,
            aspectRatio: 2,
            slotDuration: '00:10:00',
            timeFormat: 'HH:mm',
            eventSources: self.eventSources,
            events: self.events,
            resources: self.recursos_data,
            fixedWeekCount: false,
            firstDay: 1
         });
     }

I need to get the data from the url but I don't know how to make it work.
I've tried computed, props, and method, but they don't work...

I need to get the data from the value returned from my server instead of from the variable recursos_data. How can one achieve this in vuejs?


问:
R how to get the third and last row for each user
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

```<code>User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..
</code>```

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

答:
You could use a data.table solution  like this:</p>

```<code>library(data.table)

dt  = data.table("user" = c(rep(1,5),rep(2,5)),"num" = c(3,2,5,8,6,10:6))

dt[, "row" := 1:.N, by =.(user)]

> dt[ , .(Num = 3,.N), by = .(user)]
   user Num N
1:    1   3 5
2:    2   3 5
</code>```

Body:
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

Body:
You could use a data.table solution  like this:

library(data.table)

dt  = data.table("user" = c(rep(1,5),rep(2,5)),"num" = c(3,2,5,8,6,10:6))

dt[, "row" := 1:.N, by =.(user)]

> dt[ , .(Num = 3,.N), by = .(user)]
   user Num N
1:    1   3 5
2:    2   3 5


问:
What is 'Context' on Android?
In Android programming, what exactly is a Context class and what is it used for?

I read about it on the developer site, but I am unable to understand it clearly.

答:
Putting simple, Androids Context is a mess that you won't love until you stop worrying about.

Android Contexts are:

God-objects.

Thing that you want to pass around all your application when you are starting developing for Android, but will avoid doing it when you get a little bit closer to programming, testing and Android itself.

Unclear dependency.

Common source of memory leaks.

PITA for testing.

Actual context used by Android system to dispatch permissions, resources, preferences, services, broadcasts, styles, showing dialogs and inflating layout. And you need different Context instances for some separate things (obviously, you can't show a dialog from an application or service context; layouts inflated from application and activity contexts may differ).

Title: What is 'Context' on Android?


问:
How can two tabs communicate inside a browser?
How can prepare a communication channel to communicate between multiple opened tabs in same browser without any server side support?</p>

答:
Take a look at Window/postMessage.

You can also use Window.localStorage and register a StorageEvent and react on it from another tab.

Here's an interesting read: Using the Web Storage API;

EXAMPLE using localStorage and the StorageEvent

Put this into page1.html

```<code><button>CLICK ME TO CHANGE "A" - "B"</button>
<script>
document.querySelector("button").addEventListener("click", function(){
  localStorage.ab = localStorage.ab ===  "A" ? "B" : "A";
});
</script>
</code>```

and this into page2.html

```<code><script>
window.addEventListener("storage", function( StorageEvent ){
  console.log( StorageEvent );
  alert(StorageEvent.newValue);
});
</script>
</code>```

Body:
Take a look at Window/postMessage.

You can also use Window.localStorage and register a StorageEvent and react on it from another tab.

Here's an interesting read: Using the Web Storage API;

EXAMPLE using localStorage and the StorageEvent

Put this into page1.html

<button>CLICK ME TO CHANGE "A" - "B"</button>
<script>
document.querySelector("button").addEventListener("click", function(){
  localStorage.ab = localStorage.ab ===  "A" ? "B" : "A";
});
</script>

and this into page2.html

<script>
window.addEventListener("storage", function( StorageEvent ){
  console.log( StorageEvent );
  alert(StorageEvent.newValue);
});
</script>


问:
How to code a union using a struct as template, while having that union as an element

I am trying to construct a union that will replace the pair of pointers (left & right)
by a union which is accessible as an array.
Originally this is working code for a Binary Search Tree (BST)

I want to be able to do this:

```<code>p = p->pLR.array[value>insertValue];
</code>```

in addition to the old branched

```<code>if(value>insertValue) p = p->right;
else  p = p->left;
</code>```

1b. This is not exactly to avoid costly branching misprediction,
but simply to be able to learn to implement [something] like this.

Mostly the problem that BinaryNode is templated in the union, and the union is an element of the BinaryNode!

Here is my non-compiling code-in-progress:

```<code>template    <class dataType, class BinaryNode<dataType> >
union BinaryNodePointerPair {
struct {
        BinaryNode<dataType> *left;
        BinaryNode<dataType> *right;
    };
    BinaryNode<dataType> *array[2];
};
template    <class dataType>
struct BinaryNode {
    dataType    value;
    BinaryNodePointerPair<dataType,BinaryNode<dataType> > pLR;
};
[Error] 'BinaryNode' is not a template
</code>```

refactored from:

```<code>template    <class dataType>
struct BinaryNode {
    dataType    value;
    BinaryNode  *left;
    BinaryNode  *right;
};
</code>```

What I have tried so far:

3a. According to   'X is not a template' error
the template should be

```<code>template    <class dataType, class <dataType>BinaryNode >
[Error] expected identifier before '<' token
[Error] expected '>' before '<' token
[Error] type/value mismatch at argument 2 in template parameter list for 'template<class dataType, int <anonymous> > union BinaryNodePointerPair'
</code>```

3b. So i change it to

```<code>template    <class dataType, class BinaryNode<dataType> >
</code>```

But this gives the errors, plus the original.

```<code>[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
</code>```

3c. So i again change it to

```<code>template    <class dataType, class BinaryNode<dataType> >
</code>```

but this gives even more errors

```<code>[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
[Error] 'BinaryNode' is not a template type
</code>```

3d. Now, this is eerily close to CRTP
(no need to tell me this isnt real CRTP, but it is curiously)

```<code>template    <class dataType>
union BinaryNodePointerPair {
struct {
    BinaryNode<dataType> *left;
    BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template    <class dataType, BinaryNodePointerPair<dataType> >
struct BinaryNode {
    dataType    value;
    BinaryNodePointerPair<dataType> pLR;
};
[Error] 'BinaryNode' is not a template
</code>```

Only 1 error! WOW! This has got to be a winner!

3e. Now I really really force-pattern it into CRTP... it's even worse.

```<code>if(value>insertValue) p = p->right;
else  p = p->left;
</code>```0

It doesn't have to be CRTP.
Is there a way to do it?

How do I write a union w/ pointers to a struct having an element of that union?

答:
I don't really get the question, but did you perhaps forget the forward declaration of BinaryNode?

```<code>template <class dataType>
struct BinaryNode;

template <class dataType>
union BinaryNodePointerPair
{
  struct
  {
    BinaryNode<dataType> *left;
    BinaryNode<dataType> *right;
  };
  BinaryNode<dataType> *array[2];
};

template <class dataType>
struct BinaryNode
{
  dataType value;
  BinaryNodePointerPair<dataType> pLR;
};
</code>```

Body:
I am trying to construct a union that will replace the pair of pointers (left & right)
by a union which is accessible as an array.
Originally this is working code for a Binary Search Tree (BST)

I want to be able to do this:

p = p->pLR.array[value>insertValue];

in addition to the old branched

if(value>insertValue) p = p->right;
else  p = p->left;

1b. This is not exactly to avoid costly branching misprediction,
but simply to be able to learn to implement [something] like this.

Mostly the problem that BinaryNode is templated in the union, and the union is an element of the BinaryNode!

Here is my non-compiling code-in-progress:

template    <class dataType, class BinaryNode<dataType> >
union BinaryNodePointerPair {
struct {
        BinaryNode<dataType> *left;
        BinaryNode<dataType> *right;
    };
    BinaryNode<dataType> *array[2];
};
template    <class dataType>
struct BinaryNode {
    dataType    value;
    BinaryNodePointerPair<dataType,BinaryNode<dataType> > pLR;
};
[Error] 'BinaryNode' is not a template

refactored from:

template    <class dataType>
struct BinaryNode {
    dataType    value;
    BinaryNode  *left;
    BinaryNode  *right;
};

What I have tried so far:

3a. According to   'X is not a template' error
the template should be

template    <class dataType, class <dataType>BinaryNode >
[Error] expected identifier before '<' token
[Error] expected '>' before '<' token
[Error] type/value mismatch at argument 2 in template parameter list for 'template<class dataType, int <anonymous> > union BinaryNodePointerPair'

3b. So i change it to

template    <class dataType, class BinaryNode<dataType> >

But this gives the errors, plus the original.

[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template

3c. So i again change it to

template    <class dataType, class BinaryNode<dataType> >

but this gives even more errors

[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
[Error] 'BinaryNode' is not a template type

3d. Now, this is eerily close to CRTP
(no need to tell me this isnt real CRTP, but it is curiously)

template    <class dataType>
union BinaryNodePointerPair {
struct {
    BinaryNode<dataType> *left;
    BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template    <class dataType, BinaryNodePointerPair<dataType> >
struct BinaryNode {
    dataType    value;
    BinaryNodePointerPair<dataType> pLR;
};
[Error] 'BinaryNode' is not a template

Only 1 error! WOW! This has got to be a winner!

3e. Now I really really force-pattern it into CRTP... it's even worse.

template    <class dataType, class BinaryNode<dataType> >
union BinaryNodePointerPair {
    struct {
        BinaryNode<dataType> *left;
        BinaryNode<dataType> *right;
    };
    BinaryNode<dataType> *array[2];
};
template    <class dataType>
struct BinaryNode {
    dataType    value;
    BinaryNodePointerPair<dataType, BinaryNode<dataType>> pLR;
};
[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template

It doesn't have to be CRTP.
Is there a way to do it?

How do I write a union w/ pointers to a struct having an element of that union?

Body:
I don't really get the question, but did you perhaps forget the forward declaration of BinaryNode?

template <class dataType>
struct BinaryNode;

template <class dataType>
union BinaryNodePointerPair
{
  struct
  {
    BinaryNode<dataType> *left;
    BinaryNode<dataType> *right;
  };
  BinaryNode<dataType> *array[2];
};

template <class dataType>
struct BinaryNode
{
  dataType value;
  BinaryNodePointerPair<dataType> pLR;
};


答:
I expect your issue is some interaction between fullCalendar and your asynchronous method. You want to initialize fullCalendar after your data is returned.

How about returning the promise from your getResources method?

```<code>methods: {
    getResources: function() {
        var self = this;
        return Vue.http.get('/admin/getResources').then((response) => {
            _.forEach(response.data.resources,function(item){
                self.meus_recursos.push(item);
            });
        });
    },
},

mounted() {
    const cal = $(this.$el),
        self = this;

    self.getResources().then(() => {
        cal.fullCalendar({
            header: this.header,
            defaultView: this.defaultView,
            editable: this.editable,
            selectable: this.selectable,
            selectHelper: this.selectHelper,
            aspectRatio: 2,
            slotDuration: '00:10:00',
            timeFormat: 'HH:mm',
            eventSources: self.eventSources,
            events: self.events,
            resources: self.meus_recursos,
            fixedWeekCount: false,
            firstDay: 1
         });
    });
 }
</code>```

Or, you could call fullCalendar right afterwards in getResources.

```<code>getResources: function() {
    var self = this;
    return Vue.http.get('/admin/getResources')
        .then((response) => {
            _.forEach(response.data.resources,function(item){
                self.meus_recursos.push(item);
        })
        .then(() => {
            $(this.$el).fullCalendar({
                header: this.header,
                defaultView: this.defaultView,
                editable: this.editable,
                selectable: this.selectable,
                selectHelper: this.selectHelper,
                aspectRatio: 2,
                slotDuration: '00:10:00',
                timeFormat: 'HH:mm',
                eventSources: self.eventSources,
                events: self.events,
                resources: self.meus_recursos,
                fixedWeekCount: false,
                firstDay: 1
             });
        })
    });
}
</code>```

Alternatively you could not even mount the component until you retrieve the data.

Title: Vue.js 2: set a prop value via http.get before the component is mounted

Body:
I expect your issue is some interaction between fullCalendar and your asynchronous method. You want to initialize fullCalendar after your data is returned.

How about returning the promise from your getResources method?

methods: {
    getResources: function() {
        var self = this;
        return Vue.http.get('/admin/getResources').then((response) => {
            _.forEach(response.data.resources,function(item){
                self.meus_recursos.push(item);
            });
        });
    },
},

mounted() {
    const cal = $(this.$el),
        self = this;

    self.getResources().then(() => {
        cal.fullCalendar({
            header: this.header,
            defaultView: this.defaultView,
            editable: this.editable,
            selectable: this.selectable,
            selectHelper: this.selectHelper,
            aspectRatio: 2,
            slotDuration: '00:10:00',
            timeFormat: 'HH:mm',
            eventSources: self.eventSources,
            events: self.events,
            resources: self.meus_recursos,
            fixedWeekCount: false,
            firstDay: 1
         });
    });
 }

Or, you could call fullCalendar right afterwards in getResources.

getResources: function() {
    var self = this;
    return Vue.http.get('/admin/getResources')
        .then((response) => {
            _.forEach(response.data.resources,function(item){
                self.meus_recursos.push(item);
        })
        .then(() => {
            $(this.$el).fullCalendar({
                header: this.header,
                defaultView: this.defaultView,
                editable: this.editable,
                selectable: this.selectable,
                selectHelper: this.selectHelper,
                aspectRatio: 2,
                slotDuration: '00:10:00',
                timeFormat: 'HH:mm',
                eventSources: self.eventSources,
                events: self.events,
                resources: self.meus_recursos,
                fixedWeekCount: false,
                firstDay: 1
             });
        })
    });
}

Alternatively you could not even mount the component until you retrieve the data.


问:
how to restrict access to directory so I can run php scripts from browser
First post, be gentle :) ... I have been doing searches on this site as well as others and realize I may be in over my head.

Here is the situation:

1) I have a website running on BlueHost (linux OS, I think is running Apache) that is open for general access

2) I have a set of php scripts on the website that I would like to limit the access to only one user via some sort of login through a webbrowser.

3) I have put the scripts in a directory under /home/public_html.  I did not know how to access the files with a web browser above that level (like in /home)

4) These scripts do not access any other part of the website nor does any other part of the website access the scripts.

Here is what I tried:

1) Using cpanel to change the permissions on the directory. Result was a 404 when I try to access the scripts with a browser.

2) .htaccess/.htpasswd for the folder in question (found some instructions here and on the web).  Didn't seem to force asking for a password so I probably did something wrong

I know this is vague but I will ask it anyway...  Given my situation, is there a preferred approach I can research?  For example, having the php code ask the user for a password, somehow accessing the scripts from the server side, etc.

Thanks for your patience and help

答: BTW, You can create a username/encrypted pair by using the free tool htpasswd generator</p>


答:
As @jonathon said, the operator is written <>.

```<code>Check 1 <> 2.
</code>```

But you can also do this:

```<code>Require Import Unicode.Utf8.
Check 1 ≠ 2.
</code>```

Title: Unicode "not equal" notation in Coq (≠)

Body:
The following text is mentioned in SF book:

This is how we use not to state that 0 and 1 are different elements of nat:

Theorem zero_not_one : ~(0 = 1).
Proof.
  intros contra. inversion contra.
Qed.

Such inequality statements are frequent enough to warrant a special
  notation, x ≠ y:

Check (0 ≠ 1).
(* ===> Prop *)

But when I actually do this in Coq:

Check (0 ≠ 1).

It gives me this error:

Syntax Error: Lexer: Undefined token

In fact, looking at the standard
library, I
cannot seem to find any notation for that. So, what is the proper
notation for it ?

Body:
As @jonathon said, the operator is written <>.

Check 1 <> 2.

But you can also do this:

Require Import Unicode.Utf8.
Check 1 ≠ 2.


答:
I personally have issues with JQuery, as it seems to stop people looking into JavaScript's native capabilities.  I would personally use the onerror event, e.g.:

myimage.onerror = function() { this.style.visibility = 'hidden'; }

(not tested)

Title: want to hide image when image is not found at the src location?

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.


问:
Restore to an earlier commit in Git Shell
Lets say i have 20 commits on a project in github. After 20 commits i feel like my program is running slow. I there fore want to go back and test when the programs slows down. I simply cant figure out what command i need to use to sync my local drive with a specific commit id from github. Please help, i know this is probably very simple. How

Ive tried git checkout, but this creates a new branch or something

```<code>git checkout <SHA HASH>
</code>```

答:
Actually you can use git checkout like you tried. As long as you don't use the -b option, this does not create a new branch, but leaves you with a detached HEAD (i. e. HEAD points to a specific commit, not to a branch), so exactly what you want.

If you do not want to test one commit after another to find the point where it slows down, you instead might want to use git bisect which supports exactly your usecase of efficiently finding one specific commit where something changes. This could be the commit where a bug was introduced, or the commit where something became slow or whatever. It supports this by a binary search algorithm, meaning you give it a commit where the project was slow and a commit where the project was fast, then Git checks out the middle between them. You then tell Git whether this commit is slow or fast and so on until Git tells you it has found the first commit where the project became slow, based on your input. You usually need waaaay less tries to find the commit in question than when testing one commit after another.

Your command would be something like git bisect start --term-old=fast --term-new=slow @ @~20 if you know it is slow at the current commit and was fast 20 commits ago. Then after testing the checked out code you will call git bisect slow or git bisect fast until you found the commit in question. If you can determine whether the code is slow or fast programmatically, you can even give git bisect a script that tells bisect with its return value whether the commit is slow, fast or indeterminate (e. g. build fails so slow or fast cannot be measured) and Git will autmatically find you the commit in question without anymore manual intervention.

Body:
Lets say i have 20 commits on a project in github. After 20 commits i feel like my program is running slow. I there fore want to go back and test when the programs slows down. I simply cant figure out what command i need to use to sync my local drive with a specific commit id from github. Please help, i know this is probably very simple. How

Ive tried git checkout, but this creates a new branch or something

git checkout <SHA HASH>


问:
How can I create fillable input forms inside a pdf?
I need to create PDF forms which can be used to take input from the user. They need to contain drop down boxes and text boxes. Please suggest which software or tool will best suit my purpose</p>

答:
First of all, software recommendations have meanwhile become off-topic on stack overflow, different stack exchange sites for that have been established since then.

That been said, the question itself is not very exact. There actually are two major form technologies in use in PDFs: AcroForm forms and XFA forms.

AcroForm forms are the original PDF forms technology conclusively specified in the PDF specification ISO 32000-1 (soon to be updated by part 2). This technology only allows static forms, i.e. forms for which the number and positions of fields is already fixed at form definition time. (Actually there is a dynamic sub-feature of this technology, page templates which fields, which allows you to add extra pages with their own fields, but this feature is hardly ever used.)

Creating and filling this kind of forms nowadays is possible using a wide selection of options, desktop applications (Adobe's Acrobat being just one among many), web applications, and general purpose PDF libraries for many languages or platforms. A quick search on google can show you many options...

Displaying this kind of forms is possible on many PDF viewers, editing them visually at least on numerous of them.

XFA (XML Forms Architecture) forms are an alternative forms technology introduced by Adobe which is referenced by the PDF specification (part 1) but which has remained in the Adobe legacy domain. This technology actually uses PDF files merely as transport medium, the XML definitions of XFA forms define forms in a way that is independent of PDF as such. XFA forms can be dynamic (e.g. they can contain tables with variable number of columns), their form elements can grow and move later elements.

Creating and filling this kind of forms is possible using only a small selection of options, foremost Adobe desktop and server products and very few alternative solutions.

Displaying this kind of forms is possible only on Adobe products and a very small selection of other products, and depending on the version of the Adobe PDF viewer a digital signature by a Adobe private key might be required for non-trivial use of such forms.

Support for XFA forms will become deprecated in the ISO 32000-2 specification. Thus, using them in new projects might not be the best idea.


问:
design practice: is it good to hide/unhide controls at runtime
I have always had a bias against controls appearing/disappearing at runtime. I think that I read this somewhere but google is not forthcoming and I've not been successful in finding anything to support my bias in any of the hard-copies that I have. We're having an internal debate as to the validity of this approach and I wonder if anyone can point me to any reference that discusses the topic.

Thanks!

Bo

答:
If a using a control is going to produce an error, you probably want to at least disable that control.

Whether to hide or disable, depends on the control.  In a standard drop down menu, it probably makes sense to disable, because then all the items are still in the same place.


问:
Scaling InkStrokes in UWP
I've got a simple demo application that uses an image as the background of an InkCanvas and I scale the strokes when the display of the image is resized so that they remain in the same place relative to the image. Since you can draw -> resize -> draw -> resize -> draw this means I have to scale each stroke a different amount each time by assigning the PointTransform on each stroke.

```<code>float thisScale = (float)(scale / _prevScale);
foreach (InkStroke stroke in myCanvas.InkPresenter.StrokeContainer.GetStrokes())
{
    float thisPointScale = thisScale * stroke.PointTransform.M11;
    stroke.PointTransform = Matrix3x2.CreateScale(new Vector2(thisPointScale));
}
</code>```

This resizes the length of the strokes perfectly well. However, it does nothing to the thickness of the strokes. This is even more evident when you use a thick or non-uniform pen (eg the highlighter pen).

These link to two screen clips which show the results.
Full-screen - https://1drv.ms/i/s!ArHMZAt1svlBiZZDfrxFqyGU1bJ6MQ
Smaller window - https://1drv.ms/i/s!ArHMZAt1svlBiZZCqHHYaISPfWMMpQ

Any ideas on how I can resize the thickness of the strokes?

答:
Apply a ScaleTransform to the InkCanvas control. That'll take care of scaling the ink stroke,the stroke locations and the background image. Essentially the transform applies to everything contained in the InkCanvas. No need to use the Matrix with the StrokeCollection.

XAML

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <Button Content="Red Highlighter "
                x:Name="InkRedAttributesButton"
                Click="InkRedAttributesButton_Click" />
        <Button Content="Blue Highlighter "
                x:Name="InkBlueAttributesButton"
                Click="InkBlueAttributesButton_Click" />
        <Button Content="Scale Down"
                x:Name="ScaleDownButton"
                Click="ScaleDownButton_Click" />
        <Button Content="Scale Up"
                x:Name="ScaleUpButton"
                Click="ScaleUpButton_Click" />
    </StackPanel>
    <InkCanvas x:Name="myCanvas"
               Grid.Row="1"  HorizontalAlignment="Left" VerticalAlignment="Top">
        <InkCanvas.Background>
            <ImageBrush ImageSource="/SO_Questions;component/Images/Star02.jpg"
                        Stretch="Fill" />
        </InkCanvas.Background>
        <InkCanvas.RenderTransform>
            <ScaleTransform x:Name="InkCanvasScaleTransform" />
        </InkCanvas.RenderTransform>
    </InkCanvas>
</Grid>
</code>```

Code

```<code> private void ScaleUpButton_Click(object sender, RoutedEventArgs e) {
      InkCanvasScaleTransform.ScaleX += .2;
      InkCanvasScaleTransform.ScaleY += .2;

    }
    private void ScaleDownButton_Click(object sender, RoutedEventArgs e) {
      InkCanvasScaleTransform.ScaleX -= .2;
      InkCanvasScaleTransform.ScaleY -= .2;

    }

    private void InkRedAttributesButton_Click(object sender, RoutedEventArgs e) {
      DrawingAttributes inkAttributes = new DrawingAttributes();

      inkAttributes.Height = 12;
      inkAttributes.Width = 12;
      inkAttributes.Color = Colors.Red;
      inkAttributes.IsHighlighter = true;
      myCanvas.DefaultDrawingAttributes = inkAttributes;
    }

    private void InkBlueAttributesButton_Click(object sender, RoutedEventArgs e) {
      DrawingAttributes inkAttributes = new DrawingAttributes();

      inkAttributes.Height = 12;
      inkAttributes.Width = 12;
      inkAttributes.Color = Colors.Blue;
      inkAttributes.IsHighlighter = true;
      myCanvas.DefaultDrawingAttributes = inkAttributes;
    }
</code>```

Screenshots

Scaled 100%

Scaled 60%

Title: Scaling InkStrokes in UWP

Body:
I've got a simple demo application that uses an image as the background of an InkCanvas and I scale the strokes when the display of the image is resized so that they remain in the same place relative to the image. Since you can draw -> resize -> draw -> resize -> draw this means I have to scale each stroke a different amount each time by assigning the PointTransform on each stroke.

float thisScale = (float)(scale / _prevScale);
foreach (InkStroke stroke in myCanvas.InkPresenter.StrokeContainer.GetStrokes())
{
    float thisPointScale = thisScale * stroke.PointTransform.M11;
    stroke.PointTransform = Matrix3x2.CreateScale(new Vector2(thisPointScale));
}

This resizes the length of the strokes perfectly well. However, it does nothing to the thickness of the strokes. This is even more evident when you use a thick or non-uniform pen (eg the highlighter pen).

These link to two screen clips which show the results.
Full-screen - https://1drv.ms/i/s!ArHMZAt1svlBiZZDfrxFqyGU1bJ6MQ
Smaller window - https://1drv.ms/i/s!ArHMZAt1svlBiZZCqHHYaISPfWMMpQ

Any ideas on how I can resize the thickness of the strokes?

Body:
Apply a ScaleTransform to the InkCanvas control. That'll take care of scaling the ink stroke,the stroke locations and the background image. Essentially the transform applies to everything contained in the InkCanvas. No need to use the Matrix with the StrokeCollection.

XAML

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <Button Content="Red Highlighter "
                x:Name="InkRedAttributesButton"
                Click="InkRedAttributesButton_Click" />
        <Button Content="Blue Highlighter "
                x:Name="InkBlueAttributesButton"
                Click="InkBlueAttributesButton_Click" />
        <Button Content="Scale Down"
                x:Name="ScaleDownButton"
                Click="ScaleDownButton_Click" />
        <Button Content="Scale Up"
                x:Name="ScaleUpButton"
                Click="ScaleUpButton_Click" />
    </StackPanel>
    <InkCanvas x:Name="myCanvas"
               Grid.Row="1"  HorizontalAlignment="Left" VerticalAlignment="Top">
        <InkCanvas.Background>
            <ImageBrush ImageSource="/SO_Questions;component/Images/Star02.jpg"
                        Stretch="Fill" />
        </InkCanvas.Background>
        <InkCanvas.RenderTransform>
            <ScaleTransform x:Name="InkCanvasScaleTransform" />
        </InkCanvas.RenderTransform>
    </InkCanvas>
</Grid>

Code

 private void ScaleUpButton_Click(object sender, RoutedEventArgs e) {
      InkCanvasScaleTransform.ScaleX += .2;
      InkCanvasScaleTransform.ScaleY += .2;

    }
    private void ScaleDownButton_Click(object sender, RoutedEventArgs e) {
      InkCanvasScaleTransform.ScaleX -= .2;
      InkCanvasScaleTransform.ScaleY -= .2;

    }

    private void InkRedAttributesButton_Click(object sender, RoutedEventArgs e) {
      DrawingAttributes inkAttributes = new DrawingAttributes();

      inkAttributes.Height = 12;
      inkAttributes.Width = 12;
      inkAttributes.Color = Colors.Red;
      inkAttributes.IsHighlighter = true;
      myCanvas.DefaultDrawingAttributes = inkAttributes;
    }

    private void InkBlueAttributesButton_Click(object sender, RoutedEventArgs e) {
      DrawingAttributes inkAttributes = new DrawingAttributes();

      inkAttributes.Height = 12;
      inkAttributes.Width = 12;
      inkAttributes.Color = Colors.Blue;
      inkAttributes.IsHighlighter = true;
      myCanvas.DefaultDrawingAttributes = inkAttributes;
    }

Screenshots

Scaled 100%

Scaled 60%


问:
Google Maps geocoding API doesn't return administrative_area_level_1
I made a script calling Google Maps Geocoding API to retrieve administrative_area_level_1. It had been running fine retrieving tag for more than 90 % of addresses until December 2016. Since then, successful rate has dropped - in the API call result, there is no administrative_area_level_1 address anymore, or just sporadic.

The API call I've been using without change is in form:
https://maps.googleapis.com/maps/api/geocode/json?language=cs&region=cs&address=, , , &key=

i.e.:
https://maps.googleapis.com/maps/api/geocode/json?language=cs&region=cs&address=nám. W. Churchilla 1938/4, 130 67, Praha 3 - Žižkov, Česká republika&key=

Has Google made any changes? Is there any way, how to retrieve administrative_area_level_1 from Google Maps Geocoding API?

答:
In November 2016 Google announced a new version of forward geocoder.

In the new forward geocoder the address components array contains only information that is relevant for address formatting in the country in question.

If I understand correctly, the administrative area level 1 is not used for formatted addresses in Česká republika, so this information doesn't appear in the address components.

The only reliable method to get admin area 1 at the moment is to execute a reverse geocoding request with coordinates from your first request and with result type equal to admin area level 1.

For example,

forward geocoder for 'nám. W. Churchilla 1938/4, 130 67, Praha 3 - Žižkov, Česká republika' returns 50.083244, 14.441828

Now the reverse geocoding with result type admin area level 1:

https://maps.googleapis.com/maps/api/geocode/json?latlng=50.083244%2C14.441828&result_type=administrative_area_level_1&key=YOUR_API_KEY

returns the following result

```<code>{
  "results":[
    {
      "address_components":[
        {
          "long_name":"Prague",
          "short_name":"Prague",
          "types":[
            "administrative_area_level_1","political"
          ]
        },
        {
          "long_name":"Czechia",
          "short_name":"CZ",
          "types":[
             "country","political"
          ]
        }
      ],
      "formatted_address":"Prague, Czechia",
      "geometry":{
        "bounds":{
          "northeast":{
            "lat":50.177403,"lng":14.7067945
          },
          "southwest":{
            "lat":49.94193629999999,"lng":14.2244533
          }
        },
        "location":{
          "lat":50.0599268,"lng":14.5039935
        },
        "location_type":"APPROXIMATE",
        "viewport":{
          "northeast":{
            "lat":50.177403,"lng":14.7067945
          },
          "southwest":{
            "lat":49.94193629999999,"lng":14.2244533
          }
        }
      },
      "place_id":"ChIJi3lwCZyTC0cRIKgUZg-vAAE",
      "types":[
        "administrative_area_level_1","political"
      ]
    }
  ],
  "status":"OK"
}
</code>```

UPDATE

There is also a feature request in the public issue tracker to add the administrative area level 1 in the response for Czech republic:

https://issuetracker.google.com/issues/35830929

Fell free to star the feature request to express your interest and subscribe to notifications.

UPDATE 1

Good news.

The feature request 35830929 is now marked as Fixed by Google.

Body:
In November 2016 Google announced a new version of forward geocoder.

In the new forward geocoder the address components array contains only information that is relevant for address formatting in the country in question.

If I understand correctly, the administrative area level 1 is not used for formatted addresses in Česká republika, so this information doesn't appear in the address components.

The only reliable method to get admin area 1 at the moment is to execute a reverse geocoding request with coordinates from your first request and with result type equal to admin area level 1.

For example,

forward geocoder for 'nám. W. Churchilla 1938/4, 130 67, Praha 3 - Žižkov, Česká republika' returns 50.083244, 14.441828

Now the reverse geocoding with result type admin area level 1:

https://maps.googleapis.com/maps/api/geocode/json?latlng=50.083244%2C14.441828&result_type=administrative_area_level_1&key=YOUR_API_KEY

returns the following result

{
  "results":[
    {
      "address_components":[
        {
          "long_name":"Prague",
          "short_name":"Prague",
          "types":[
            "administrative_area_level_1","political"
          ]
        },
        {
          "long_name":"Czechia",
          "short_name":"CZ",
          "types":[
             "country","political"
          ]
        }
      ],
      "formatted_address":"Prague, Czechia",
      "geometry":{
        "bounds":{
          "northeast":{
            "lat":50.177403,"lng":14.7067945
          },
          "southwest":{
            "lat":49.94193629999999,"lng":14.2244533
          }
        },
        "location":{
          "lat":50.0599268,"lng":14.5039935
        },
        "location_type":"APPROXIMATE",
        "viewport":{
          "northeast":{
            "lat":50.177403,"lng":14.7067945
          },
          "southwest":{
            "lat":49.94193629999999,"lng":14.2244533
          }
        }
      },
      "place_id":"ChIJi3lwCZyTC0cRIKgUZg-vAAE",
      "types":[
        "administrative_area_level_1","political"
      ]
    }
  ],
  "status":"OK"
}

UPDATE

There is also a feature request in the public issue tracker to add the administrative area level 1 in the response for Czech republic:

https://issuetracker.google.com/issues/35830929

Fell free to star the feature request to express your interest and subscribe to notifications.

UPDATE 1

Good news.

The feature request 35830929 is now marked as Fixed by Google.


问:
Pygame error: not able to open .wav file
I have a problem with my Pygame program. I need help.
The wav file is in the same directory as the python file.
I run It in terminal- Python3:

```<code>import pygame.mixer
sounds = pygame.mixer
sounds.init()

def wait_finish(channel):
    while channel.get_busy():
        pass

asked = 0
true = 0
false = 0

choice = str(input("Push 1 for true, 2 for false, 0 to end"))
while choice != '0':
      if choice == '1':
             asked = asked + 1
             true = true + 1
             s = sounds.Sound("correct.wav")
             wait_finish(s.play())
      if choice == '2':
             asked = asked + 1
             false = false + 1
             s = sounds.Sound("wrong.wav")
             wait_finish(s.play())
      choice = str(input("Push 1 for true, 2 for false, 0 to end"))

print ("you asked" +str(asked) + "questions")
print ("there were" +str(false) + "wrong answers")
print ("and" + str(true) + "correct answers")
</code>```

It throws- pygame.error:

Unable to open file 'correct.wav'

答:
I had the same problem, could not get this code to work:

```<code>correctSound = pygame.mixer.Sound('jingle3.wav')
</code>```

I got pygame error:

Unable to open file 'jingle3.wav'

The problem was solved by loading the 'jingle3.wav' into Audicity and changing it from 32-bit PCM to a 16-bit PCM .wav-file. After that the pygame.mixer.Sound worked perfectly.

I got this tip on this forum, and it worked!

Body:
I have a problem with my Pygame program. I need help.
The wav file is in the same directory as the python file.
I run It in terminal- Python3:

import pygame.mixer
sounds = pygame.mixer
sounds.init()

def wait_finish(channel):
    while channel.get_busy():
        pass

asked = 0
true = 0
false = 0

choice = str(input("Push 1 for true, 2 for false, 0 to end"))
while choice != '0':
      if choice == '1':
             asked = asked + 1
             true = true + 1
             s = sounds.Sound("correct.wav")
             wait_finish(s.play())
      if choice == '2':
             asked = asked + 1
             false = false + 1
             s = sounds.Sound("wrong.wav")
             wait_finish(s.play())
      choice = str(input("Push 1 for true, 2 for false, 0 to end"))

print ("you asked" +str(asked) + "questions")
print ("there were" +str(false) + "wrong answers")
print ("and" + str(true) + "correct answers")

It throws- pygame.error:

Unable to open file 'correct.wav'

Body:
I had the same problem, could not get this code to work:

correctSound = pygame.mixer.Sound('jingle3.wav')

I got pygame error:

Unable to open file 'jingle3.wav'

The problem was solved by loading the 'jingle3.wav' into Audicity and changing it from 32-bit PCM to a 16-bit PCM .wav-file. After that the pygame.mixer.Sound worked perfectly.

I got this tip on this forum, and it worked!


问:
Dynamic angular.js orderby button ng-click
Here is the code:

```<code><button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>
<div ng-repeat="item in items | orderBy: propriety">
  <li>item.name - item.price</li>
</div>
</code>```

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

答:
try

```<code><button ng-init="propriety= 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'">
</code>```

working fiddle

Body:
Here is the code:

<button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>

item.name - item.price

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

Body:
try

<button ng-init="propriety= 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'">

working fiddle


问:
Unity double mouse click input event receive
I'm making a 2D topdown shooter in Unity (version 5.6.0b3 64-bit) and I have a problem with receive mouse input properly, especially mousewheel.

I'm using mousewheel for switching weapons.

I have a problem with registering mouse input.

Code for my mouse:

```<code>if(Input.GetAxis("Mouse ScrollWheel")>0)
{
Debug.Log("Mousewheel Up");
}

if(Input.GetAxis("Mouse ScrollWheel")<0)
{
Debug.Log("Mousewheel Down");
}
</code>```

After first launching game in main menu in console I can see it detecting corretly

But after starting game and loading scene its starting to act weird and double registering mouse wheel moving:

And by this bug switching weapon not working corretly (it double switching it, missing one in the middle)
for example i have 3 weapons, from 1 it switches to 3.

Also it spawn 2 explosions on 1 right click (should be 1)

I don't know what is going on, I appreciate every help.

答: OK, I found bug in my scripts (after I find out that I can click on Debug Log and trace the call) I was calling my Input function second time (not needed) from second player controlling script. Problem solved.</p>

Body:
I'm making a 2D topdown shooter in Unity (version 5.6.0b3 64-bit) and I have a problem with receive mouse input properly, especially mousewheel.

I'm using mousewheel for switching weapons.

I have a problem with registering mouse input.

Code for my mouse:

if(Input.GetAxis("Mouse ScrollWheel")>0)
{
Debug.Log("Mousewheel Up");
}

if(Input.GetAxis("Mouse ScrollWheel")<0)
{
Debug.Log("Mousewheel Down");
}

After first launching game in main menu in console I can see it detecting corretly

But after starting game and loading scene its starting to act weird and double registering mouse wheel moving:

And by this bug switching weapon not working corretly (it double switching it, missing one in the middle)
for example i have 3 weapons, from 1 it switches to 3.

Also it spawn 2 explosions on 1 right click (should be 1)

I don't know what is going on, I appreciate every help.


问:
Refresh Enterprise Library Cache After External App Updates It
After searching around for months on and off I finally decided to post this up.

We have an ASP.NET MVC app that uses enterprise library to cache items. We also use a windows service that every so often updates those cached items. Problem is that when the windows service updates the cached items, the mvc website does not see the updated cached items until we reset IIS. We have thought about putting some code in the service to restart the IIS service but think there has got to be a better way. There seems to be one other post that talks about removing items from an external app, but it doesn't go far enough.

We think it has something to do with the in memory version that is local to each instance of the cache manager but simply cannot find a way to bring it all together.

答:
Well, that's pretty much it.  The cache that is being used by the Enterprise Library is in-memory, and the ASP.NET and Windows Service applications both have different memory spaces.  When you update the cache in one, you don't update the cache in the other.

The problem exists in the ASP.NET app as well, but it seems that this is a read-only cache, and you are performing the writes from the service.

What you need to do is create a cache that both app domains can share and there are many ways to do this:

Store the items in a shared persistance store (filesystem, database, etc) that both app domains can access easily

Have a cache service which will handle the updates of the cache items, but which you will query (through WCF, for example) for the cache items

In general, you are looking to perform "distributed caching".  To that end, you should read the article in MSDN Magazine titled "Distributed Caching On The Path To Scalability" for more information on distributed caching options in .NET