问:
R - doParallel does not work with Student and Fisher tests
So I am using the R package doParallel to parallelized some steps of my script when I have to handle large list of elements to compute it faster.
Since this time all of the functions I used so far were wroking perfectly well with foreach() : I just had to specify my number of cores with registerDoParallel() and that was all!

I recently tried to use different statistics tests in R using var.test() and t.test() and I don't understand why but I realized that used in foreach() it wasn't working...
So to be more clear what I am basically doing is iterating over rows of 2 matrices of the same dimensions : each row , in each matrix, contains 5 numeric values and I do for example:

```<code>var.test(matrixA[1,],matrixB[1,])$p.value
</code>```

to extract, for row number 1, the corresponding p.value from the Fisher test made on 10 numeric values (2 groups of 5 values in each matrix's row number 1).
Problem is my matrices have millions of rows so I have to iterate over the number of rows, and I do this with the foreach() function:

```<code>p.values.res<-foreach(i=seq(dim(matrixA)[1])) %dopar%
  var.test(matrixA[i,],matrixB[i,])$p.value
</code>```

(Here I set registerDoParallel(cores = 6) prior to the foreach()).
I tried different tests : fisher test and student test (t.test()) and unfortunately none of them were working on my 6 cores, only one.

I also tried with "cl": registerDoParallel(cl = 4)
It doesn't work either.

I tried to restart R, to quit and reopen session, to restart computer: doesn't work.

Does anybody knows why it does not work, and how to fix that ?

My configuration: Linux Mint 18.2 Cinnamon 64-bit (3.4.6); Intel Core I7-6700 CPU; R version 3.4.3 (2017-11-30); RStudio Version 1.1.383 2009-2017.

here are 2 short examples of matrices

MatrixA:

```<code>0.7111111  0.7719298  0.7027027   0.6875000  0.6857143
0.8292683  0.6904762  0.8222222   0.8333333  0.6250000
0.8846154  0.5714286  0.8928571   0.8846154  0.9259259
0.9000000  0.5000000  0.9500000   0.8666667  0.8260870
0.8235294  0.3684211  0.9411765   0.8333333  0.8000000
0.5714286  0.2142857  0.6666667   0.5000000  0.5555556
</code>```

MatrixB:

```<code>0.5227273  0.7142857  0.7808219   0.6346154  0.7362637
0.9166667  0.7173913  0.8611111   0.7391304  0.7538462
0.8666667  0.6052632  0.8260870   0.7333333  0.9024390
0.9285714  0.5806452  0.8750000   0.6956522  0.8787879
0.8333333  0.5517241  0.8333333   0.6818182  0.8750000
0.7500000  0.2941176  0.6666667   0.4444444  0.7500000
</code>```

Thank you all in advance for your help.
Regards,

答:
I can't reproduce your problem. This works fine for me:</p>

```<code>matrixA <- matrix(runif(36), 6)
matrixB <- matrix(runif(36), 6)

cl <- parallel::makeCluster(4)
doParallel::registerDoParallel(cl)
library(foreach)
p.values.res<-foreach(i=seq(dim(matrixA)[1])) %dopar%
  var.test(matrixA[i,],matrixB[i,])$p.value
parallel::stopCluster(cl)
</code>```

Body:
So I am using the R package doParallel to parallelized some steps of my script when I have to handle large list of elements to compute it faster.
Since this time all of the functions I used so far were wroking perfectly well with foreach() : I just had to specify my number of cores with registerDoParallel() and that was all!

I recently tried to use different statistics tests in R using var.test() and t.test() and I don't understand why but I realized that used in foreach() it wasn't working...
So to be more clear what I am basically doing is iterating over rows of 2 matrices of the same dimensions : each row , in each matrix, contains 5 numeric values and I do for example:

var.test(matrixA[1,],matrixB[1,])$p.value

to extract, for row number 1, the corresponding p.value from the Fisher test made on 10 numeric values (2 groups of 5 values in each matrix's row number 1).
Problem is my matrices have millions of rows so I have to iterate over the number of rows, and I do this with the foreach() function:

p.values.res<-foreach(i=seq(dim(matrixA)[1])) %dopar%
  var.test(matrixA[i,],matrixB[i,])$p.value

(Here I set registerDoParallel(cores = 6) prior to the foreach()).
I tried different tests : fisher test and student test (t.test()) and unfortunately none of them were working on my 6 cores, only one.

I also tried with "cl": registerDoParallel(cl = 4)
It doesn't work either.

I tried to restart R, to quit and reopen session, to restart computer: doesn't work.

Does anybody knows why it does not work, and how to fix that ?

My configuration: Linux Mint 18.2 Cinnamon 64-bit (3.4.6); Intel Core I7-6700 CPU; R version 3.4.3 (2017-11-30); RStudio Version 1.1.383 2009-2017.

here are 2 short examples of matrices

MatrixA:

0.7111111  0.7719298  0.7027027   0.6875000  0.6857143
0.8292683  0.6904762  0.8222222   0.8333333  0.6250000
0.8846154  0.5714286  0.8928571   0.8846154  0.9259259
0.9000000  0.5000000  0.9500000   0.8666667  0.8260870
0.8235294  0.3684211  0.9411765   0.8333333  0.8000000
0.5714286  0.2142857  0.6666667   0.5000000  0.5555556

MatrixB:

0.5227273  0.7142857  0.7808219   0.6346154  0.7362637
0.9166667  0.7173913  0.8611111   0.7391304  0.7538462
0.8666667  0.6052632  0.8260870   0.7333333  0.9024390
0.9285714  0.5806452  0.8750000   0.6956522  0.8787879
0.8333333  0.5517241  0.8333333   0.6818182  0.8750000
0.7500000  0.2941176  0.6666667   0.4444444  0.7500000

Thank you all in advance for your help.
Regards,

Body:
I can't reproduce your problem. This works fine for me:

matrixA <- matrix(runif(36), 6)
matrixB <- matrix(runif(36), 6)

cl <- parallel::makeCluster(4)
doParallel::registerDoParallel(cl)
library(foreach)
p.values.res<-foreach(i=seq(dim(matrixA)[1])) %dopar%
  var.test(matrixA[i,],matrixB[i,])$p.value
parallel::stopCluster(cl)


来源: stackexchange

问:
initialValues for multiple select in redux-form
I have select element defined as multiple. I want to pass initialValues to redux-form

```<code>     <Field
          name="favoriteColor"
          component="select"
          type="select-multiple"
          multiple >
            <option value="">Select a color...</option>
            {colors.map(colorOption => (
              <option value={colorOption.name} key={colorOption.name}>
                {colorOption.name}
              </option>
            ))}
      </Field>
</code>```

CodeSandBox example

Redux-form reacts to changes like favoriteColor: ['Blue', 'Green', ...], but i need favoriteColor: [{name: 'Blue'}, {name: 'Green'}, ...]. Also for initializing it has to be watch to name field of object

答:
Use lodash to manipute data on your initialValues prop of your form.

https://codesandbox.io/s/318n0oy6xp

ContentLicense: CC BY-SA 4.0

Body:
I have select element defined as multiple. I want to pass initialValues to redux-form

     <Field
          name="favoriteColor"
          component="select"
          type="select-multiple"
          multiple >
            <option value="">Select a color...</option>
            {colors.map(colorOption => (
              <option value={colorOption.name} key={colorOption.name}>
                {colorOption.name}
              </option>
            ))}
      </Field>

CodeSandBox example

Redux-form reacts to changes like favoriteColor: ['Blue', 'Green', ...], but i need favoriteColor: [{name: 'Blue'}, {name: 'Green'}, ...]. Also for initializing it has to be watch to name field of object

ContentLicense: CC BY-SA 3.0


问:
Enter triggers button click
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

```<code>$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})
</code>```

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

答:
You can use javascript to block form submission until the appropriate time.  A very crude example:

```<code><form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">

    <input type='text' name='txtTest' />

    <input type='button' value='Submit'
        onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />

</form>
</code>```

Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.

Title: Enter triggers button click

Body:
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

Body:
You can use javascript to block form submission until the appropriate time.  A very crude example:

<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">

    <input type='text' name='txtTest' />

    <input type='button' value='Submit'
        onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />

</form>

Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.

ContentLicense: CC BY-SA 2.5


问:
Remove unnecessary nesting when deserializing XML or access data in parent node?
The XML I'm attempting to deserialize has a lot of fields that have the data nested in a subfield and I'd like to assign this data into the parent property on the class rather than create additional unneeded structure.

```<code><?xml version="1.0" encoding="UTF-8"?>
<x:EventRecord eventid="EVR-1000">
  <x:Postcode>
    <x:ID>ABC123</x:ID>
  </x:Postcode>
</x:EventRecord>
</code>```

I've created an EventRecord class with a Postcode string property:

```<code>public class EventRecord
{
  public string EventID { get; set; }
  public string Postcode { get; set; }
}
</code>```

Is there an attribute that can decorate the property that can tell the deserializer to take the value out of the nested ID field? There will never be any other fields in <x:Postcode> aside from <x:ID>.

Also is there a way to assign the eventid XML attribute on the parent x:EventRecord node to the EventID property inside itself?

答:
Using following xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<root xmlns:x="abc">
<x:EventRecord eventid="EVR-1000">
  <x:Postcode>
    <x:ID>ABC123</x:ID>
  </x:Postcode>
</x:EventRecord>
</root>
</code>```

Code :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetNamespaceOfPrefix("x");

            EventRecord record = doc.Descendants(ns + "EventRecord").Select(x => new EventRecord() {
                EventID = (string)x.Attribute("eventid"),
                Postcode = (string)x.Descendants(ns + "ID").FirstOrDefault()
            }).FirstOrDefault();

        }
    }
    public class EventRecord
    {
        public string EventID { get; set; }
        public string Postcode { get; set; }
    }
}
</code>```

Body:
The XML I'm attempting to deserialize has a lot of fields that have the data nested in a subfield and I'd like to assign this data into the parent property on the class rather than create additional unneeded structure.

<?xml version="1.0" encoding="UTF-8"?>
<x:EventRecord eventid="EVR-1000">
  <x:Postcode>
    <x:ID>ABC123</x:ID>
  </x:Postcode>
</x:EventRecord>

I've created an EventRecord class with a Postcode string property:

public class EventRecord
{
  public string EventID { get; set; }
  public string Postcode { get; set; }
}

Is there an attribute that can decorate the property that can tell the deserializer to take the value out of the nested ID field? There will never be any other fields in <x:Postcode> aside from <x:ID>.

Also is there a way to assign the eventid XML attribute on the parent x:EventRecord node to the EventID property inside itself?

Body:
Using following xml :

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:x="abc">
<x:EventRecord eventid="EVR-1000">
  <x:Postcode>
    <x:ID>ABC123</x:ID>
  </x:Postcode>
</x:EventRecord>
</root>

Code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetNamespaceOfPrefix("x");

            EventRecord record = doc.Descendants(ns + "EventRecord").Select(x => new EventRecord() {
                EventID = (string)x.Attribute("eventid"),
                Postcode = (string)x.Descendants(ns + "ID").FirstOrDefault()
            }).FirstOrDefault();

        }
    }
    public class EventRecord
    {
        public string EventID { get; set; }
        public string Postcode { get; set; }
    }
}


