问:
Regex match cookie value and remove hyphens
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

```<code>facility=34222%7CConner-Department-Store;
</code>```

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??

答:
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.

This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:

```<code>var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
  return m.replace('-', '');
}).join(" "));
</code>```

Demo:

var str = "facility=34222%7CConner-Department-Store;";

var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
  return m.replace('-', '');
}).join(" "));```

Explanation:

Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.

Replace any - occurence in the matched words.

Then just join these matches array with white space.

Body:
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

facility=34222%7CConner-Department-Store;

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??

Body:
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.

This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:

var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
  return m.replace('-', '');
}).join(" "));

Demo:

var str = "facility=34222%7CConner-Department-Store;";

var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
  return m.replace('-', '');
}).join(" "));

Explanation:

Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.

Replace any - occurence in the matched words.

Then just join these matches array with white space.


来源: stackexchange

问:
Extract category Information from columns, based on similarity to patterns
Suppose I have the following data frame:

```<code>table<-data.frame(col1=c('4.3 automatic version 1', '3.2 manual version 2',
                         '2.3 version 1', '9.0 version 6'),
                  col2=c('ite auto version 2', 'ite version 3', '2.5 manual version 2',
                         'vserion auto 5'))

                     col1                 col2
1 4.3 automatic version 1   ite auto version 2
2    3.2 manual version 2        ite version 3
3           2.3 version 1 2.5 manual version 2
4           9.0 version 6       vserion auto 5
</code>```

I want to add a column with values of only 'automatic' or 'manual', based on the contents of columns 1 and 2. If col1 or col2 includes some word like either 'auto' or 'automatic' then col3 would be 'automatic'.  If col1 or col2 is like 'manual' then col3 would be 'manual', like this:

```<code>                     col1                 col2      col3
1 4.3 automatic version 1   ite auto version 2 automatic
2    3.2 manual version 2        ite version 3    manual
3           2.3 version 1 2.5 manual version 2    manual
4           9.0 version 6       vserion auto 5 automatic
</code>```

答:
I like to keep things flexible.  I also like to keep intermediate data structures.  So there's almost certainly something shorter and more memory efficient than this.

Note that I'm using regular expressions to search with flexibility (based on your use of the words similarity and like).  To demonstrate the effects, I have made some changes to your input data.  I have also added some edge cases.

An alternative approach might use the tm text mining package.  That would give you even more flexibility that this grep solution, at the cost of some additional complexity.

```<code>my.table <-
  data.frame(
    col1 = c(
      '4.3 automatic version 1',
      '3.2 manual version 2',
      '2.3 version 1',
      '9.0 version 6',
      'maybe standard',
      'or neither'
    ),
    col2 = c(
      'ite automated version 2',
      'ite version 3',
      '2.5 manual version 2',
      'vserion auto 5',
      'maybe automatic',
      'for reals'
    )
  )

search.terms <- c("auto|automated|automatic", "manual|standard")
names(search.terms) <- c("automatic", "manual")

term.test <- function(term)  {
  term.pres <- apply(
    my.table,
    MARGIN = 1,
    FUN = function(one.cell) {
      any(grep(pattern = term, x = one.cell))
    }
  )
  return(term.pres)
}

term.presence <- lapply(X = search.terms, term.test)

term.presence <- do.call(cbind.data.frame, term.presence)

names(term.presence) <- names(search.terms)

as.labels <- lapply(names(search.terms), function(one.term) {
  tempcol <- tempflag <- term.presence[, one.term]
  tempcol <- rep('', length(tempflag))
  tempcol[tempflag] <- one.term
  return(tempcol)
})

as.labels <- do.call(cbind.data.frame, as.labels)
names(as.labels) <- search.terms

labels.concat <-
  apply(
    as.labels,
    MARGIN = 1,
    FUN = function(one.row) {
      temp <- unique(sort(one.row))
      temp <- temp[nchar(temp) > 0]
      temp <- paste(temp, sep = ", ", collapse = "; ")
      return(temp)
    }
  )

my.table$col3 <- labels.concat

print(my.table)
</code>```

which gives

```<code>                     col1                    col2              col3
1 4.3 automatic version 1 ite automated version 2         automatic
2    3.2 manual version 2           ite version 3            manual
3           2.3 version 1    2.5 manual version 2            manual
4           9.0 version 6          vserion auto 5         automatic
5          maybe standard         maybe automatic automatic; manual
6              or neither               for reals
>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have the following data frame:

table<-data.frame(col1=c('4.3 automatic version 1', '3.2 manual version 2',
                         '2.3 version 1', '9.0 version 6'),
                  col2=c('ite auto version 2', 'ite version 3', '2.5 manual version 2',
                         'vserion auto 5'))

                     col1                 col2
1 4.3 automatic version 1   ite auto version 2
2    3.2 manual version 2        ite version 3
3           2.3 version 1 2.5 manual version 2
4           9.0 version 6       vserion auto 5

I want to add a column with values of only 'automatic' or 'manual', based on the contents of columns 1 and 2. If col1 or col2 includes some word like either 'auto' or 'automatic' then col3 would be 'automatic'.  If col1 or col2 is like 'manual' then col3 would be 'manual', like this:

                     col1                 col2      col3
1 4.3 automatic version 1   ite auto version 2 automatic
2    3.2 manual version 2        ite version 3    manual
3           2.3 version 1 2.5 manual version 2    manual
4           9.0 version 6       vserion auto 5 automatic

Body:
I like to keep things flexible.  I also like to keep intermediate data structures.  So there's almost certainly something shorter and more memory efficient than this.

Note that I'm using regular expressions to search with flexibility (based on your use of the words similarity and like).  To demonstrate the effects, I have made some changes to your input data.  I have also added some edge cases.

An alternative approach might use the tm text mining package.  That would give you even more flexibility that this grep solution, at the cost of some additional complexity.

my.table <-
  data.frame(
    col1 = c(
      '4.3 automatic version 1',
      '3.2 manual version 2',
      '2.3 version 1',
      '9.0 version 6',
      'maybe standard',
      'or neither'
    ),
    col2 = c(
      'ite automated version 2',
      'ite version 3',
      '2.5 manual version 2',
      'vserion auto 5',
      'maybe automatic',
      'for reals'
    )
  )

search.terms <- c("auto|automated|automatic", "manual|standard")
names(search.terms) <- c("automatic", "manual")

term.test <- function(term)  {
  term.pres <- apply(
    my.table,
    MARGIN = 1,
    FUN = function(one.cell) {
      any(grep(pattern = term, x = one.cell))
    }
  )
  return(term.pres)
}

term.presence <- lapply(X = search.terms, term.test)

term.presence <- do.call(cbind.data.frame, term.presence)

names(term.presence) <- names(search.terms)

as.labels <- lapply(names(search.terms), function(one.term) {
  tempcol <- tempflag <- term.presence[, one.term]
  tempcol <- rep('', length(tempflag))
  tempcol[tempflag] <- one.term
  return(tempcol)
})

as.labels <- do.call(cbind.data.frame, as.labels)
names(as.labels) <- search.terms

labels.concat <-
  apply(
    as.labels,
    MARGIN = 1,
    FUN = function(one.row) {
      temp <- unique(sort(one.row))
      temp <- temp[nchar(temp) > 0]
      temp <- paste(temp, sep = ", ", collapse = "; ")
      return(temp)
    }
  )

my.table$col3 <- labels.concat

print(my.table)

which gives

                     col1                    col2              col3
1 4.3 automatic version 1 ite automated version 2         automatic
2    3.2 manual version 2           ite version 3            manual
3           2.3 version 1    2.5 manual version 2            manual
4           9.0 version 6          vserion auto 5         automatic
5          maybe standard         maybe automatic automatic; manual
6              or neither               for reals
>


问:
HLS implementation with FFmpeg
I am trying to implement HLS using FFmpeg for transcoding + segmenting but have been facing a couple of issues that have been bugging me for the past week.

Issue

Webserver currently receives live MP4 fragments being recorded on-the-go and needs to take care of transcoding and segmentation.

As mp4 fragments are being received, they need to be encoded. Then segmented. If i run a segmenter (be it ffmpeg or apple mediastreamsegmenter), every mp4 fragment is being treated as a VOD by itself and I'm not being able to integrate them as part of a larger live event implementation.

I thought of a solution where every time I receive an mp4 fragment, I first use fmpeg to concatenate it with previous ones to form the larger mp4 that I then pass to be segmented for HLS. That did not work either because the entire stream has to be re-segmented each and every time and existing TS fragments replaced by new ones that are similar yet shifted in time.

Implementation 1

ffmpeg -re -i fragmentX.mp4 -b:v 118k -b:a 32k -vcodec copy -preset:v veryfast -acodec aac -strict -2 -ac 2 -f mpegts -y fragmentX.ts

I manage the m3u8 manifest on my own, deleting old fragments and appending new ones.

When validating the stream, I find it stacked with EXT-X-DISCONTINUITY tags making the stream unwatchable.

Implementation 2

First combine latest fragment with overall.mp4

ffmpeg -i "concat:newfragment.mp4|existing.mp4" -c copy overall.mp4

Then pass the combination to ffmpeg for HLS segmentation

ffmpeg -re -i overall.mp4 -ac 2 -r 20 -vcodec libx264 -b:v 318k -preset:v veryfast -acodec aac -strict -2 -b:a 32k -hls_time 2 -hls_list_size 3 -hls_allow_cache 0 -hls_base_url /Users/JosephKalash/Desktop/test/350/ -hls_segment_filename '350/fragment%03d.ts' -hls_flags delete_segments 350/index.m3u8