问:
Can I use grep to extract a single column of a CSV file?
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
```

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

答:
If you just need the 3rd field and it's always properly delimited with ';'  why not use 'cut'?

```<code>cut -d';' -f3   <filename>
</code>```

UPDATED:

OP wasn't clear, maybe only want to look at the 3rd line?

```<code>head -3 <filename> | tail -1
</code>```

OR..   Maybe just getting of list of the things that appear in the 3rd field?

Not clear what the intended use of 'grep' would be??

```<code>cut -d';' -f3   <filename>  | sort -u
</code>```

Body:
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

Body:
If you just need the 3rd field and it's always properly delimited with ';'  why not use 'cut'?

cut -d';' -f3   <filename>

UPDATED:

OP wasn't clear, maybe only want to look at the 3rd line?

head -3 <filename> | tail -1

OR..   Maybe just getting of list of the things that appear in the 3rd field?

Not clear what the intended use of 'grep' would be??

cut -d';' -f3   <filename>  | sort -u


问:
Can operations be generalized?
I just wrote this code:

```<code>private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

答:
You can make a Dictionary<OperationEnum, Func<double, double, double>>:

```<code>static readonly Dictionary<OperationEnum, Func<double, double, double>> operations =
    new Dictionary<OperationEnum, Func<double, double, double>> {
        { OperationEnum.Sum, (a, b) => a + b },
        ...
    };
</code>```

Title: Can operations be generalized?

Body:
I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

Body:
You can make a Dictionary<OperationEnum, Func<double, double, double>>:

static readonly Dictionary<OperationEnum, Func<double, double, double>> operations =
    new Dictionary<OperationEnum, Func<double, double, double>> {
        { OperationEnum.Sum, (a, b) => a + b },
        ...
    };


问:
STDEVP for calculated fields
I have a table that looks like this:

```<code>ID       CHANNEL    VENDOR  num_PERIOD  SALES.A SALES.B
000001  Business    Shop    1            40       30
000001  Business    Shop    2            60       20
000001  Business    Shop    3            NULL     30
</code>```

With many combinations of ID, CHANNEL and VENDOR, and sales records for each of them over time (num_PERIOD).

I want to get the average Standard Deviation of a new field, which returns the sum of SALES.A + SALES.B sum(IS.NULL(SALES.A,0) + ISNULL(SALES.B,0)).

The problem I have is that STDEVP seem to fail with calculated fields, and the result that returns is invalid.

I have been trying with:

```<code>select ID, CHANNEL, VENDOR, stdevp(sum(isnull(SALES.A,0) + ISNULL(QSALES.B,0))) OVER (PARTITION BY  ID, CHANNEL, VENDOR) as STDEV_SALES
      FROM TABLE
GROUP BY ID, CHANNEL, VENDOR
</code>```

However, the results I'm obtaning are always 0 or NULL.

What I want to obtain is the Average Standard Deviation of each ID, CHANNEL and VENDOR over time (num_PERIOD).

Can someone find an approximation for this please?

答:
Your query doesn't match the sample data.

I can see the problem, though.  The SUM() are calculating a single value for each group, and then you are taking the standard deviation of that value.  Because you cannot nest aggregation functions, you have turned it into a window function.

Get rid of the sum().  The following should work in SQL Server:

```<code>SELECT ID, CHANNEL, VENDOR,
       STDEVP(COALESCE(SALES.A, 0) + COALESCE(QSALES.B, 0))  as STDEV_SALES
FROM SALES . . .
     QSALES
GROUP BY ID, CHANNEL, VENDOR;
</code>```

I would also return the COUNT(*) . . . the standard deviation doesn't make sense if you have fewer than 3 rows.  (Okay, it is defined for two values, but not very useful.)

Title: STDEVP for calculated fields

Body:
I have a table that looks like this:

ID       CHANNEL    VENDOR  num_PERIOD  SALES.A SALES.B
000001  Business    Shop    1            40       30
000001  Business    Shop    2            60       20
000001  Business    Shop    3            NULL     30

With many combinations of ID, CHANNEL and VENDOR, and sales records for each of them over time (num_PERIOD).

I want to get the average Standard Deviation of a new field, which returns the sum of SALES.A + SALES.B sum(IS.NULL(SALES.A,0) + ISNULL(SALES.B,0)).

The problem I have is that STDEVP seem to fail with calculated fields, and the result that returns is invalid.

I have been trying with:

select ID, CHANNEL, VENDOR, stdevp(sum(isnull(SALES.A,0) + ISNULL(QSALES.B,0))) OVER (PARTITION BY  ID, CHANNEL, VENDOR) as STDEV_SALES
      FROM TABLE
GROUP BY ID, CHANNEL, VENDOR

However, the results I'm obtaning are always 0 or NULL.

What I want to obtain is the Average Standard Deviation of each ID, CHANNEL and VENDOR over time (num_PERIOD).

Can someone find an approximation for this please?

Body:
Your query doesn't match the sample data.