Concatenation is not perfect and there are noticeable glitches where the fragments are supposed to be stitched. Segmentation replaces older fragments and the manifest is rewritten as if it's a new HLS stream every time ffmpeg is called.

I cannot figure out how to get this to work properly.

Any ideas?

答: Solved by relying on nginx rtmp module which turned out to be suited for the above implementation.</p>

Title: HLS implementation with FFmpeg


问:
Class has no instance of setter '_scheduler'
I have a class which has a ViewChild _scheduler.  Im not really sure why it needs a setter though since i am only wanting to use it to get the markup related to it.  I am having some issues reading the error code since it isnt quite relating back to my files entirely as it is tracing X.template.dart so i cant quite see which line the issues are on.

I was looking at the html file, but it is actually just pointing to the closing tag to the Div.

答: Don't use a private name for the ViewChild. In the generated code it is trying to set the ViewChild _scheduler on an instance of the component, but since it's private, the setter call is failing. It should work if you rename it to scheduler.


问:
Generate Description Fields for Body Parameters
So I've been Googling a lot to try and solve this problem but I can't seem to find anything on it. See picture for reference, but I'm trying to fill in the Description field for the body parameters. What is the best way to do this?

答:
I found the answers here confusing so here is my complete solution.

First turn on XMLDocumentation by going to Areas -> HelpPage -> App_Start -> HelpPageConfig.cs and uncommenting out the following two lines.

```<code>// Uncomment the following to use the documentation from XML documentation file.
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
</code>```

Then for the method that you want to provide documentation for create an xml comment in the following format. This is usually autocompleted for me but I have resharper turned on so that may not be the default.

```<code>    /// <summary>
    /// An example method description
    /// </summary>
    /// <param name="id">An example parameter description</param>
    /// <returns>An example return value description</returns>
    // GET: api/Products/5
    public string Get(int id)
    {
        return "value";
    }
</code>```

If you run the app and go to your api help page, the documentation should be visible.

Body:
I found the answers here confusing so here is my complete solution.

First turn on XMLDocumentation by going to Areas -> HelpPage -> App_Start -> HelpPageConfig.cs and uncommenting out the following two lines.

// Uncomment the following to use the documentation from XML documentation file.
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

Then for the method that you want to provide documentation for create an xml comment in the following format. This is usually autocompleted for me but I have resharper turned on so that may not be the default.

    /// <summary>
    /// An example method description
    /// </summary>
    /// <param name="id">An example parameter description</param>
    /// <returns>An example return value description</returns>
    // GET: api/Products/5
    public string Get(int id)
    {
        return "value";
    }

If you run the app and go to your api help page, the documentation should be visible.


问:
Does filter() work in-place in python?
If I call filter() on a list, say:

```<code>>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]
</code>```

Is this:

a) creating a totally new list in memory with the results

or

b) is it just pop()-ing items from the existing list and returning the same list?

答:
Filter returns a new list containing elements of the expression that satisfy the given conditions.  The original list is intact.  In your case, it doesn't really matter, because your list is an in-place constant -- but I assume that you have a more general application in mind.

See the documentation: it states that filter constructs a new iterable (list, tuple, ...).

Title: Does filter() work in-place in python?

Body:
If I call filter() on a list, say:

>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]

Is this:

a) creating a totally new list in memory with the results

or

b) is it just pop()-ing items from the existing list and returning the same list?


问:
Exploitation of GPU using Halide
I'm implementing an algorithm using Halide while comparing hand-tuned(using CUDA) version of same algorithm.
Acceleration of the Halide implementation mostly went well, but still slower a bit than hand-tuned version. So I tried to see exact execution time of each Func using nvvp(nvidia visual profiler). By doing that, I figured out that hand-tuned implementation overlaps multiple function's(they're similar) execution which is implemented as a Func in Halide implemetation. Cuda's Stream technology is used to do it.

I would like to know whether I can do similar exploitation of GPU in Halide or not.

I appreciate for reading.

答:
Currently the runtime has no support for CUDA streams. It might be possible to replace the runtime with something that can do this, but there is no extra information passed in to control the concurrency. (The runtime is somewhat designed to be replaceable, but there is a bit of a notion of a single queue and full dependency information is not passed down. It may be possible to reconstruct the dependencies from the inputs and outputs, but that starts to be a lot of work to solve a problem the compiler should be solving itself.)

We're talking about how to express such control in the schedule. One possibility is to use the support being prototyped in the async branch to do this, but we haven't totally figured out how to apply this to GPUs. (The basic idea is scheduling a Func async on a GPU would put it on a different stream. We'd need to use GPU synchronization APIs to handle producer/consumer dependencies.) Ultimately this is something we are interested in exploiting, but work needs to be done.

Title: Exploitation of GPU using Halide


问:
behavior of html control in ASP.NET
Let's say I have a html input box:

```<code> <form id="form1" runat="server">
    <div>
        <input id="Text1" type="text"/>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
    </div>
</form>
</code>```

If I type something like "My Subjects" into the input, and click the button, the text in the input box will disappear, here is something I don't quite understand:

This is a post request, since "My Subjects" will be submitted to the server, so when the server render the html, it should add the text to the input textbox and then send the html document back to the browser, is my understanding incorrect?

答:
ASP.NET WebForms only adds the "postback magic" to HTML elements if they have the runat="server" attribute applied, otherwise they're treated as static plain text.

Add runat="server" and it will work:

```<code><input id="Text1" type="text" runat="server" />
</code>```

Title: behavior of html control in ASP.NET

Body:
Let's say I have a html input box:

 <form id="form1" runat="server">

        <input id="Text1" type="text"/>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>

</form>

If I type something like "My Subjects" into the input, and click the button, the text in the input box will disappear, here is something I don't quite understand:

This is a post request, since "My Subjects" will be submitted to the server, so when the server render the html, it should add the text to the input textbox and then send the html document back to the browser, is my understanding incorrect?

Body:
ASP.NET WebForms only adds the "postback magic" to HTML elements if they have the runat="server" attribute applied, otherwise they're treated as static plain text.

Add runat="server" and it will work:

<input id="Text1" type="text" runat="server" />


答: Filter is acting on a iterable and creates a new interable.</p>

Title: Does filter() work in-place in python?


问:
How to find records that don't have a value in SQL Server 2014?
I have a table 'FinTrans' that has data that looks like this:

```<code>---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------
</code>```

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

```<code>SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode
</code>```

答:
You can do this with group by and having:

```<code>SELECT A.AccountNumber
FROM FinTrans F INNER JOIN
     Account A
     ON F.AcctID = A.AccountID
WHERE TransCode IN ('PYMT', 'TOLL')
GROUP BY A.AccountNumber
HAVING SUM(CASE WHEN TransCode = 'PYMT' THEN 1 ELSE 0 END) = 0;
</code>```

Do you really need the other columns in your sample SQL?  They are not relevant to your question.

You can also do this with EXISTS/NOT EXISTS:

```<code>select a.*
from account a
where exists (select 1
              from FinTrans f
              where f.AcctID = a.AccountID and f.TransCode = 'TOLL'
             ) and
      not exists (select 1
                  from FinTrans f
                  where f.AcctID = a.AccountID and f.TransCode = 'PYMT'
                 );
</code>```

This has the performance advantage that no aggregation is necessary.

Body:
I have a table 'FinTrans' that has data that looks like this:

---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode

Body:
You can do this with group by and having:

SELECT A.AccountNumber
FROM FinTrans F INNER JOIN
     Account A
     ON F.AcctID = A.AccountID
WHERE TransCode IN ('PYMT', 'TOLL')
GROUP BY A.AccountNumber
HAVING SUM(CASE WHEN TransCode = 'PYMT' THEN 1 ELSE 0 END) = 0;

Do you really need the other columns in your sample SQL?  They are not relevant to your question.

You can also do this with EXISTS/NOT EXISTS:

select a.*
from account a
where exists (select 1
              from FinTrans f
              where f.AcctID = a.AccountID and f.TransCode = 'TOLL'
             ) and
      not exists (select 1
                  from FinTrans f
                  where f.AcctID = a.AccountID and f.TransCode = 'PYMT'
                 );

This has the performance advantage that no aggregation is necessary.


问:
Docker run command failing when trying to install the mysql php extension
I have a docker php container that I need to connect to a mysql container, in order to do so I use the following docker file to construct the appropriate image:

```<code>FROM php:7-fpm
ADD /build /build
ADD /config /config
RUN docker-php-ext-install mysqli
</code>```

I have written a python script to automate the process of building and running my containers, in particular it executes these functions to build the php container image:

```<code>import docker
client = docker.from_env()
php_image = client.images.build(path="./php-docker/",tag="bjaniston/php-container",rm=True)
</code>```

Up until recently this was working absolutely fine, but has now started failing with the following error:

```<code>Traceback (most recent call last):
  File "docker_setup.py", line 3, in <module>
    php_image = client.images.build(path="./php-docker/",tag="bjaniston/php-container",rm=True)
  File "/usr/local/lib/python3.4/dist-packages/docker/models/images.py", line 172, in build
    raise BuildError(chunk['error'])
docker.errors.BuildError: The command '/bin/sh -c docker-php-ext-install mysqli' returned a non-zero code: 2
</code>```

I am not sure what would cause this error, I have not modified the docker file since the last time this image was successfully built.

答:
After running the build command manually in the terminal docker gave a different error saying that the device had run out of space, having browsed the docker forums to decipher the error I stumbled across this page:
https://forums.docker.com/t/where-does-docker-keep-images-containers-so-i-can-better-track-my-disk-usage/8370/9

Running the shell command below solved my problem (bear in mind this removes all named volumes from the host):

```<code>docker volume rm $(docker volume ls -q )
</code>```

The original error from the docker python API seemed very opaque, and gave little idea of the cause of the problem.

Body:
I have a docker php container that I need to connect to a mysql container, in order to do so I use the following docker file to construct the appropriate image:

FROM php:7-fpm
ADD /build /build
ADD /config /config
RUN docker-php-ext-install mysqli

I have written a python script to automate the process of building and running my containers, in particular it executes these functions to build the php container image:

import docker
client = docker.from_env()
php_image = client.images.build(path="./php-docker/",tag="bjaniston/php-container",rm=True)

Up until recently this was working absolutely fine, but has now started failing with the following error:

Traceback (most recent call last):
  File "docker_setup.py", line 3, in <module>
    php_image = client.images.build(path="./php-docker/",tag="bjaniston/php-container",rm=True)
  File "/usr/local/lib/python3.4/dist-packages/docker/models/images.py", line 172, in build
    raise BuildError(chunk['error'])
docker.errors.BuildError: The command '/bin/sh -c docker-php-ext-install mysqli' returned a non-zero code: 2

I am not sure what would cause this error, I have not modified the docker file since the last time this image was successfully built.

Body:
After running the build command manually in the terminal docker gave a different error saying that the device had run out of space, having browsed the docker forums to decipher the error I stumbled across this page:
https://forums.docker.com/t/where-does-docker-keep-images-containers-so-i-can-better-track-my-disk-usage/8370/9

Running the shell command below solved my problem (bear in mind this removes all named volumes from the host):

docker volume rm $(docker volume ls -q )

The original error from the docker python API seemed very opaque, and gave little idea of the cause of the problem.


问:
Terraform - resource repeated multiple times
I have a terraform plan which consists of multiple aws_sqs_queue resources which more of less share the same config. Before I remove any repeating configs and use variables I wanted to run terraform plan to see if it works. However I keep running into -

```<code>module root: 1 error(s) occurred:

* data.template_file.ep_match_result_queues: resource repeated multiple times
</code>```

Ive tried googling but there is not much information available. Any help will be much appreciated. My plan looks like this: (ignore extra braces, typos as this is just a skeleton to give you a general idea how the plan is sturctured):

```<code>data "template_file" "ep_match_result_queues" {
  template = "${var.namespace}-sm-ep"
}

resource "aws_sns_topic" "sns_topic_name" {
  name            = "ep_sm_match_result_topic${var.environment}"
  display_name    = ""
  policy          = <<POLICY
{
 #policy
}

resource "aws_sqs_queue" "queue1" {
 #config
}

resource "aws_sqs_queue" "queue2" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue3" {
#config
}

resource "aws_sqs_queue" "queue4" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue5" {
 #config
}

resource "aws_sqs_queue" "queue6" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue7" {
 #config
}

resource "aws_sqs_queue" "queue8" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue_policy" "queue_policy" {
  queue_url = [ ... ]
  policy    = "${data.aws_iam_policy_document.match_result_queues_policy.json}"
}

data "aws_iam_policy_document" "match_result_queues_policy" {
 #policy
}
</code>```

答:
You can use a variable to specify how many you want and then add that to the name of the Queue.

```<code>resource "aws_sqs_queue" "terraform_queue" {
  count  = "${var.queue_count}"
  name                      = "terraform-example-queue-${count.index}"
  delay_seconds             = 90
  max_message_size          = 2048
  message_retention_seconds = 86400
  receive_wait_time_seconds = 10
  redrive_policy            = "{\"deadLetterTargetArn\":\"${aws_sqs_queue.terraform_queue_deadletter.arn}\",\"maxReceiveCount\":4}"
}
</code>```

https://www.terraform.io/intro/examples/count.html

Body:
I have a terraform plan which consists of multiple aws_sqs_queue resources which more of less share the same config. Before I remove any repeating configs and use variables I wanted to run terraform plan to see if it works. However I keep running into -

module root: 1 error(s) occurred:

* data.template_file.ep_match_result_queues: resource repeated multiple times

Ive tried googling but there is not much information available. Any help will be much appreciated. My plan looks like this: (ignore extra braces, typos as this is just a skeleton to give you a general idea how the plan is sturctured):

data "template_file" "ep_match_result_queues" {
  template = "${var.namespace}-sm-ep"
}

resource "aws_sns_topic" "sns_topic_name" {
  name            = "ep_sm_match_result_topic${var.environment}"
  display_name    = ""
  policy          = <<POLICY
{
 #policy
}

resource "aws_sqs_queue" "queue1" {
 #config
}

resource "aws_sqs_queue" "queue2" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue3" {
#config
}

resource "aws_sqs_queue" "queue4" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue5" {
 #config
}

resource "aws_sqs_queue" "queue6" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue7" {
 #config
}

resource "aws_sqs_queue" "queue8" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue_policy" "queue_policy" {
  queue_url = [ ... ]
  policy    = "${data.aws_iam_policy_document.match_result_queues_policy.json}"
}

data "aws_iam_policy_document" "match_result_queues_policy" {
 #policy
}

Body:
You can use a variable to specify how many you want and then add that to the name of the Queue.

resource "aws_sqs_queue" "terraform_queue" {
  count  = "${var.queue_count}"
  name                      = "terraform-example-queue-${count.index}"
  delay_seconds             = 90
  max_message_size          = 2048
  message_retention_seconds = 86400
  receive_wait_time_seconds = 10
  redrive_policy            = "{\"deadLetterTargetArn\":\"${aws_sqs_queue.terraform_queue_deadletter.arn}\",\"maxReceiveCount\":4}"
}

https://www.terraform.io/intro/examples/count.html


问:
Mapbox Methods Not Recognized by Android Studio
Getting a bit lost here: I need to update Mapbox's API from 4.x.x-beta to 5.x.x and a number of things, such as xml attributes' names, way of getting access token and location services has been changed. I dealt with the first two thanks to the documentation but cannot seem to make LocationServices methods work. Android Studio tells me that it cannot resolve methods such as getLocationServices() or getLastLocation(). Here's what my code looks like, that's what used to work with Mapbox 4.x:

```<code>package com.example.myapp.interactor;

import android.location.Location;

import com.mapbox.mapboxsdk.location.LocationServices;

import com.example.myapp.MyApp;

public class GpsInteractor {

    private LocationServices locationServices;

    public GpsInteractor() {
        locationServices = LocationServices.getLocationServices(MyApp.applicationContext());
    }

    public Location lastKnownLocation() {
        return locationServices.getLastLocation();
    }
}
</code>```

So, as per documentation here ("Getting Location Updates" section), I should copy LostLocationEngine class to my project. When I did so, it cannot access some of the fields from LocationRequest.java LOST API class, namely interval, fastestInterval and smallestDisplacement.
I found this question with really similar problem and tried to compile several combinations of Mapbox APIs, but no luck.

Am I missing something?

答:
If you haven't modified the maps locationSource yet,
LocationEngine locationEngine = LocationSource.getLocationEngine(this) will return the default LOST location engine being used. Starting in 5.0.0 LocationEngine replaces the LocationServices class. For example, to get the last known user location, you can do this:

```<code>LocationEngine locationEngine = LocationSource.getLocationEngine(this)
locationEngine.getLastLocation();
</code>```

You can read more on the LocationEngine in the new documentation here.

Body:
Getting a bit lost here: I need to update Mapbox's API from 4.x.x-beta to 5.x.x and a number of things, such as xml attributes' names, way of getting access token and location services has been changed. I dealt with the first two thanks to the documentation but cannot seem to make LocationServices methods work. Android Studio tells me that it cannot resolve methods such as getLocationServices() or getLastLocation(). Here's what my code looks like, that's what used to work with Mapbox 4.x:

package com.example.myapp.interactor;

import android.location.Location;

import com.mapbox.mapboxsdk.location.LocationServices;

import com.example.myapp.MyApp;

public class GpsInteractor {

    private LocationServices locationServices;

    public GpsInteractor() {
        locationServices = LocationServices.getLocationServices(MyApp.applicationContext());
    }

    public Location lastKnownLocation() {
        return locationServices.getLastLocation();
    }
}

So, as per documentation here ("Getting Location Updates" section), I should copy LostLocationEngine class to my project. When I did so, it cannot access some of the fields from LocationRequest.java LOST API class, namely interval, fastestInterval and smallestDisplacement.
I found this question with really similar problem and tried to compile several combinations of Mapbox APIs, but no luck.

Am I missing something?

Body:
If you haven't modified the maps locationSource yet,
LocationEngine locationEngine = LocationSource.getLocationEngine(this) will return the default LOST location engine being used. Starting in 5.0.0 LocationEngine replaces the LocationServices class. For example, to get the last known user location, you can do this:

LocationEngine locationEngine = LocationSource.getLocationEngine(this)
locationEngine.getLastLocation();

You can read more on the LocationEngine in the new documentation here.


答:
is my understanding incorrect?

No, I'm afraid not.  There is no mechanism by which this behavior would be automatic.  You would have to write code or use some tool which does this.  The ASP.NET Framework has code internally which does this for server controls, which are ones with runat="server".  (See things like ViewState, and take a look at the hidden fields that ASP.NET automatically adds to your page.)

If you want to populate your page with values included in the request, you would do so in the code for that page.  To do this, first you need to give the input a name so it's included in the POST:

```<code><input id="Text1" type="text" name="Text1"/>
</code>```

Then you can find the value server-side in the POST request with something like:

```<code>Request.Form["Text1"]
</code>```

From there you can put it on the page in a variety of ways, just like any other value in your class that you want to put on the page.