I can see the problem, though.  The SUM() are calculating a single value for each group, and then you are taking the standard deviation of that value.  Because you cannot nest aggregation functions, you have turned it into a window function.

Get rid of the sum().  The following should work in SQL Server:

SELECT ID, CHANNEL, VENDOR,
       STDEVP(COALESCE(SALES.A, 0) + COALESCE(QSALES.B, 0))  as STDEV_SALES
FROM SALES . . .
     QSALES
GROUP BY ID, CHANNEL, VENDOR;

I would also return the COUNT(*) . . . the standard deviation doesn't make sense if you have fewer than 3 rows.  (Okay, it is defined for two values, but not very useful.)


问:
How to provide command line arguments to save a file to a particular location?

I have been using sys.argv to provide parameters in the command line.

For example, I have a method:

```<code>def function(param1, param2):
    # Stuff goes here.

def main():
    ... sys.argv[1] ...
    ... sys.argv[2] ...

if __name__ == '__main__':
main()
</code>```

Now when I run this code the command will be something like this:

```<code>python filename.py param1 param2
</code>```

The param can be anything, from paths to filenames set as and when required.

My question is how to set a parameter in which you can set a destination to store a file, say a pickle file for example. I would like to know how to do something like this:

```<code>python filename.py param1 param2 param3
</code>```

where param3 is basically the destination of the file to be saved. If there is something like sys where we can provide a destination for a file to be saved using param1 and param2.

Please help. Thanks.

答:
Unless your just trying to setup a quick-and-dirty script, it's rarely good idea to use sys.argv directly to get script arguments. Instead, use a command line argument parser. There are plenty out there for Python that are robust and fairly easy to use.

Here's a simple example using the default argument parser that comes with Python; argparse. The script expects a single argument - a file path.

```<code>import argparse

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('file_path', help='A file path')
    return parser.parse_args()

def main():
    args = get_args()
    if args.file_path:
        with open(args.file_path) as file:
            file.write('Lorem ipsum dolor sit.')
</code>```

Body:
I have been using sys.argv to provide parameters in the command line.

For example, I have a method:

def function(param1, param2):
    # Stuff goes here.

def main():
    ... sys.argv[1] ...
    ... sys.argv[2] ...

if __name__ == '__main__':
main()

Now when I run this code the command will be something like this:

python filename.py param1 param2

The param can be anything, from paths to filenames set as and when required.

My question is how to set a parameter in which you can set a destination to store a file, say a pickle file for example. I would like to know how to do something like this:

python filename.py param1 param2 param3

where param3 is basically the destination of the file to be saved. If there is something like sys where we can provide a destination for a file to be saved using param1 and param2.

Please help. Thanks.

Body:
Unless your just trying to setup a quick-and-dirty script, it's rarely good idea to use sys.argv directly to get script arguments. Instead, use a command line argument parser. There are plenty out there for Python that are robust and fairly easy to use.

Here's a simple example using the default argument parser that comes with Python; argparse. The script expects a single argument - a file path.

import argparse

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('file_path', help='A file path')
    return parser.parse_args()

def main():
    args = get_args()
    if args.file_path:
        with open(args.file_path) as file:
            file.write('Lorem ipsum dolor sit.')


问:
Pattern Matching In java for repeated pattern
I want my string to match a pattern like this +cat,+dog,-name,+cat

So basically it should start with + or - followed by variable name and then ","

So I want to have a regex for the same for matching the string.

Could you please tell the regex for this pattern ?

答:
This regex matches one instance of "+/- plus a variable name":

```<code>[+-]\w+
</code>```

Now, to make it so that it matches multiple instances of the above, separated by commas, change it like this:

```<code>[+-]\w+(,[+-]\w+)*
</code>```

Basically, I added this part:

```<code>(,[+-]\w+)*
</code>```

It is a group that can repeat zero or more times (*), in the group, there is a comma, followed by the first pattern we saw.

Basically, you just need to move the comma to the start of the capture group.

Body:
This regex matches one instance of "+/- plus a variable name":

[+-]\w+

Now, to make it so that it matches multiple instances of the above, separated by commas, change it like this:

[+-]\w+(,[+-]\w+)*

Basically, I added this part:

(,[+-]\w+)*

It is a group that can repeat zero or more times (*), in the group, there is a comma, followed by the first pattern we saw.

Basically, you just need to move the comma to the start of the capture group.


答:
You can create a dictionary of delegates, so your function will look something like:</p>

```<code>private double PerformOperation(OperationEnum operation, double aggregateValue,
                            double sourceValue)
{
    return operators[operation](aggregateValue, sourceValue);
}
</code>```

Title: Can operations be generalized?

Body:
You can create a dictionary of delegates, so your function will look something like:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                            double sourceValue)
{
    return operators[operation](aggregateValue, sourceValue);
}


问:
How can I replace two double quotes with one double quotes using Regex without capturing occurrences of one double quote?
I'm trying to do a replace on a JSON string. Something like this:

```<code>'{"val1":"1","val2":"2"","val3":"","val4":""}'
</code>```

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

```<code>replace(/""/g, '"')
</code>```

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

```<code>replace(/[^:]+"";/g, '"')
</code>```

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

答:
Something like this should work.

const str = '{"val1":"1","val2":"2"","val3":"","val4":""}';
const cleaned = str.replace(/(\"+([^",]*)\"+)/g, (match,quotes,val) => `"${val}"`);
console.log(cleaned);
console.log(JSON.parse(cleaned));```
</div>
</div>
</p>

<p>Basically, it'll match each block of quotes (including extra quotes), then rewrite it to have only one pair of quotes.</p>

<p>Do note: it won't work if your values have commas. That's a limitation to this particular approach. If you need commas in the value, you could use this alternate regex:</p>

```/(\"([^"]*)\"+)/g
```

That one will work for commas, but won't work if you have a double-quote at the start of the string. You'd have to move the + in that case to the first one instead.

Body:
I'm trying to do a replace on a JSON string. Something like this:

'{"val1":"1","val2":"2"","val3":"","val4":""}'

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

replace(/""/g, '"')

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

replace(/[^:]+"";/g, '"')

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

Body:
Something like this should work.

const str = '{"val1":"1","val2":"2"","val3":"","val4":""}';
const cleaned = str.replace(/(\"+([^",]*)\"+)/g, (match,quotes,val) => `"${val}"`);
console.log(cleaned);
console.log(JSON.parse(cleaned));

Basically, it'll match each block of quotes (including extra quotes), then rewrite it to have only one pair of quotes.

Do note: it won't work if your values have commas. That's a limitation to this particular approach. If you need commas in the value, you could use this alternate regex:

/(\"([^"]*)\"+)/g

That one will work for commas, but won't work if you have a double-quote at the start of the string. You'd have to move the + in that case to the first one instead.


问:
aws_access_key_id in aws lambda environment
I'm using boto3 in order to create a presigned post url for s3.

```<code>s3 = boto3.client('s3')
post = s3.generate_presigned_post(
        Bucket=bucket_name,
        Key=f"{userid}.{suffix}"
    )
</code>```

The aws_access_key_id that is being used is incorrect, one of the ways of using the right one is by adding an environment variable through environment variables.

Any idea how can I enforce using the aws access key as defined by the user I've created in IAM ?

Update 1

Policy attached to the IAM role that executes the lambda

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:*"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:AttachNetworkInterface",
                "ec2:CreateNetworkInterface",
                "ec2:DeleteNetworkInterface",
                "ec2:DescribeInstances",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DetachNetworkInterface",
                "ec2:ModifyNetworkInterfaceAttribute",
                "ec2:ResetNetworkInterfaceAttribute"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "kinesis:*"
            ],
            "Resource": "arn:aws:kinesis:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "sns:*"
            ],
            "Resource": "arn:aws:sns:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "sqs:*"
            ],
            "Resource": "arn:aws:sqs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:*"
            ],
            "Resource": "arn:aws:dynamodb:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "route53:*"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

Update 2

Role in IAM

Role configuration in Lambda configuration

答:
You should not use an IAM User for any sort of execution permissions in lambda. Rather, use an IAM role with appropriate policies attached and attach that role to your Lambda function.

Also note that once the role is configured, the access id and secret will be automatically set as environment variables by lambda and Boto will retrieve them without any additional configuration.

Body:
I'm using boto3 in order to create a presigned post url for s3.

s3 = boto3.client('s3')
post = s3.generate_presigned_post(
        Bucket=bucket_name,
        Key=f"{userid}.{suffix}"
    )

The aws_access_key_id that is being used is incorrect, one of the ways of using the right one is by adding an environment variable through environment variables.

Any idea how can I enforce using the aws access key as defined by the user I've created in IAM ?

Update 1

Policy attached to the IAM role that executes the lambda

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:*"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:AttachNetworkInterface",
                "ec2:CreateNetworkInterface",
                "ec2:DeleteNetworkInterface",
                "ec2:DescribeInstances",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DetachNetworkInterface",
                "ec2:ModifyNetworkInterfaceAttribute",
                "ec2:ResetNetworkInterfaceAttribute"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "kinesis:*"
            ],
            "Resource": "arn:aws:kinesis:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "sns:*"
            ],
            "Resource": "arn:aws:sns:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "sqs:*"
            ],
            "Resource": "arn:aws:sqs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:*"
            ],
            "Resource": "arn:aws:dynamodb:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "route53:*"
            ],
            "Resource": "*"
        }
    ]
}

Update 2

Role in IAM

Role configuration in Lambda configuration


问:
how to call methods with multiple arguments
i am trying to learn python. in a method like average below how can call this method without supplying value for a means we only supply values for b.
How will we call such a method.

```<code>def average(a=5 , *b):
    sum=0
    count=0
    print(" b is {0}".format(b))
    for bb in b:
        sum += bb
        count+=1
    av=(sum+a)/(count+1)
    return av

print("average is {0}".format(average(3,5,7,8,9,2)))
</code>```

Here it takes a=3 and the rest as b. How can we call this method without value for a at all.

Can we have the first value as nargs like . If yes how do we supply the value of b.

```<code>def average(*a,b)
</code>```

答:
```<code>def average(*a, b):
    ...
</code>```

Using the syntax above, you must include b by keyword-only:

```<code>average(1,2,3,b=4)
</code>```

If you don't like that, then just unpack inside the function directly like shown below:

```<code>def average(*args):
    *a, b = args
    ...
</code>```

You will need to add handling for the case where args is empty.

Body:
i am trying to learn python. in a method like average below how can call this method without supplying value for a means we only supply values for b.
How will we call such a method.

def average(a=5 , *b):
    sum=0
    count=0
    print(" b is {0}".format(b))
    for bb in b:
        sum += bb
        count+=1
    av=(sum+a)/(count+1)
    return av

print("average is {0}".format(average(3,5,7,8,9,2)))

Here it takes a=3 and the rest as b. How can we call this method without value for a at all.

Can we have the first value as nargs like . If yes how do we supply the value of b.

def average(*a,b)

Body:
def average(*a, b):
    ...

Using the syntax above, you must include b by keyword-only:

average(1,2,3,b=4)

If you don't like that, then just unpack inside the function directly like shown below:

def average(*args):
    *a, b = args
    ...

You will need to add handling for the case where args is empty.


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
Dunno... For me, it was Turbo Pascal 6 that introduced the concept of OOP but I didn't quite get it back then. Then I've learnt C++ and everything immediately became crystal clear. Coming from C++, C# is just seems really straightforward so I couldn't really say that I had an a-ha moment with C# or .NET.

I guess you just have to write code. Lots of code.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: DrJokepu


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

答: They are the same.  You can use Truth Table Generator to test it.  Both these expressions give false only in one case, when A, B and C are false.

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)


问:
Identify the edges of triangles in a network
In a triangle/circular graph of A->B->C. To reach C from A, A->C is shortest path but can also be reached if the path is part of triangle or circular path. Lets say if A->C is broken then C can be reached by A->B->C.I need an indicator saying about a backup paths.

How do I implement this, I tried using different commands in R but couldn't achieve and I am very new to R and igraph.

答:
Use all_simple_paths()

```<code>net <- data.frame(from= c('A', 'B', 'C', 'A'),
                  to = c('B', 'C', 'E', 'C'),
                  stringsAsFactors = F)

net <- igraph::graph_from_data_frame(net)

igraph::all_simple_paths(net, 'A', 'C')
</code>```

igraph is pretty powerful. It is definitely worth spending time and exploring its documentation. Also, Katherine Ognyanova created an AWESOME tutorial that is definitely worth everyone's time.

Body:
Use all_simple_paths()

net <- data.frame(from= c('A', 'B', 'C', 'A'),
                  to = c('B', 'C', 'E', 'C'),
                  stringsAsFactors = F)

net <- igraph::graph_from_data_frame(net)

igraph::all_simple_paths(net, 'A', 'C')

igraph is pretty powerful. It is definitely worth spending time and exploring its documentation. Also, Katherine Ognyanova created an AWESOME tutorial that is definitely worth everyone's time.


问:
Why does this akka-http route test never complete successfully?
I've a simple route and some tests that success individually, but collectively fail with timeout. Any idea why?

```<code>val route = (requestHandler: ActorRef @@ Web) => {
   get {
     pathPrefix("apps") {
       pathEndOrSingleSlash {
         completeWith(implicitly[ToEntityMarshaller[List[String]]]) { callback =>
           requestHandler ! GetAppsRequest(callback)
         }
       } ~ path("stats") {
         completeWith(implicitly[ToEntityMarshaller[List[Stats]]]) { callback =>
           requestHandler ! GetStatsRequest(callback)
         }
       }
     } ~ path("apps" / Segment / "stats") { app =>
       completeWith(implicitly[ToEntityMarshaller[Stats]]) { callback =>
         requestHandler ! GetStatsForOneRequest(app, callback)
       }
     }
   }
 }
</code>```

and tests:

```<code>val testProbe = TestProbe()
val testProbeActor = testProbe.ref
  .taggedWith[Web]

val timeout = 1.minute

"Route" should "respond to get apps request" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  Get("/apps") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetAppsRequest(callback) => {
        callback(k8SProperties.apps)
      }
    }
    entityAs[List[String]] should contain("test")
  }
  testProbe.expectNoMessage(timeout)
}

it should "respond to get stats request for all apps" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  val app = "test"
  Get("/apps/stats") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetStatsRequest(callback) => {
        callback(List(Stats(app, ChronoUnit.SECONDS, Nil)))
      }
      case other => fail(s"Unexpected message $other.")
    }
    entityAs[List[Stats]].size shouldBe (1)
    entityAs[List[Stats]].head.app shouldBe (app)
  }
  testProbe.expectNoMessage(timeout)
}

it should "respond to get stats request for one app" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  val app = "test"
  Get(s"/apps/$app/stats") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetStatsForOneRequest(app, callback) => {
        callback(Stats(app, ChronoUnit.SECONDS, Nil))
      }
      case other => fail(s"Unexpected message $other.")
    }
    entityAs[Stats].app shouldBe (app)
  }
  testProbe.expectNoMessage(timeout)
}
</code>```

Edit:
Opened https://github.com/akka/akka-http/issues/1615

答:
The problem is that you are using a single TestProbe across all three tests.  That TestProbe is a single actor and is therefore receiving messages from all three tests.  If you simply move your test probe creation and config inside the test bodies, it should work as you expect; specifically these two lines:</p>

```<code>val testProbe = TestProbe()
val testProbeActor = testProbe.ref
  .taggedWith[Web]