Title: behavior of html control in ASP.NET

Body:
is my understanding incorrect?

No, I'm afraid not.  There is no mechanism by which this behavior would be automatic.  You would have to write code or use some tool which does this.  The ASP.NET Framework has code internally which does this for server controls, which are ones with runat="server".  (See things like ViewState, and take a look at the hidden fields that ASP.NET automatically adds to your page.)

If you want to populate your page with values included in the request, you would do so in the code for that page.  To do this, first you need to give the input a name so it's included in the POST:

<input id="Text1" type="text" name="Text1"/>

Then you can find the value server-side in the POST request with something like:

Request.Form["Text1"]

From there you can put it on the page in a variety of ways, just like any other value in your class that you want to put on the page.


问:
Convert a list of list of objects to string
I've a list of list of objects like List<List<Event>>.

How can I override ToString() such that each internal list will be shown in a single line of command prompt?

```<code>public override string ToString(List<List<Event>>)
{
     return ?
}
</code>```

答:
```<code>public override string ToString(List<List<Event>> lle)
{
    StringBuilder res=new Stringbuilder(your_guess_of_lenght_here);
    foreach(List<Event> le in lle){
        foreach(Event e in le){
            res.Append(e+"any_separator_of_elements");
        }
        res.Append("\n");
    }
    return res.ToString();
}
</code>```

Something like this? I don't know your event string representation, you may want to change that.

Body:
I've a list of list of objects like List<List<Event>>.

How can I override ToString() such that each internal list will be shown in a single line of command prompt?

public override string ToString(List<List<Event>>)
{
     return ?
}

Body:
public override string ToString(List<List<Event>> lle)
{
    StringBuilder res=new Stringbuilder(your_guess_of_lenght_here);
    foreach(List<Event> le in lle){
        foreach(Event e in le){
            res.Append(e+"any_separator_of_elements");
        }
        res.Append("\n");
    }
    return res.ToString();
}

Something like this? I don't know your event string representation, you may want to change that.


Title: Does filter() work in-place in python?

Body:
>>> a = [1,2,3,4]
>>> list(filter(lambda x: x > 1, a))
[2, 3, 4]
>>> a
[1, 2, 3, 4]


问:
why is ok to chain jquery effects, instead of using callbacks
In the jquery documentation is stated that if you want to add a class after an effect is applied on a selection you must use a callback:

```<code>// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});
</code>```

However, you can chain two effects without needing to use a callback:

```<code>$(".something").fadeOut().fadeIn();
</code>```

Why is that? shouldn't you have to use a callback like this, too:

```<code>$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});
</code>```

答: Callbacks make sense for asynchronous operations. So the callback is if you want something to happen after the fading is complete. In your case, the subsequent chained .addClass() does not wait for the fading to be complete. It happens right away.

Body:
In the jquery documentation is stated that if you want to add a class after an effect is applied on a selection you must use a callback:

// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});

However, you can chain two effects without needing to use a callback:

$(".something").fadeOut().fadeIn();

Why is that? shouldn't you have to use a callback like this, too:

$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});


问:
Why wont Mozilla Firefox support third party fonts on my Website?
I have a TTF (True Type Font) which I have used correctly, as it shows up in Safari and Chrome. Is there a way to enable third party fonts on Firefox, or a MAC friendly file extension which is universal across all internet browsers?

I read up about it, and people suggested WOFF files, but they are an executable file on MAC, and Font Book wont open these files. I'm not particularly interested in downloading a third party program to install this third party font.

(In case you are wondering, or it helps, the font is "Top Secret". It's like an ARMY font)

答:
You clarified in a comment that you open your web page from local disk (so, with "file://" URL).

Firefox does not support loading web fonts from local disk, by design.

It will work when moved to server and if that server has the proper configuration to serve appropriate content-type header for font files, as explained here (please note I did not suggest to use woff, I'm just saying it's the same problem for woff and ttf), here and here.


问:
Replace text with regexp
I have to replace text this way:

```<code>Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]
</code>```

And replace that with:

```<code>Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png
</code>```

I tried with re.sub method from python:

```<code>for foo in re.search('(\[image=(.*)\])', text):
   text = re.sub("(?<=\[image=)*(?=\])", foo, text)
</code>```

But that won't work, why?

答:
Seriously, did you read regex documentation or at least the howto?

.search() returns a match object. You can't iterate over it.

.sub() replaces all occurrences in the string at once. You can't replace one by one.

One idea:

```<code>import re

text = """Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]"""

text = re.sub(r'\[image\=([^\]]+)\]', r'\1', text)

print text
</code>```

the results:

```<code>Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png
</code>```

ContentLicense: CC BY-SA 2.5

Title: Replace text with regexp

Body:
I have to replace text this way:

Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]

And replace that with:

Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png

I tried with re.sub method from python:

for foo in re.search('(\[image=(.*)\])', text):
   text = re.sub("(?<=\[image=)*(?=\])", foo, text)

But that won't work, why?

Body:
Seriously, did you read regex documentation or at least the howto?

.search() returns a match object. You can't iterate over it.

.sub() replaces all occurrences in the string at once. You can't replace one by one.

One idea:

import re

text = """Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]"""

text = re.sub(r'\[image\=([^\]]+)\]', r'\1', text)

print text

the results:

Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png


答: From my understanding, when you perform an operation like fadeIn/fadeOut what you are doing is creating a request that gets placed on an internal animation queue, which performs the actions in a FIFO manner.  Others can detail this more, but as it works like this it doesn't require the use of callbacks.</p>

Title: why is ok to chain jquery effects, instead of using callbacks


问:
COUNT after join and group by in PIG
I'm new in pig and trying understand why I can not count after join and group by:

```<code>A = LOAD 'mary' as (line);
B = LOAD 'mary' as (line);

wordsA = foreach A generate flatten(TOKENIZE(line)) as wordA;
grpdA = group wordsA by wordA;
cntdA = foreach grpdA generate group, COUNT(wordsA);

wordsB = foreach B generate flatten(TOKENIZE(line)) as wordB;
grpdB = group wordsB by wordB;
cntdB = foreach grpdB generate group, COUNT(wordsB), 'some text';

fltB = FILTER cntdB BY $1>1;

jnd = join cntdA by $1, fltB by $1;
jnd_n = foreach jnd generate $0;
grp = group jnd by $0;
out = foreach grp generate group, count(jnd_n);

dump jnd_n;
dump grp;
</code>```

dump jnd_n:

```<code>(was)
(was)
(was)
(lamb)
(lamb)
(lamb)
(Mary)
(Mary)
(Mary)
</code>```

dump grp:

```<code>(was,{(was,2,was,2,some text),(was,2,Mary,2,some text),(was,2,lamb,2,some text)})
(Mary,{(Mary,2,was,2,some text),(Mary,2,Mary,2,some text),(Mary,2,lamb,2,some text)})
(lamb,{(lamb,2,was,2,some text),(lamb,2,Mary,2,some text),(lamb,2,lamb,2,some text)})
</code>```

But I'm getting error:

Invalid scalar projection: jnd_n : A column needs to be projected from
  a relation for it to be used as a scalar

If I try to change code:

```<code>out = foreach grp generate group, count(jnd_n.$0);
</code>```

Then I'm getting another error:

Failed to generate logical plan. Nested exception:
  org.apache.pig.backend.executionengine.ExecException: ERROR 1070:
  Could not resolve count using imports: [, java.lang.,
  org.apache.pig.builtin., org.apache.pig.impl.builtin.]

I know that I can do it another way, but I want to get result like this after exactly after doing two pig operations JOIN and GROUP BY:

dump out:

```<code>(was,3)
(lamb,3)
(Mary,3)
</code>```

答:
COUNT needs to be in caps.  COUNT is a keyword.

```<code>out = foreach grp generate group, COUNT(jnd_n.$0);`
</code>```

Title: COUNT after join and group by in PIG

Body:
I'm new in pig and trying understand why I can not count after join and group by:

A = LOAD 'mary' as (line);
B = LOAD 'mary' as (line);

wordsA = foreach A generate flatten(TOKENIZE(line)) as wordA;
grpdA = group wordsA by wordA;
cntdA = foreach grpdA generate group, COUNT(wordsA);

wordsB = foreach B generate flatten(TOKENIZE(line)) as wordB;
grpdB = group wordsB by wordB;
cntdB = foreach grpdB generate group, COUNT(wordsB), 'some text';

fltB = FILTER cntdB BY $1>1;

jnd = join cntdA by $1, fltB by $1;
jnd_n = foreach jnd generate $0;
grp = group jnd by $0;
out = foreach grp generate group, count(jnd_n);

dump jnd_n;
dump grp;

dump jnd_n:

(was)
(was)
(was)
(lamb)
(lamb)
(lamb)
(Mary)
(Mary)
(Mary)

dump grp:

(was,{(was,2,was,2,some text),(was,2,Mary,2,some text),(was,2,lamb,2,some text)})
(Mary,{(Mary,2,was,2,some text),(Mary,2,Mary,2,some text),(Mary,2,lamb,2,some text)})
(lamb,{(lamb,2,was,2,some text),(lamb,2,Mary,2,some text),(lamb,2,lamb,2,some text)})

But I'm getting error:

Invalid scalar projection: jnd_n : A column needs to be projected from
  a relation for it to be used as a scalar

If I try to change code:

out = foreach grp generate group, count(jnd_n.$0);

Then I'm getting another error:

Failed to generate logical plan. Nested exception:
  org.apache.pig.backend.executionengine.ExecException: ERROR 1070:
  Could not resolve count using imports: [, java.lang.,
  org.apache.pig.builtin., org.apache.pig.impl.builtin.]

I know that I can do it another way, but I want to get result like this after exactly after doing two pig operations JOIN and GROUP BY:

dump out:

(was,3)
(lamb,3)
(Mary,3)

Body:
COUNT needs to be in caps.  COUNT is a keyword.

out = foreach grp generate group, COUNT(jnd_n.$0);`