</code>```

Body:
I've a simple route and some tests that success individually, but collectively fail with timeout. Any idea why?

val route = (requestHandler: ActorRef @@ Web) => {
   get {
     pathPrefix("apps") {
       pathEndOrSingleSlash {
         completeWith(implicitly[ToEntityMarshaller[List[String]]]) { callback =>
           requestHandler ! GetAppsRequest(callback)
         }
       } ~ path("stats") {
         completeWith(implicitly[ToEntityMarshaller[List[Stats]]]) { callback =>
           requestHandler ! GetStatsRequest(callback)
         }
       }
     } ~ path("apps" / Segment / "stats") { app =>
       completeWith(implicitly[ToEntityMarshaller[Stats]]) { callback =>
         requestHandler ! GetStatsForOneRequest(app, callback)
       }
     }
   }
 }

and tests:

val testProbe = TestProbe()
val testProbeActor = testProbe.ref
  .taggedWith[Web]

val timeout = 1.minute

"Route" should "respond to get apps request" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  Get("/apps") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetAppsRequest(callback) => {
        callback(k8SProperties.apps)
      }
    }
    entityAs[List[String]] should contain("test")
  }
  testProbe.expectNoMessage(timeout)
}

it should "respond to get stats request for all apps" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  val app = "test"
  Get("/apps/stats") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetStatsRequest(callback) => {
        callback(List(Stats(app, ChronoUnit.SECONDS, Nil)))
      }
      case other => fail(s"Unexpected message $other.")
    }
    entityAs[List[Stats]].size shouldBe (1)
    entityAs[List[Stats]].head.app shouldBe (app)
  }
  testProbe.expectNoMessage(timeout)
}

it should "respond to get stats request for one app" in {
  implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
  val app = "test"
  Get(s"/apps/$app/stats") ~> route(testProbeActor) ~> check {

    testProbe.receiveOne(timeout) match {
      case GetStatsForOneRequest(app, callback) => {
        callback(Stats(app, ChronoUnit.SECONDS, Nil))
      }
      case other => fail(s"Unexpected message $other.")
    }
    entityAs[Stats].app shouldBe (app)
  }
  testProbe.expectNoMessage(timeout)
}

Edit:
Opened https://github.com/akka/akka-http/issues/1615

Body:
The problem is that you are using a single TestProbe across all three tests.  That TestProbe is a single actor and is therefore receiving messages from all three tests.  If you simply move your test probe creation and config inside the test bodies, it should work as you expect; specifically these two lines:

val testProbe = TestProbe()
val testProbeActor = testProbe.ref
  .taggedWith[Web]


问:
Changing color of EditText in Fragment/Activity
I will change the input Color. How can I do this?
Found nothing on the web. I do not have a xml File. I create the EditText directly in the Fragment.class

答:
Use setTextColor Method</p>

```<code>final EditText inputField = new EditText(getActivity());
inputField.setTextColor(Color.RED);//your Color
or

 inputField.setTextColor(Color.parseColor("#636161"));//your Color code
</code>```

Body:
Use setTextColor Method

final EditText inputField = new EditText(getActivity());
inputField.setTextColor(Color.RED);//your Color
or

 inputField.setTextColor(Color.parseColor("#636161"));//your Color code


问:
Python Pandas: Filtering Against String Works, Against Datetime Fails
How can I filter a Pandas dataframe with a datetime64 value?

With a string elementary value, filtering is possible:

```<code>df = df[df['date_in_string_format'] < '2017-07-01']
</code>```

=> success

With a Series in datetime64 format, I get an error:

```<code>df['date_in_datetime64_format'] = map(pd.to_datetime, \
    df['date_in_string_format'], '%Y-%m-%d')

df = df[df['date_in_datetime64_format'] < pd.datetime(2017,7,1)]
</code>```

=> results in:

```<code>'<' not supported between instances of 'map' and 'datetime.datetime'
</code>```

答:
I did not see why we need  map here

```<code>df=pd.DataFrame({'Date':['2017-01-01','2017-07-19']})
df['Date'] = pd.to_datetime(df['Date'])
df[df['Date'] < pd.datetime(2017,7,1)]

Out[1674]:
        Date
0 2017-01-01
</code>```

Body:
How can I filter a Pandas dataframe with a datetime64 value?

With a string elementary value, filtering is possible:

df = df[df['date_in_string_format'] < '2017-07-01']

=> success

With a Series in datetime64 format, I get an error:

df['date_in_datetime64_format'] = map(pd.to_datetime, \
    df['date_in_string_format'], '%Y-%m-%d')

df = df[df['date_in_datetime64_format'] < pd.datetime(2017,7,1)]

=> results in:

'<' not supported between instances of 'map' and 'datetime.datetime'

Body:
I did not see why we need  map here

df=pd.DataFrame({'Date':['2017-01-01','2017-07-19']})
df['Date'] = pd.to_datetime(df['Date'])
df[df['Date'] < pd.datetime(2017,7,1)]

Out[1674]:
        Date
0 2017-01-01


答: Nope... it's not quite that generalizable, although I wish it was too. :\</p>

Title: Can operations be generalized?

Body:
I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)


问:
Bootstrap Datetimepicker not displaying date in the text field

Developing on ASP.net mvc 5, Bootstrap v3.3.7

In a Form I've a 'Date Of Calibration' field. I'm able to load bootstrap datetimepicker on this field on my Developing & Test machine. It's working fine there, but on the Live server the TextBoxFor date field doesn't show date inside it when the page loads. Once I click the textbox, datetimepicker appear and then the date gets rendered inside it.

I've also confirmed ViewModel does contain the date value when page is being loaded. It's just not getting rendered while page loads, and it only doing it on the production environment.

Any idea what could possibly be the reason

I'm loading Form inside a partial view in BootstrapModal.

```<code> @Html.TextBoxFor(model => model.date_of_calibration, new { id = "date_of_calibration", @class = "form-control" })
</code>```

Loading datetimepicker as.

```<code>$(document).ready(function () {
   $("#date_of_calibration").datepicker({ format: 'DD-MM-YYYY'});}
</code>```

Also loaded the following scripts inside the my partial view

```<code><script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
</code>```

Update

So before I was loading the field in the model as model.date_of_calibration = DateTime.Now; changed it to = DateTime.Now.Date; which uses only the date component of DateTime Instance.

Now the date does show up in the field when the page loads. but its doing it wrong. Interchanging "Date & Month". i.e If the database record has 2017-12-05 00:00:00.000 (i.e. 5th Dec), it show 12-05-2017 (i.e. 12th of May) instead of 05-12-2017.

Now again it's only happening on the live environment.

答:
please try this code on your own html file

<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link href="http://lisenme.com/demo/date_time_pick/css/bootstrap-datetimepicker.min.css" rel="stylesheet">

Inline Datetime Picker

Datetime Picker

      <input size="16" type="text" class="form-control" id="datetime" readonly>

Datetime Picker Auto Close

      <input size="16" type="text" class="form-control" id="datetime2" readonly>

```

Body:
Developing on ASP.net mvc 5, Bootstrap v3.3.7

In a Form I've a 'Date Of Calibration' field. I'm able to load bootstrap datetimepicker on this field on my Developing & Test machine. It's working fine there, but on the Live server the TextBoxFor date field doesn't show date inside it when the page loads. Once I click the textbox, datetimepicker appear and then the date gets rendered inside it.

I've also confirmed ViewModel does contain the date value when page is being loaded. It's just not getting rendered while page loads, and it only doing it on the production environment.

Any idea what could possibly be the reason

I'm loading Form inside a partial view in BootstrapModal.

 @Html.TextBoxFor(model => model.date_of_calibration, new { id = "date_of_calibration", @class = "form-control" })

Loading datetimepicker as.

$(document).ready(function () {
   $("#date_of_calibration").datepicker({ format: 'DD-MM-YYYY'});}

Also loaded the following scripts inside the my partial view

<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />

Update

So before I was loading the field in the model as model.date_of_calibration = DateTime.Now; changed it to = DateTime.Now.Date; which uses only the date component of DateTime Instance.

Now the date does show up in the field when the page loads. but its doing it wrong. Interchanging "Date & Month". i.e If the database record has 2017-12-05 00:00:00.000 (i.e. 5th Dec), it show 12-05-2017 (i.e. 12th of May) instead of 05-12-2017.

Now again it's only happening on the live environment.

Body:
please try this code on your own html file

<!DOCTYPE html>
<html>
  <head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Minified Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link href="http://lisenme.com/demo/date_time_pick/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
    <script src="http://lisenme.com/demo/date_time_pick/js/bootstrap-datetimepicker.min.js"></script>

  </head>
  <body>

    <div class="container">
      <h1>Inline Datetime Picker</h1>
      <div id="datetime4"></div>

      <script type="text/javascript">
        $("#datetime4").datetimepicker();
      </script>

      <h1>Datetime Picker</h1>
      <input size="16" type="text" class="form-control" id="datetime" readonly>

      <script type="text/javascript">
        $("#datetime").datetimepicker({
       format: 'yyyy-mm-dd hh:ii'
        });
      </script>

      <h1>Datetime Picker Auto Close</h1>
      <input size="16" type="text" class="form-control" id="datetime2" readonly>

      <script type="text/javascript">
        $("#datetime2").datetimepicker({
       format: 'yyyy-mm-dd hh:ii',
          autoclose: true
        });
      </script>

    </div>

  </body>

</html>


问:
$state.go ui-routing function ignores custom parameters
I have created a 'go' back option that takes user back to the advSrch screen/state. I pass loadSearchQuery as true if going back.

```<code>  $scope.back = function() {
    $state.go('advSrch', { isDeleted: false, loadSearchQuery: true });
  };
</code>```

However my app always uses the default no matter what.

```<code>    }).state("advSrch",{url:"/advSrch",
    templateUrl: "app/search/advSearch.html",
    controller: "searchCtl",
    params: { isDeleted: null, loadSearchQuery: null },
    data: { authorizedRoles: ['USR']}
</code>```

When I console.log after going back loadSearchQuery is always null. Am I doing something wrong?

答:
$stateParams property already deprecated, in version from 1.0 recommended to use
$transition$ and get get the current transition’s parameters using $transition$.params().

Details on this link

Body:
I have created a 'go' back option that takes user back to the advSrch screen/state. I pass loadSearchQuery as true if going back.

  $scope.back = function() {
    $state.go('advSrch', { isDeleted: false, loadSearchQuery: true });
  };

However my app always uses the default no matter what.

    }).state("advSrch",{url:"/advSrch",
    templateUrl: "app/search/advSearch.html",
    controller: "searchCtl",
    params: { isDeleted: null, loadSearchQuery: null },
    data: { authorizedRoles: ['USR']}

When I console.log after going back loadSearchQuery is always null. Am I doing something wrong?


问:
Passing # character in url with python
I have the following code:

```<code>@app.route('/famcall/Audio/AudioMng_PlayDTMF/<string:output_stream>/<string:dtmf>/<string:duration>/<string:gap>', methods=['GET'])
    def fam_audio_play_dtmf(output_stream, dtmf, duration, gap):
        params = [self.mapAudioOutputStream.business_to_tech(output_stream), dtmf, duration, gap]
        return self.call_fam_function_and_wait_response("AudioMng_PlayDTMF", params)
</code>```

and I want to use the character # in my url because it´s a value that can be used for dtmf. Is there an encode function in python which can help me in this? Or should I forget this scenario?

答: Use urllib.quote (Python 2) or urllib.parse.quote (Python 3) to escape your dtmf value or anything else that might contain reserved characters.</p>

Title: Passing # character in url with python

Body:
I have the following code:

@app.route('/famcall/Audio/AudioMng_PlayDTMF/<string:output_stream>/<string:dtmf>/<string:duration>/<string:gap>', methods=['GET'])
    def fam_audio_play_dtmf(output_stream, dtmf, duration, gap):
        params = [self.mapAudioOutputStream.business_to_tech(output_stream), dtmf, duration, gap]
        return self.call_fam_function_and_wait_response("AudioMng_PlayDTMF", params)

and I want to use the character # in my url because it´s a value that can be used for dtmf. Is there an encode function in python which can help me in this? Or should I forget this scenario?


问:
How to make a button show a table onclick
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Button1" onclick='myfunction();'>
<div id="displaytable" style="visibility: hidden">
  <table id="displaytable" style="display: none; width: 100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

答:
You should change the ID of your input to another ID, and then your function just need to be as below:

```<code>function myfunction()
{
    if (document.getElementById("displaytable").style.display === "none")
        document.getElementById("displaytable").style.display="block";
    else
        document.getElementById("displaytable").style.display="none";
}
</code>```

Body:
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}

<input type="button" value="Button1" onclick='myfunction();'>

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

Body:
You should change the ID of your input to another ID, and then your function just need to be as below:

function myfunction()
{
    if (document.getElementById("displaytable").style.display === "none")
        document.getElementById("displaytable").style.display="block";
    else
        document.getElementById("displaytable").style.display="none";
}


问:
NPM Best Practices for Continuous Integration
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

```<code>$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s
</code>```

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?

答: Schedule a daily job to build a docker container with your dependencies.  Run your CI job in the latest container.  Artifact the CI job's build.</p>

Body:
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?


问:
Can I use grep to extract a single column of a CSV file?
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
```

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

答:
Right Tools For The Job: Using awk or cut

Assuming you want to match the third column against a specific field:

```<code>awk -F';' '$3 ~ /Foo/ { print $0 }' file.txt
</code>```

...will print any line where the third field contains Foo. (Changing print $0 to print $3 would print only that third field).

If you just want to print the third column regardless, use cut: cut -d';' -f3 <file.txt

Wrong Tool For The Job: Using GNU grep

On a system where grep has the -o option, you can chain two instances together -- one to trim everything after the fourth column (and remove lines with less than four columns), another to take only the last remaining column (thus, the fourth):

```<code>str='foo;bar;baz;qux;meh;whatever'
grep -Eo '^[^;]*[;][^;]*[;][^;]*[;][^;]*' <<<"$str" \
  | grep -Eo '[^;]+$'
</code>```

To explain how that works:

^, outside of square brackets, matches only at the beginning of a line.

[^;]* matches any character except ; zero-or-more times.

[;] matches only the character ;.

...thus, each [^;]*[;] in the regex matches a single field, whether or not that field contains text. Putting four of those in the first stage means we're matching only fields, and grep -o tells grep to only emit content it was successfully able to match.

Body:
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

Body:
Right Tools For The Job: Using awk or cut

Assuming you want to match the third column against a specific field:

awk -F';' '$3 ~ /Foo/ { print $0 }' file.txt

...will print any line where the third field contains Foo. (Changing print $0 to print $3 would print only that third field).

If you just want to print the third column regardless, use cut: cut -d';' -f3 <file.txt

Wrong Tool For The Job: Using GNU grep

On a system where grep has the -o option, you can chain two instances together -- one to trim everything after the fourth column (and remove lines with less than four columns), another to take only the last remaining column (thus, the fourth):

str='foo;bar;baz;qux;meh;whatever'
grep -Eo '^[^;]*[;][^;]*[;][^;]*[;][^;]*' <<<"$str" \
  | grep -Eo '[^;]+$'

To explain how that works:

^, outside of square brackets, matches only at the beginning of a line.

[^;]* matches any character except ; zero-or-more times.

[;] matches only the character ;.

...thus, each [^;]*[;] in the regex matches a single field, whether or not that field contains text. Putting four of those in the first stage means we're matching only fields, and grep -o tells grep to only emit content it was successfully able to match.


问:
Discord JS Music bot - .message.member.voiceChannel.join() not working
I am trying to make a music bot in Discord.JS. However, I am getting an error when I debug the code.
Here is the code:

```<code>var channel = message.member.voiceChannel;

        if(!message.guild.voiceConnection) channel.join().then(function(connection){
            play(connection, message);
        });
</code>```

play is a function that I have created higher up in my code.

The error that I am getting is:

```<code>                                        ^
TypeError: Cannot read property 'join' of undefined
at Client.<anonymous> (C:\Users\ryans\Desktop\STATICbot\index.js:112:56)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:293:17)
at WebSocket.onMessage (C:\Users\ryans\Desktop\STATICbot\node_modules\ws\lib\EventTarget.js:99:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
</code>```

I have tried to change member in message.member.voiceChannel to members but that didn't work.

I have also tried to have message.member.voiceChannel outside of a variable and before .join() instead.

Any help would be greatly appreciated, thanks!

答:
So what the error code says is, that the user who sent the message is not in any voice channel, so the bot can't join the channel.

Possible Solutions:

Join a Channel and then send the message.

if channel is not found, then join a preset channel.

Body:
I am trying to make a music bot in Discord.JS. However, I am getting an error when I debug the code.
Here is the code:

var channel = message.member.voiceChannel;

        if(!message.guild.voiceConnection) channel.join().then(function(connection){
            play(connection, message);
        });

play is a function that I have created higher up in my code.

The error that I am getting is:

                                        ^
TypeError: Cannot read property 'join' of undefined
at Client.<anonymous> (C:\Users\ryans\Desktop\STATICbot\index.js:112:56)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (C:\Users\ryans\Desktop\STATICbot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:293:17)
at WebSocket.onMessage (C:\Users\ryans\Desktop\STATICbot\node_modules\ws\lib\EventTarget.js:99:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)

I have tried to change member in message.member.voiceChannel to members but that didn't work.

I have also tried to have message.member.voiceChannel outside of a variable and before .join() instead.

Any help would be greatly appreciated, thanks!


问:
Android - Multiple appWidgets playing different sounds
I'm writing an android soundboard which allow the user to create multiple desktop widgets, one for each sound. I'm using an activity for the user to choose which sound he wants to create the widget for. For each widget created I store a  shared preference in the form of

```<code>key => "WIDGET_FILENAME_"+widgetId, value=> fileName
</code>```

To play the sounds, I did override the onRecieve method on the widgetProvider class. When the desktop widget is clicked, it triggers a broadcast to this method, which gets the widget id from the intent and then loads the shared preference associated with the widget:

```<code>int appWidgetId =  intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                                     AppWidgetManager.INVALID_APPWIDGET_ID);
</code>```

The problem is: The widgetId is always the same, no matter which widget is clicked, causing the same sound to be played.

Any idea or guidance on this?

答:
I had the same problem and solved it like this:

In your AppWidgetProviderClass, declare your Intent as follows:

```<code>Intent intent = new Intent(context, YourActivity.class)
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
</code>```

...and PendingIntent

```<code>PendingIntent pi = PendingIntent.getActivity(context, appWidgetId, intent,
                                             PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

In the Activity class, after getting the appWidgetId you want to update:

```<code>int currentWidgetId = this.getIntent().getIntExtra(
       AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
</code>```

...you can use a function similar to this one:

```<code>private void updateWidgetView() {
    views = new RemoteViews(YourWidget.class.getPackage().getName(),
                            R.layout.main_widget);
    mgr = AppWidgetManager.getInstance(this);
    views.setTextViewText(R.id.some_text_view, someText);
    // Tell the AppWidgetManager to perform an update on the current App Widget
    mgr.updateAppWidget(currentWidgetId, views);
}
</code>```

Body:
I'm writing an android soundboard which allow the user to create multiple desktop widgets, one for each sound. I'm using an activity for the user to choose which sound he wants to create the widget for. For each widget created I store a  shared preference in the form of

key => "WIDGET_FILENAME_"+widgetId, value=> fileName

To play the sounds, I did override the onRecieve method on the widgetProvider class. When the desktop widget is clicked, it triggers a broadcast to this method, which gets the widget id from the intent and then loads the shared preference associated with the widget:

int appWidgetId =  intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                                     AppWidgetManager.INVALID_APPWIDGET_ID);