问:
read csv file one to many relationship
I have 2 csv files, one looks like this:

```<code>summary, key, pID, Name, ID
xsajssad, abc123, 1234, p1, 12345678
yasdnalskdj, babc123, 234, p1, 312345678
zsadkmas, cabc123, 3234, p1, 212345678
</code>```

My other csv file looks like this:

```<code>link
file://doc/312345678/document1.doc
file://doc/312345678/document2.doc
file://doc/12345678/document3.doc
file://soc/12345678/document1.doc
file://doc/12345678/document2.doc
file://doc/212345678/document112983.doc
</code>```

What I want is to alter my first csv files are placed to the corressponding ID. The ID is embedded in the file link needs to map back to the unique ID in file 1. This is a one to many relationship, but I want to create a new row to match however many matches there are in the first file.

```<code>summary, key, projectID, projectName, ID, link
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document3.doc
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document1.doc
xsajssad, abc123, 1234, p1, 12345678, file://dpc/12345678/document2.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document1.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document2.doc
zsadkmas, cabc123, 3234, p1, 212345678, file://doc/212345678/document112983.doc
</code>```

What is the most efficient way to do this?

答:
First read the filepath cvs file, and save into memory, and close the read (call this data set 1).

Then read the other cvs file, doing the same thing (data set 2).

Then, loop through data set 1, and for each id, select the data from data set 2, and insert into a new file.

when the loop through data set 1 is complete.  delete original file, and rename the new file - which, from a users perspective will look as though you simply modified it.

This is a simpler way to do things than modification, because inserting and modifying rows requires more logic than is necessary.

Title: read csv file one to many relationship

Body:
I have 2 csv files, one looks like this:

summary, key, pID, Name, ID
xsajssad, abc123, 1234, p1, 12345678
yasdnalskdj, babc123, 234, p1, 312345678
zsadkmas, cabc123, 3234, p1, 212345678

My other csv file looks like this:

link
file://doc/312345678/document1.doc
file://doc/312345678/document2.doc
file://doc/12345678/document3.doc
file://soc/12345678/document1.doc
file://doc/12345678/document2.doc
file://doc/212345678/document112983.doc

What I want is to alter my first csv files are placed to the corressponding ID. The ID is embedded in the file link needs to map back to the unique ID in file 1. This is a one to many relationship, but I want to create a new row to match however many matches there are in the first file.

summary, key, projectID, projectName, ID, link
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document3.doc
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document1.doc
xsajssad, abc123, 1234, p1, 12345678, file://dpc/12345678/document2.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document1.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document2.doc
zsadkmas, cabc123, 3234, p1, 212345678, file://doc/212345678/document112983.doc

What is the most efficient way to do this?


问:
PBKDF2 - What happens when generating 1024 bits key length with SHA512?
I have this code snippet to generate key with PBKDF2.

```<code>SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, length);
        SecretKey key = skf.generateSecret(spec);
        byte[] res = key.getEncoded();
</code>```

I am wondering how generating works when a key lengthis longer than specified SHA digest algorithm type?

For example - what happens when I set a key length of 1024 bits and use PBKDF2WithHmacSHA512 algorithm? Where are 512 bits generated?

答:
In general it is not advised to ask for more than the hash length as each block is run through all the iterations again:

According to Wikipedia (which has a somewhat more readable format than PKCS#5):

```<code>DK = T1 || T2 || ... || Tdklen/hlen
Ti = F(Password, Salt, c, i)
</code>```

here c is the iteration count by the way.

The problem with this is that generally large amounts of key material are only used when the result is split into multiple components. And if an attacker can verify a good password guess using only - say - the first 128 bits then the attacker has to do less work than the legitimate user of the algorithm.

One way of resolving this is to split the output of PBKDF2 using a KBKDF such as HKDF using different labels (information that is also hashed). That way you can generate almost infinite amount of key material without running through all the iterations for each 512 bits.

Note that 512 bits is enough for two very secure AES-256 bit keys. So that's one very good reason to use SHA-512 for PBKDF2. Note that on 64 bit machines SHA-512 may be faster than SHA-256 while delivering more output material and security.

Body:
I have this code snippet to generate key with PBKDF2.

SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, length);
        SecretKey key = skf.generateSecret(spec);
        byte[] res = key.getEncoded();

I am wondering how generating works when a key lengthis longer than specified SHA digest algorithm type?

For example - what happens when I set a key length of 1024 bits and use PBKDF2WithHmacSHA512 algorithm? Where are 512 bits generated?

Body:
In general it is not advised to ask for more than the hash length as each block is run through all the iterations again:

According to Wikipedia (which has a somewhat more readable format than PKCS#5):

DK = T1 || T2 || ... || Tdklen/hlen
Ti = F(Password, Salt, c, i)

here c is the iteration count by the way.

The problem with this is that generally large amounts of key material are only used when the result is split into multiple components. And if an attacker can verify a good password guess using only - say - the first 128 bits then the attacker has to do less work than the legitimate user of the algorithm.

One way of resolving this is to split the output of PBKDF2 using a KBKDF such as HKDF using different labels (information that is also hashed). That way you can generate almost infinite amount of key material without running through all the iterations for each 512 bits.

Note that 512 bits is enough for two very secure AES-256 bit keys. So that's one very good reason to use SHA-512 for PBKDF2. Note that on 64 bit machines SHA-512 may be faster than SHA-256 while delivering more output material and security.


问:
Terraform - should I use user_data or provisioner to bootstrap a resource?
It seems like I can use either user_data with a template file or a "remote-exec" provisioner with inline commands to bootstrap. So which one is considered more idiomatic?

答:
Though I do agree with Josh, if there are no run time changes to the instance you can use packer to build an ami and then use that in the launch config. That way you don't have to wait for user-data to run.

Packer is part of the Hashicorp family of tools

https://www.packer.io/docs/builders/amazon-ebs.html


问:
connecting to a remote java application
I have to build a server/client chat room in java as a school project, and I want to know if I can connect to that server from the world network (not local network) using the IP address and ports (I wanted to host it but I realized too late that I should have built a web app not a desktop one). My app is using Transmission Content Protocol(TCP) sockets. I have tried to connect to the app by using the public IP and the port that I have opened in firewall. I can post the code if needed. Thanks in advance</p>

答:
If your networks firewall settings let you do it, of course you can connect.

Now, your computer has an internal ip address, which is like 192.168.xxx.xxx and your router has an external ip address which is unique.

Set up your router to forward connections. Steps to do it may change for each router but the point is to forward all connections coming to this router with a port number you have declared, to a internal ip address and a port number.

In your client side, your connection statement will have your external ip adress and the port number you have written in your router settings. In your server side, it will listen your internal ip address and the port number your router forwards to.

To be clear;

Client  ---"xx.xx.xx.xx:9999"--->  Router  ---"192.168.xx.xx:8888"---> Server

As you see above, the router forwards all the connections coming to 9999. port, to 192.168.xx.xx address and 8888. port.

Title: connecting to a remote java application


问:
Angular 4.1.3 When using AOT, Service Factory returns undefined
In my Angular app, I use a shared service that I need not to be a singleton as the data is updated constantly.

Service Factory:

```<code>import {DataService} from '../../../../shared/services/data.service';
import {Http} from '@angular/http';

export const DataServiceProvider = {
    provide: DataService,
    useFactory(http: Http) {
        return new DataService(http);
    },
    deps: [Http]
};
</code>```

When I run the app in JIT mode, the factory works fine, but when I build with the --aot flag, I receive the following error.

```<code>ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
</code>```

The service returned has a get() method which makes a call to the server.  I'm at a loss to understand what in AOT is breaking this seemingly simple functionality.

For additional reference, I inject the service in the constructor:

```<code>construct(
    dataService: DataService
) {
    super();
}
</code>```

And call it in ngOnInit():

```<code>ngOnOnit() {
    this.subscribe(this.dataService.get(), (res) => { this.data = res });
}
</code>```

I have some subscription functionality abstracted away from my component that handle unsubscribing to prevent memory leaks which is why that code may look so strange.

答:
In order for AOT to work, all functions need to be statically analyzable. See this Medium article for more information. Since you're exporting an object, and that object has an anonymous function on it, try exporting the function as well. Update your factory like this:</p>

```<code>import {DataService} from '../../../../shared/services/data.service';
import {Http} from '@angular/http';

export const DataServiceProvider = {
    provide: DataService,
    useFactory: dataServiceProviderUseFactory,
    deps: [Http]
};
export function dataServiceProviderUseFactory(http: Http) {
    return new DataService(http);
}
</code>```

Body:
In my Angular app, I use a shared service that I need not to be a singleton as the data is updated constantly.

Service Factory:

import {DataService} from '../../../../shared/services/data.service';
import {Http} from '@angular/http';

export const DataServiceProvider = {
    provide: DataService,
    useFactory(http: Http) {
        return new DataService(http);
    },
    deps: [Http]
};

When I run the app in JIT mode, the factory works fine, but when I build with the --aot flag, I receive the following error.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined

The service returned has a get() method which makes a call to the server.  I'm at a loss to understand what in AOT is breaking this seemingly simple functionality.

For additional reference, I inject the service in the constructor:

construct(
    dataService: DataService
) {
    super();
}

And call it in ngOnInit():

ngOnOnit() {
    this.subscribe(this.dataService.get(), (res) => { this.data = res });
}

I have some subscription functionality abstracted away from my component that handle unsubscribing to prevent memory leaks which is why that code may look so strange.

Body:
In order for AOT to work, all functions need to be statically analyzable. See this Medium article for more information. Since you're exporting an object, and that object has an anonymous function on it, try exporting the function as well. Update your factory like this:

import {DataService} from '../../../../shared/services/data.service';
import {Http} from '@angular/http';

export const DataServiceProvider = {
    provide: DataService,
    useFactory: dataServiceProviderUseFactory,
    deps: [Http]
};
export function dataServiceProviderUseFactory(http: Http) {
    return new DataService(http);
}


答:
Here are two ways to do this with your example.

```<code>clear
input  SubjectID  DecisionID  AltID  my_alpha
 1   1   1   0.4
 1   1   2   0.4
 1   2   1   0.6
 1   2   2   0.6
 2   1   1   0.8
 2   1   2   0.8
 2   2   1   0.5
 2   2   2   0.5
 end

 gen alpha_AltID_1 = cond(AltID == 1, my_alpha, 0)
 gen alpha_AltID_2 = cond(AltID == 2, my_alpha, 0)

 separate my_alpha, by(AltID)
 mvencode my_alpha?, mv(0)

 list AltID *alpha*, sep(0)

     +--------------------------------------------------------------+
     | AltID   my_alpha   alpha_~1   alpha_~2   my_alp~1   my_alp~2 |
     |--------------------------------------------------------------|
  1. |     1         .4         .4          0         .4          0 |
  2. |     2         .4          0         .4          0         .4 |
  3. |     1         .6         .6          0         .6          0 |
  4. |     2         .6          0         .6          0         .6 |
  5. |     1         .8         .8          0         .8          0 |
  6. |     2         .8          0         .8          0         .8 |
  7. |     1         .5         .5          0         .5          0 |
  8. |     2         .5          0         .5          0         .5 |
     +--------------------------------------------------------------+
</code>```

So, what about your real case? The separate/mvencode method should work. So should this if your ids go from 1 to 5151:

```<code>forval j = 1/5151 {
    gen alpha_AltID_`j' = cond(AltID == `j', my_alpha, 0)
}
</code>```

If your ids are not so well behaved, then tell us how so.

It's difficult to believe that any loop code would take as long as you report, but since you don't show us the code, detailed comment is difficult.

All that said, why you do need one variable to be mapped to thousands?

Title: Stata: Turning One Variable into Multiple, with each as Value or 0

Body:
Suppose I have the following dataset:

clear
input  SubjectID  DecisionID  AltID  my_alpha
 1   1   1   0.4
 1   1   2   0.4
 1   2   1   0.6
 1   2   2   0.6
 2   1   1   0.8
 2   1   2   0.8
 2   2   1   0.5
 2   2   2   0.5
 end

I want to create a new variable for each value of AltID that depends on the value of my_alpha. In this scenario, there would now be AltID_alpha_1 and AltID_alpha_2. AltID_alpha_1 would be equal to my_alpha when AltID is 1, and equal to 0 otherwise. Similarly, AltID_alpha_2 would be equal to my_alpha when AltID is equal to 2, and equal to 0 otherwise. That is, it should look like this:

| SubjectID  | DecisionID | AltID | my_alpha | alpha_AltID_1 | alpha_AltID_2 |

| 1 ------------ | 1 ------------ | 1 -----   | 0.4 -------- | 0.4--------------- | 0----------------- |

| 1 ------------ | 1 ------------ | 2 -----   | 0.4 -------- | 0----------------- | 0.4--------------- |

| 1 ------------ | 2 ------------ | 1 -----   | 0.6 -------- | 0.6--------------- | 0----------------- |

| 1 ------------ | 2 ------------ | 2 -----   | 0.6 -------- | 0----------------- | 0.6--------------- |

| 2 ------------ | 1 ------------ | 1 -----   | 0.8 -------- | 0.8--------------- | 0----------------- |

| 2 ------------ | 1 ------------ | 2 -----   | 0.8 -------- | 0----------------- | 0.8--------------- |

| 2 ------------ | 2 ------------ | 1 -----   | 0.5 -------- | 0.5--------------- | 0----------------- |

| 2 ------------ | 2 ------------ | 2 -----   | 0.5 -------- | 0----------------- | 0.5--------------- |

The problem is that in my actual data, I have well over a million observations, 5151 values for AltID, and need to create variables for both my_alpha and my_beta (at a minimum). I need a way to do this "quickly".

I tried using a foreach loop to create the variables, but I had to cut it off after it had been running for 20 hours (on my desktop that has 24 GB of RAM). I was able to use the command quietly tab AltID, gen(alpha_AltID_) to get 0's in the proper places and 1's elsewhere, which took only a few seconds, but I then need a loop that replaces all the 1's with proper values, which seems to be taking roughly two hours (at the current pace). Does anyone have a more time-efficient solution?

Body:
Here are two ways to do this with your example.

clear
input  SubjectID  DecisionID  AltID  my_alpha
 1   1   1   0.4
 1   1   2   0.4
 1   2   1   0.6
 1   2   2   0.6
 2   1   1   0.8
 2   1   2   0.8
 2   2   1   0.5
 2   2   2   0.5
 end

 gen alpha_AltID_1 = cond(AltID == 1, my_alpha, 0)
 gen alpha_AltID_2 = cond(AltID == 2, my_alpha, 0)

 separate my_alpha, by(AltID)
 mvencode my_alpha?, mv(0)

 list AltID *alpha*, sep(0)

     +--------------------------------------------------------------+
     | AltID   my_alpha   alpha_~1   alpha_~2   my_alp~1   my_alp~2 |
     |--------------------------------------------------------------|
  1. |     1         .4         .4          0         .4          0 |
  2. |     2         .4          0         .4          0         .4 |
  3. |     1         .6         .6          0         .6          0 |
  4. |     2         .6          0         .6          0         .6 |
  5. |     1         .8         .8          0         .8          0 |
  6. |     2         .8          0         .8          0         .8 |
  7. |     1         .5         .5          0         .5          0 |
  8. |     2         .5          0         .5          0         .5 |
     +--------------------------------------------------------------+

So, what about your real case? The separate/mvencode method should work. So should this if your ids go from 1 to 5151:

forval j = 1/5151 {
    gen alpha_AltID_`j' = cond(AltID == `j', my_alpha, 0)
}

If your ids are not so well behaved, then tell us how so.

It's difficult to believe that any loop code would take as long as you report, but since you don't show us the code, detailed comment is difficult.

All that said, why you do need one variable to be mapped to thousands?


问:
Eclipse - Disabling compiling of XML files while in Java perspective
When compiling android stuff in eclipse, I am forever annoyed when I hit the "Run" button to compile and run, if I am in a .java file everything works great if im in an .xml file (for android layouts) it compiles the xml file and produces an _out.xml file which screws up the project so that I first have to delete the "out" file then clean my project files.

Any quick answer on how to disable the compiling of xml files?

答:
Samuel has told already a solution. What I prefer is to use the "always run the last project" setting.

Go to window -> preferences -> Run/Debug -> Launching and than activate the option on the bottom labeled: "Always launch the previously launched application"

If you have multiple projects you will sometimes have the issue that you start a project you didn't meant to start. That will occur only once, because after starting the right project, you will stick to that until you switch to the next project (which shouldn't happen very often on a working day).

Its not a perfect solution, but prevents the mentioned issue with, in my experience, the lowest/smallest (whats the right term?) side effects.


问:
How to get PyQt4 working with Spyder
I'm trying to step through some code using Spyder (Python 3.6) but I keep getting the below error:

ModuleNotFoundError: No module named 'PyQt4'

I have googled it and looked through Stack Overflow, but none of the possibilities seem to work.

答:
Qt4 is no longer supported in Anaconda, so no new packages were created for Python 3.6.

You could use a community channel called conda-forge to install PyQt4 for Python 3.6. However, that channel is not supported nor associated with Continuum (the company behind Anacoda).

Title: How to get PyQt4 working with Spyder


问:
awk command returns inconsistent result
I have a script which performs several validations in a file.
One of the validation is to check if a line exceeds 95 characters (including spaces). If it does, it will return the line number/s where the line exceeds 95 characters. Below is the command used for the validation:

```<code>$(cat $FileName > $tempfile)
totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4])
if [[$totalCharacters != "" ]]; then
  totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4] | cut -d : -f1 | tr "\n" ",")
  echo "line too long"
  exit 1
fi
</code>```

In the lower environment the code is working as expected. But in production, there are time that the validation returns the error "line too long" but does not return any line number. We just reran the script and it does not return any error.

I would like to know what could be wrong in the command used.
The previous developer who worked on this said that it could be an issue with the use of the awk command, but I am not sure since this is the first time I have encountered using the awk command.

答:
This is not well written.  All you need is:

```<code>awk 'length>94{print NR; f=1} END{exit f}' file
</code>```

If there are lines longer than 94 chars, it will print the line numbers and the exit with status 1; otherwise the exit status will be 0 and no output will be generated.

Title: awk command returns inconsistent result

Body:
I have a script which performs several validations in a file.
One of the validation is to check if a line exceeds 95 characters (including spaces). If it does, it will return the line number/s where the line exceeds 95 characters. Below is the command used for the validation:

$(cat $FileName > $tempfile)
totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4])
if [[$totalCharacters != "" ]]; then
  totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4] | cut -d : -f1 | tr "\n" ",")
  echo "line too long"
  exit 1
fi

In the lower environment the code is working as expected. But in production, there are time that the validation returns the error "line too long" but does not return any line number. We just reran the script and it does not return any error.