The problem is: The widgetId is always the same, no matter which widget is clicked, causing the same sound to be played.

Any idea or guidance on this?

Body:
I had the same problem and solved it like this:

In your AppWidgetProviderClass, declare your Intent as follows:

Intent intent = new Intent(context, YourActivity.class)
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

...and PendingIntent

PendingIntent pi = PendingIntent.getActivity(context, appWidgetId, intent,
                                             PendingIntent.FLAG_UPDATE_CURRENT);

In the Activity class, after getting the appWidgetId you want to update:

int currentWidgetId = this.getIntent().getIntExtra(
       AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

...you can use a function similar to this one:

private void updateWidgetView() {
    views = new RemoteViews(YourWidget.class.getPackage().getName(),
                            R.layout.main_widget);
    mgr = AppWidgetManager.getInstance(this);
    views.setTextViewText(R.id.some_text_view, someText);
    // Tell the AppWidgetManager to perform an update on the current App Widget
    mgr.updateAppWidget(currentWidgetId, views);
}


问:
Can this be refactored to use generic functional principles?
A comparator function ascending accepts two arguments - a and b. It must return an integer comparing the two.

I have a list that I want to sort by name, so I wrote the following functions.

Is there a functional idiom I can use to combine these two functions, rather than having byName take responsibility for composing the resulting function?

```<code>const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i.get('name');
const useTogether = (...fns) => ...; // is there an idiomatic function like this?

// usage
items.sort(useTogether(byName(ascending)));
</code>```

答:
I'm not sure if it satisfies what you're looking for, but here is one possible formulation of your useTogether (with a somewhat different signature) that does WORK. I'm not aware of a standard function with precisely that effect.

const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i['name'];
const useTogether = (selector, consumer) => (...fnArgs) => consumer(...fnArgs.map(selector));

var items = [{ name: "C" }, { name: "A" }, { name: "B" }];

console.log(
  items.sort(useTogether(byName, ascending))
)```

Body:
A comparator function ascending accepts two arguments - a and b. It must return an integer comparing the two.

I have a list that I want to sort by name, so I wrote the following functions.

Is there a functional idiom I can use to combine these two functions, rather than having byName take responsibility for composing the resulting function?

const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i.get('name');
const useTogether = (...fns) => ...; // is there an idiomatic function like this?

// usage
items.sort(useTogether(byName(ascending)));


问:
Branch.io implement referral system
I'm trying to implement branch.io referral system in my game.

I have some questions about branch.io

It is mandatory to  identify users on log in and log out, or if I don't want branch system will take care of this?

Before rewarding user in onStateChanged every time I need to check changed to be true ?

It is mandatory to set credits balance(on first start) and then use redeemRewards ?

How to implement own Filter after adding in reward rule and filter in dashboard  ?

My problem is that onStateChanged call me every time and on every device(referring and referred acting users), even my rule in dashboard is only  Referred acting user and even I add custom filter in dashboard

答:
Aaron from Branch.io here

1. It is mandatory to identify users on log in and log out, or if I don't want branch system will take care of this?
It's mandatory to identify the users if you want Branch to merge identities, otherwise random IDs may be tied to each referrer and referree since we don't merge them automatically. To acknowledge the referral and merge identities, you must call setIdentity() before you create a link in order to the referring users' identity to link itself. Once a referred user goes through the install process, you must call setIdentity() again before you trigger an event that triggers the Reward Rule for the referree.

2. Before rewarding user in onStateChanged every time I need to check changed to be true ? If you are using onStateChanged to track the state of the referral and sign up, then yes you'd likely have to check if it's true to trigger the Reward Rule at that time. This will prevent the Reward Rule from triggering each time.

3. Is it mandatory to set credits balance(on first start) and then use redeemRewards ? No, it is not mandatory to set the credit balance on first start. Every identity will start off with a credit balance of zero and will increment or decrement only on redemption or the triggering of Reward Rules.

4. How to implement own Filter after adding in reward rule and filter in dashboard ? You definitely can implement filters on your Reward Rules. You can use the same filter parameters as you do for our webhooks system which you can find in
the documentation here.

We highly recommend you set your Reward Rules to trigger on custom events and not installs and opens to avoid the unwanted merging of identities. You can always find more documentation on our referral mechanism here.

Title: Branch.io implement referral system


问:
Problem with virtualenv in Mac OS X
I've installed virtualenv via pip and get this error after creating a new environment:

```<code>selenium:~ auser$ virtualenv new
New python executable in new/bin/python
ERROR: The executable new/bin/python is not functioning
ERROR: It thinks sys.prefix is u'/System/Library/Frameworks/Python.framework/    Versions/2.6' (should be '/Users/user/new')
ERROR: virtualenv is not compatible with this system or executable
</code>```

In my environment:

```<code>PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
PATH=/System/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
</code>```

How can I repair this?

Thanks.

答:
I also had this problem, and I tried the following method which worked for me:

```<code>conda install virtualenv
</code>```

virtualenv --system-site-packages /anaconda/envs/tensorflow (here envs keeps all the virtual environments made by user)

```<code>source /anaconda/envs/tensorflow/bin/activate
</code>```

Hope it's helpful.

Title: Problem with virtualenv in Mac OS X

Body:
I've installed virtualenv via pip and get this error after creating a new environment:

selenium:~ auser$ virtualenv new
New python executable in new/bin/python
ERROR: The executable new/bin/python is not functioning
ERROR: It thinks sys.prefix is u'/System/Library/Frameworks/Python.framework/    Versions/2.6' (should be '/Users/user/new')
ERROR: virtualenv is not compatible with this system or executable

In my environment:

PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
PATH=/System/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

How can I repair this?

Thanks.

Body:
I also had this problem, and I tried the following method which worked for me:

conda install virtualenv

virtualenv --system-site-packages /anaconda/envs/tensorflow (here envs keeps all the virtual environments made by user)

source /anaconda/envs/tensorflow/bin/activate

Hope it's helpful.


问:
Webpack: include specific file instead of package.json specified?
I have a webpack configuration:

```<code>var path = require("path");

module.exports = {
  entry: {
    app: [
      './src/index.js'
    ]
  },

  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: '[name].js',
  },

  module: {
    rules: [
      {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
        ]
      },
      {
        test:    /\.js$/,
        exclude: /node_modules/,
      },
      {
        test:    /\.html$/,
        exclude: /node_modules/,
        loader:  'file-loader?name=[name].[ext]',
      },
      {
        test:    /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        loader:  'elm-webpack-loader?verbose=true&warn=true',
          options: {debug: true, warn: true},
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
    ],

    noParse: /\.elm$/,
  },

  devServer: {
    inline: true,
    stats: { colors: true },
  },

};
</code>```

I have a few questions:

According to me the above config says that it should not be looking
for js files in node_modules. However it is still bundling
./node_modules/dexie/dist/dexie.es.js when I call require ("dexie"). (I am just doing this to experiment and understand webpack).

I would rather like to call dexie.js instead of dexie.es.js. How do
I make this happen. I know I can set the  mainFields property.
However how do I do this on a prelibrary basis instead of globally.

答:
To your first question please see here. It has already been answered.
No matter what you exclude in your loaders config, the file will be bundled unless you define it as external in your config.

To your second question, you can just require the other file with

```<code>require('dexie/dexie.js')
</code>```

When you just write require('dexie'), webpack will look in your node_modules folder for a folder named 'dexie', read the package.json and resolve the file described by the module property. This is described here.

For more info, please read the webpack docs. They are excellent.

Body:
I have a webpack configuration:

var path = require("path");

module.exports = {
  entry: {
    app: [
      './src/index.js'
    ]
  },

  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: '[name].js',
  },

  module: {
    rules: [
      {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
        ]
      },
      {
        test:    /\.js$/,
        exclude: /node_modules/,
      },
      {
        test:    /\.html$/,
        exclude: /node_modules/,
        loader:  'file-loader?name=[name].[ext]',
      },
      {
        test:    /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        loader:  'elm-webpack-loader?verbose=true&warn=true',
          options: {debug: true, warn: true},
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
    ],

    noParse: /\.elm$/,
  },

  devServer: {
    inline: true,
    stats: { colors: true },
  },

};

I have a few questions:

According to me the above config says that it should not be looking
for js files in node_modules. However it is still bundling
./node_modules/dexie/dist/dexie.es.js when I call require ("dexie"). (I am just doing this to experiment and understand webpack).

I would rather like to call dexie.js instead of dexie.es.js. How do
I make this happen. I know I can set the  mainFields property.
However how do I do this on a prelibrary basis instead of globally.

Body:
To your first question please see here. It has already been answered.
No matter what you exclude in your loaders config, the file will be bundled unless you define it as external in your config.

To your second question, you can just require the other file with

require('dexie/dexie.js')

When you just write require('dexie'), webpack will look in your node_modules folder for a folder named 'dexie', read the package.json and resolve the file described by the module property. This is described here.

For more info, please read the webpack docs. They are excellent.


问:
What's wrong with using setter injection for an Android ViewModel vs Implementing and injecting a ViewModel.Factory?
I have been struggling with getting a Dagger singleton injected into an android component (Service) and a ViewModel.

See this question as a reference.
I have not found a good example of how to simply inject a field in a Service and a field in a ViewModel with the same object.  If there is a simple solution to that I would love to see it.

I found some questions, here and here, that have answers that go down a path of implementing ViewModel.Factory and then injecting dependencies into the constructor of a ViewModel subclass that has dependencies via the create method.

My question is. Are there any serious issues with just injecting the object in to the Activity (and the Service) and then using a setter to inject the object into the ViewModel after it has been retrieved?  For example.

```<code> class MainActivity : AppCompatActivity() {

    @Inject lateinit var messageBus: MessageBus // "thing" I want in the ViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        // get the ViewModel
        val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
        // inject the "thing" via a setter
        viewModel.messageBus = messageBus
    }
}
</code>```

In the view MainViewModel class I could check to see if the value has been already be set, and only set it if it's null.

```<code>class MainViewModel: ViewModel() {

    var messageBus: MessageBus? = null
    set(value) {
        if (field == null) {
            field = value
            // do initialization stuff
        }
    }
}
</code>```

答: I see it as a little hack, but not a harmful hack. I like the idea of providing the ViewModelFactory using dagger along with all dependencies necessary for it to function and then injecting that into the activity so you can pass it in to the of(FragmentActivity activity, ViewModelProvider.Factory factory) method. It avoids mutability on that property.

Body:
I have been struggling with getting a Dagger singleton injected into an android component (Service) and a ViewModel.

See this question as a reference.
I have not found a good example of how to simply inject a field in a Service and a field in a ViewModel with the same object.  If there is a simple solution to that I would love to see it.

I found some questions, here and here, that have answers that go down a path of implementing ViewModel.Factory and then injecting dependencies into the constructor of a ViewModel subclass that has dependencies via the create method.

My question is. Are there any serious issues with just injecting the object in to the Activity (and the Service) and then using a setter to inject the object into the ViewModel after it has been retrieved?  For example.

 class MainActivity : AppCompatActivity() {

    @Inject lateinit var messageBus: MessageBus // "thing" I want in the ViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        // get the ViewModel
        val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
        // inject the "thing" via a setter
        viewModel.messageBus = messageBus
    }
}

In the view MainViewModel class I could check to see if the value has been already be set, and only set it if it's null.

class MainViewModel: ViewModel() {

    var messageBus: MessageBus? = null
    set(value) {
        if (field == null) {
            field = value
            // do initialization stuff
        }
    }
}


问:
Script editor opening folder and questioning to delete it
I want the program to open a folder and then display a text to delete this folder, but I can't get it working. Any help is appreciated.</p>

```<code>    on opening folder theResponse
    tell application "Finder"
    set theName to name of theResponse
    activate
    display alert "Attention!" message "The folder" & theName & " was opened."
    set question to display dialog "Do you want to delete this folder?" buttons {"No", "Yes"} default button "No"
    set answer to button returned of question
    if answer is equal to "Yes" then
    set sourceFolder to theName
    move sourceFolder to the trash
        end tell
    end opening folder
</code>```

答:
theName is the folder name – a string – for example Pictures or Movies. You need the reference to the folder (Finder specifier or alias) which is theResponse

Delete

```<code>set sourceFolder to theName
</code>```

and change

```<code>move theResponse to the trash
</code>```

Body:
I want the program to open a folder and then display a text to delete this folder, but I can't get it working. Any help is appreciated.

    on opening folder theResponse
    tell application "Finder"
    set theName to name of theResponse
    activate
    display alert "Attention!" message "The folder" & theName & " was opened."
    set question to display dialog "Do you want to delete this folder?" buttons {"No", "Yes"} default button "No"
    set answer to button returned of question
    if answer is equal to "Yes" then
    set sourceFolder to theName
    move sourceFolder to the trash
        end tell
    end opening folder

Body:
theName is the folder name – a string – for example Pictures or Movies. You need the reference to the folder (Finder specifier or alias) which is theResponse

Delete

set sourceFolder to theName

and change

move theResponse to the trash