I would like to know what could be wrong in the command used.
The previous developer who worked on this said that it could be an issue with the use of the awk command, but I am not sure since this is the first time I have encountered using the awk command.

Body:
This is not well written.  All you need is:

awk 'length>94{print NR; f=1} END{exit f}' file

If there are lines longer than 94 chars, it will print the line numbers and the exit with status 1; otherwise the exit status will be 0 and no output will be generated.


问:
make says: `No rule to make target` when I try to compile a Qt application for android platfrom
I wanted to compile this project for android platform. I simply downloaded it and selected all android kits after I opened the TelnetWidgetTest.pro file in Qt creator. Now the project could be compiled successfully if I choose (Android for x86 GCC4.9 Qt 5.5.0) but I got the following error when I select (Android for armeabi-v7a GCC 4.9 Qt 5.5.0):

```<code>mingw32-make: *** No rule to make target '..\..\..\..\AppData\Roaming\IDM\android-ndk-r10d\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_hashtable_size.h', needed by 'build\mainwindowimpl.obj'.  Stop.
17:43:33: The process "C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe" exited with code 2.
Error while building/deploying project TelnetWidgetTest (kit: Android for armeabi-v7a (GCC 4.9, Qt 5.5.0))
When executing step "Make"
</code>```

If I choose (kit: Android for armeabi (GCC 4.9, Qt 5.5.0)) It also returns the following error:

```<code>    mingw32-make: *** No rule to make target '..\..\..\..\AppData\Roaming\IDM\android-ndk-r10d\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h', needed by 'build\mainwindowimpl.obj'.  Stop.
17:42:38: The process "C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe" exited with code 2.
Error while building/deploying project TelnetWidgetTest (kit: Android for armeabi (GCC 4.9, Qt 5.5.0))
When executing step "Make"
</code>```

The program could be compiled and run successfully in windows desktop.

What does it mean when make tells **No rule to make target** ? I checked the mentioned folders the files exist and path to android NDK is correct. So what the real problem is?

Another question is that, What is profiler_map_to_unordered_map.h and why it is needed by one of my object files (mainwindowimpl.obj).

答:
Just yesterday I bumped into a similar issue. After a rather painful investigation I found that the culprit is path length!

If I create a project:

```<code>`c:\x\12345678901234567890123456789012345.pro`
</code>```

which creates build directory

```<code>`c:\build-12345678901234567890123456789012345-Android_for_armeabi_v7a_GCC_4_9_Qt_5_9_0_for_Android_armv7-Debug`
</code>```

(109 characters) with Android SDK in

```<code>`c:\Users\miroslav.kropacek\AppData\Local\Android\sdk`
</code>```

it creates paths in Makefile like:

```<code>`..\Users\miroslav.kropacek\AppData\Local\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`
</code>```

(150 characters)

One (less comfortable) solution is to rename your project file, in my example shortening it by one character from 12345678901234567890123456789012345 to 1234567890123456789012345678901234 is enough to make it compile.

Another solution is to manually take care in Qt creator's dialog for build directories specification, and enter something less offending there (like simple "release" and "debug" directories) but you have to remember to do that every time you pull sources from scratch.

And yet another solution is copying Android SDK to C:\Android\sdk which leads to following path in Makefile:

```<code>`..\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`
</code>```

(112 characters) and works OK.

Without looking into source code I can only speculate that the culprit is mingw's make which creates a buffer 260 characters long so when the relative path is resolving, it gets as long as:

```<code>`c:\build-12345678901234567890123456789012345-Android_for_armeabi_v7a_GCC_4_9_Qt_5_9_0_for_Android_armv7-Debug\..\Users\miroslav.kropacek\AppData\Local\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`
</code>```

what happens to be exactly 260 characters and with \0 it's exactly one character beyond with infamous Windows limit.

Body:
I wanted to compile this project for android platform. I simply downloaded it and selected all android kits after I opened the TelnetWidgetTest.pro file in Qt creator. Now the project could be compiled successfully if I choose (Android for x86 GCC4.9 Qt 5.5.0) but I got the following error when I select (Android for armeabi-v7a GCC 4.9 Qt 5.5.0):

mingw32-make: *** No rule to make target '..\..\..\..\AppData\Roaming\IDM\android-ndk-r10d\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_hashtable_size.h', needed by 'build\mainwindowimpl.obj'.  Stop.
17:43:33: The process "C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe" exited with code 2.
Error while building/deploying project TelnetWidgetTest (kit: Android for armeabi-v7a (GCC 4.9, Qt 5.5.0))
When executing step "Make"

If I choose (kit: Android for armeabi (GCC 4.9, Qt 5.5.0)) It also returns the following error:

    mingw32-make: *** No rule to make target '..\..\..\..\AppData\Roaming\IDM\android-ndk-r10d\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h', needed by 'build\mainwindowimpl.obj'.  Stop.
17:42:38: The process "C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe" exited with code 2.
Error while building/deploying project TelnetWidgetTest (kit: Android for armeabi (GCC 4.9, Qt 5.5.0))
When executing step "Make"

The program could be compiled and run successfully in windows desktop.

What does it mean when make tells **No rule to make target** ? I checked the mentioned folders the files exist and path to android NDK is correct. So what the real problem is?

Another question is that, What is profiler_map_to_unordered_map.h and why it is needed by one of my object files (mainwindowimpl.obj).

Body:
Just yesterday I bumped into a similar issue. After a rather painful investigation I found that the culprit is path length!

If I create a project:

`c:\x\12345678901234567890123456789012345.pro`

which creates build directory

`c:\build-12345678901234567890123456789012345-Android_for_armeabi_v7a_GCC_4_9_Qt_5_9_0_for_Android_armv7-Debug`

(109 characters) with Android SDK in

`c:\Users\miroslav.kropacek\AppData\Local\Android\sdk`

it creates paths in Makefile like:

`..\Users\miroslav.kropacek\AppData\Local\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`

(150 characters)

One (less comfortable) solution is to rename your project file, in my example shortening it by one character from 12345678901234567890123456789012345 to 1234567890123456789012345678901234 is enough to make it compile.

Another solution is to manually take care in Qt creator's dialog for build directories specification, and enter something less offending there (like simple "release" and "debug" directories) but you have to remember to do that every time you pull sources from scratch.

And yet another solution is copying Android SDK to C:\Android\sdk which leads to following path in Makefile:

`..\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`

(112 characters) and works OK.

Without looking into source code I can only speculate that the culprit is mingw's make which creates a buffer 260 characters long so when the relative path is resolving, it gets as long as:

`c:\build-12345678901234567890123456789012345-Android_for_armeabi_v7a_GCC_4_9_Qt_5_9_0_for_Android_armv7-Debug\..\Users\miroslav.kropacek\AppData\Local\Android\sdk\ndk-bundle\sources\cxx-stl\gnu-libstdc++\4.9\include\profile\impl\profiler_map_to_unordered_map.h`

what happens to be exactly 260 characters and with \0 it's exactly one character beyond with infamous Windows limit.


问:
SQL selecting a record based on a column but displaying all values in said column
I'm having an issue where a table can be setup as below.  I want to only return the records that have BA in column C but I also want to show that those records have a line for AA.

name,   invoice,     code,      payment

name1,    111,        BA,        $20

name1,    112,        AA,        $50

name2,    113,        AA,        $50

By adding code = BA in the Where clause, I am only getting line 1.  I would like to only pull the name1 name because it has an invoice with the BA code but I would also like to pull the second line because it is the same person and I want to show all payments for any person that has a BA code.  Say invoice 111 was a partial payment with an error code BA and that person came back later to correct their mistake and make an additional payment.  I want to be able to show that correction as well.

Thanks in advance!

答:
```<code>SELECT t1.*
FROM [Table] t1
INNER JOIN
(
    SELECT DISTINCT [name] FROM [Table] WHERE code = 'BA'
) t2 ON t2.[name] = t1.[name]
</code>```


问:
Simple Yahtzee simulation not giving proper result?
I am working through the MIT OpenCourseWare intro to computer programming course and I am not sure if I am solving a simple simulation the right way.

What is the probability of rolling a Yahtzee! on the first roll? That is, what is the
  probability of rolling five 6-sided dice, and having them all display the same number?

Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and
  submit your code as

So the probability of rolling a Yahtzee is 1/1296 or about .077%

Here is my code to run the simulation:

```<code>import random

def runYahtzee(numTrials):
    """Runs the classes version of the yahtzee simulation"""

    success = 0
    for i in range(numTrials):

        dices = []
        for i in range(6):
            dices.append(random.randrange(1,7))
        #print dices

        state = True
        for dice in dices:
            if dice != dices[0]:
                state = False
        if state == True:
            print "You got a Yahtzee"
            print dices
            success += 1

    print "numTrials is: " + str(numTrials)
    print "Success is: " + str(success)
    rate = float(success)/numTrials
    return rate

runYahtzee(10000000)
</code>```

Running the program multiple times, I get around .0001258 each time.  This is .012%, but the actual probability is around .077%. Is there something that I am doing wrong here?

答:
What you're doing wrong is rolling 6 dice instead of 5.

0.001258 * 6 = 0.0007548

... which is close to your 0.077%

Change your loop:

```<code>    for i in range(5):
</code>```

BTW, the plural is dice; the singular is die.  dices is wrong, unless you're trying to be amusing.  In that case, you can use the singular "douse" ... never say die!

Body:
I am working through the MIT OpenCourseWare intro to computer programming course and I am not sure if I am solving a simple simulation the right way.

What is the probability of rolling a Yahtzee! on the first roll? That is, what is the
  probability of rolling five 6-sided dice, and having them all display the same number?

Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and
  submit your code as

So the probability of rolling a Yahtzee is 1/1296 or about .077%

Here is my code to run the simulation:

import random

def runYahtzee(numTrials):
    """Runs the classes version of the yahtzee simulation"""

    success = 0
    for i in range(numTrials):

        dices = []
        for i in range(6):
            dices.append(random.randrange(1,7))
        #print dices

        state = True
        for dice in dices:
            if dice != dices[0]:
                state = False
        if state == True:
            print "You got a Yahtzee"
            print dices
            success += 1

    print "numTrials is: " + str(numTrials)
    print "Success is: " + str(success)
    rate = float(success)/numTrials
    return rate

runYahtzee(10000000)

Running the program multiple times, I get around .0001258 each time.  This is .012%, but the actual probability is around .077%. Is there something that I am doing wrong here?

Body:
What you're doing wrong is rolling 6 dice instead of 5.

0.001258 * 6 = 0.0007548

... which is close to your 0.077%

Change your loop:

    for i in range(5):

BTW, the plural is dice; the singular is die.  dices is wrong, unless you're trying to be amusing.  In that case, you can use the singular "douse" ... never say die!


问:
Difference between synchronized(this) and few synchronized methods of class
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

```<code>public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}
</code>```

答:
No, they are the same.

```<code>private synchronized void foo() {}

private void foo2() {
 synchronized(this){
 }
}
</code>```

They will do the exact same as both monitor the instance which they are called from.

A good tutorial can be found in the blog of Jakob Jenkov
http://tutorials.jenkov.com/java-concurrency/synchronized.html#java-synchronized-example

Happy coding!

Body:
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}

Body:
No, they are the same.

private synchronized void foo() {}

private void foo2() {
 synchronized(this){
 }
}

They will do the exact same as both monitor the instance which they are called from.

A good tutorial can be found in the blog of Jakob Jenkov
http://tutorials.jenkov.com/java-concurrency/synchronized.html#java-synchronized-example

Happy coding!


问:
Transform between RGB and one Integer/Float Value
I'd like to ask if it's possible to transform between RGB and one continuous color value (like in float [0..1] or Integer [0..255]) that represents a color range.

E.g.: I have a continous color range like a rainbow:

Red - Orange - Yellow - Green - Blue - Indigo - Violet

-> represented with 0~1 or 0~255 (or whatever range)

And now I want to transform the value e.g. (0.5 = green) to an equal RGB value ([0,1,0]?). Is that possible with a transfer function (back and forward)? Maybe in Python?

答:
The simplest way is simply to add up the RGB while weighting each component.  Doing so will give you a range 0-16,777,215. Eg:

```<code>RGB Tuple = Hex Value = Decimal
0,0,0 = 0x000000 = 0
255,255,255 = 0xFFFFFF = 16777215
</code>```

Here's a online calculator that will convert any individual color: https://www.shodor.org/stella2java/rgbint.html

Code for hex converters in any given language will be all over the google. :)

You can use any number space you like (eg 0-1 or whatever) and go back and forth as much as you want, so long as your chosen number space holds all of those 16.7+ million unique colors.

If you compress the number space, you'd be losing some colors (as the first poster explained).

Body:
The simplest way is simply to add up the RGB while weighting each component.  Doing so will give you a range 0-16,777,215. Eg:

RGB Tuple = Hex Value = Decimal
0,0,0 = 0x000000 = 0
255,255,255 = 0xFFFFFF = 16777215

Here's a online calculator that will convert any individual color: https://www.shodor.org/stella2java/rgbint.html

Code for hex converters in any given language will be all over the google. :)

You can use any number space you like (eg 0-1 or whatever) and go back and forth as much as you want, so long as your chosen number space holds all of those 16.7+ million unique colors.

If you compress the number space, you'd be losing some colors (as the first poster explained).


问:
C# disable listbox from parent form
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

```<code>_child.listBox1.Enabled = false;
</code>```

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?

答:
Although it works, exposing the control of a form as a public property is considered a bad design practice.

Suppose that at some point in the future, you will have to change the internal ListBox into some other type, such as ListView, in order to add some functionality.

In this scenario, if you create a method called DisableList on the form, you will only have to change one place in code, to update the way the list should be disabled.

But if you choose the method of writing code such as _client.listbox1.Enabled = false;, you will have to go through all the pieces of code that touch the ListBox, and update them.

A very important principal in design is to avoid exposing the internal implementation details of class to those that have to use it. In this case, you will benefit if the parent form won't have to know that the list is implemented as a ListBox.

Title: C# disable listbox from parent form

Body:
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

_child.listBox1.Enabled = false;

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?


问:
BotKit Slack Bot to Microsoft Teams Bot
I recently built a slack bot via the BotKit toolkit and now want to be able to expand from just slack to many other services. Basically, I was reading https://venturebeat.com/2016/11/02/how-bots-will-work-on-microsoft-teams/
and it states that

"The integration means Microsoft Bot Framework users will be able to make bots for Slack, and Botkit users will be able to bring their bots to additional platforms, like Telegram, Kik, Twilio, and Skype. (Before the change, Botkit was only able to make bots for Slack and Facebook Messenger.)"

However, it is not clear to me how this can be accomplished. Do you mind explaining this to me or pointing me in the right direction? From what I understand, it should be a simple process of having my slackbot basically run within Microsoft Teams or Skype or whatever service.

Thanks!

答:
So I think your path is:

Register your bot in the Bot Framework to host the bot, referencing the Botkit. Make sure you add Microsoft Teams as a channel.

Create a package for your bot and [Sideload it][3] in Teams to test.

Title: BotKit Slack Bot to Microsoft Teams Bot


问:
why is ok to chain jquery effects, instead of using callbacks
In the jquery documentation is stated that if you want to add a class after an effect is applied on a selection you must use a callback:

```<code>// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});
</code>```

However, you can chain two effects without needing to use a callback:

```<code>$(".something").fadeOut().fadeIn();
</code>```

Why is that? shouldn't you have to use a callback like this, too:

```<code>$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});
</code>```

答:
Because, simply put, the call to .fadeIn doesn't wait. All it does is add the effect to a queue, then continues with whatever other code you have. What the jQuery documentation is saying is that if you want to add a class to an element once the effect is complete (which they're just using as an example), you'll have to use the callback, which is called at the end of the effect.

Additionally, you absolutely could chain two effects by using callbacks, but it's unnecessary amounts of typing (and developers usually aim to be as lazy as possible). The reason it works to chain two effects together without the callback is that calling .fadeIn or .fadeOut adds the appropriate effect to jQuery's effect queue for that DOM element. Effects are played from the queue one at a time, in sequence, so no matter how fast you add them to the queue, they'll always play out at the correct speed and time.

Body:
In the jquery documentation is stated that if you want to add a class after an effect is applied on a selection you must use a callback:

// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});

However, you can chain two effects without needing to use a callback:

$(".something").fadeOut().fadeIn();

Why is that? shouldn't you have to use a callback like this, too:

$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});


问:
how to add ArrayList data to the same # in derby?
so i have this issue not sure how to solve it i want to add arraylist data  such as [A,b,c,d,e,f] to the first record looking something like this </p>

```<code>"#"|| ID  ||  numbers  || section

`1 ||  1  ||  Abcdef  ||   A1
</code>```

<p>here is my code </p>

```<code>Statement st = conn.createStatement();
String sql = "INSERT INTO LOCATION (ID,LETTERS,SECTION) "
        + "VALUES (?,?,?)";
System.out.println(ch.size());
try (PreparedStatement insert = conn.prepareStatement(sql)) {
        insert.setString(1, "1");
        insert.setString(3, "A1");
    for (int i = 0; i < ch.size(); i++) {
         insert.setString(2, ch.get(i).toString());
         insert.executeUpdate();
    }
    st.close();
    conn.close();
}
</code>```

答:
I think there are two problems

Your code executes an update (insert.executeUpdate()) so many times as your ch arraylist size

You are invoking the setString as many times as the length of your arraylist but passing it a single character and not a concatenation of the elements of your arraylist

That part of your code should be:

```<code>   String arrayChars = "";
   for (int i = 0; i < ch.size(); i++) {
         arrayChars += ch.get(i).toString(); // If youre using an array of strings theres no need to use .toString()
    }
    insert.setString(2, arrayChars);
    insert.executeUpdate();
</code>```

Body:
so i have this issue not sure how to solve it i want to add arraylist data  such as [A,b,c,d,e,f] to the first record looking something like this

"#"|| ID  ||  numbers  || section

`1 ||  1  ||  Abcdef  ||   A1

here is my code

Statement st = conn.createStatement();
String sql = "INSERT INTO LOCATION (ID,LETTERS,SECTION) "
        + "VALUES (?,?,?)";
System.out.println(ch.size());
try (PreparedStatement insert = conn.prepareStatement(sql)) {
        insert.setString(1, "1");
        insert.setString(3, "A1");
    for (int i = 0; i < ch.size(); i++) {
         insert.setString(2, ch.get(i).toString());
         insert.executeUpdate();
    }
    st.close();
    conn.close();
}

Body:
I think there are two problems

Your code executes an update (insert.executeUpdate()) so many times as your ch arraylist size

You are invoking the setString as many times as the length of your arraylist but passing it a single character and not a concatenation of the elements of your arraylist

That part of your code should be:

   String arrayChars = "";
   for (int i = 0; i < ch.size(); i++) {
         arrayChars += ch.get(i).toString(); // If youre using an array of strings theres no need to use .toString()
    }
    insert.setString(2, arrayChars);
    insert.executeUpdate();