问:
Cisco Webex - new attendeeSendVideo option
Aparently Cisco Webex has upgraded their APIs and now the service CreateTrainingSession has a new option attendeeSendVideo, that option turns ON attendees web cameras by default.

The documentation does not mention where to put the new option attendeeSendVideo in the XML.

Wondering if this is new option goes in the body or header as a child property.

XML:

webex_request.body = "<?xml version=\"1.0\"
encoding=\"UTF-8\"?>
<serv:message
  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
  xmlns:serv=\"http://www.webex.com/schemas/2002/06/service\">

  <securityContext>
    <webExID>#{webExId}</webExID>
    <password>#{ENV['WEB_EX_PWD']}</password>
    <siteID>#{ENV['WEB_EX_SITE_ID']}</siteID>
  </securityContext>

  <bodyContent
    xsi:type=\"java:com.webex.service.binding.training.CreateTrainingSession\">
    <schedule>
      <duration>#{duration}</duration>
    </schedule>
    <metaData>
      <confName>#{title}</confName>
    </metaData>
  </bodyContent>

</serv:message>"
```

答:
The documentation says to add extra options in here enableOptions

https://developer.cisco.com/docs/webex-xml-api-reference-guide/#!createtrainingsession/createtrainingsession

```<code><bodyContent
  xsi:type=\"java:com.webex.service.binding.training.CreateTrainingSession\">
  <schedule>
    <duration>#{duration}</duration>
  </schedule>
  <metaData>
    <confName>#{title}</confName>
  </metaData>
  <enableOptions>
    <attendeeSendVideo>true</attendeeSendVideo>
  </enableOptions>
</bodyContent>
</code>```

Body:
The documentation says to add extra options in here enableOptions

https://developer.cisco.com/docs/webex-xml-api-reference-guide/#!createtrainingsession/createtrainingsession

<bodyContent
  xsi:type=\"java:com.webex.service.binding.training.CreateTrainingSession\">
  <schedule>
    <duration>#{duration}</duration>
  </schedule>
  <metaData>
    <confName>#{title}</confName>
  </metaData>
  <enableOptions>
    <attendeeSendVideo>true</attendeeSendVideo>
  </enableOptions>
</bodyContent>


来源: stackexchange

问:
Transfer Learning on MNIST: wrong labels error
So I trained a perceptron in tensorflow on the MNIST dataset but only the digits 0 through 4. Then I made a new model with all the same layers and weights but with a new output layer also with 5 output nodes. I want to train this new model to classify the digits 5 to 9.

I generated a new x_train and y_train with only the digits 5 to 9, and ran

transfer_model.fit(x_train[train_filter],y_train[train_filter], epoch=5)

where train_filter is defined as np.where(np.logical_and(x_train<=5,x_train>=9)).

At the very first step of training, I get this error:

InvalidArgumentError:  Received a label value of 9 which is outside the valid range of [0, 5).  Label values: 5 9 7 8 9 8 7 6 8 7 6 9 5 5 8 7 6 9 9 7 6 7 6 8 7 7 9 7 6 8 5 6

This makes sense because I originally trained the network to classify in the range [0,5), but now I want to do the range [5,10). Did I miss a step here? I'm not sure what I'm missing... How do I define what each output neuron corresponds to?

Here is my model summary:

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_7 (Flatten)          (None, 784)               0
_________________________________________________________________
dense_49 (Dense)             (None, 100)               78500
_________________________________________________________________
batch_normalization_10 (Batc (None, 100)               400
_________________________________________________________________
dropout_5 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_50 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_11 (Batc (None, 100)               400
_________________________________________________________________
dropout_6 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_51 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_12 (Batc (None, 100)               400
_________________________________________________________________
dropout_7 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_52 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_13 (Batc (None, 100)               400
_________________________________________________________________
dropout_8 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_53 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_14 (Batc (None, 100)               400
_________________________________________________________________
dropout_9 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_55 (Dense)             (None, 5)                 505
=================================================================
Total params: 121,405
Trainable params: 505
Non-trainable params: 120,900
_________________________________________________________________
</code>```

答: You need to map 5-9 to 0-4.  Class labels are probably done via one hot encoding, you have 5 unique labels, so it only needs a vector of length 5 to represent it.  But since label is 5-9 its going to be out of range.  You do not need to adjust model, just add a map to the label outputs. </p>

ContentLicense: CC BY-SA 4.0

Body:
So I trained a perceptron in tensorflow on the MNIST dataset but only the digits 0 through 4. Then I made a new model with all the same layers and weights but with a new output layer also with 5 output nodes. I want to train this new model to classify the digits 5 to 9.

I generated a new x_train and y_train with only the digits 5 to 9, and ran

transfer_model.fit(x_train[train_filter],y_train[train_filter], epoch=5)

where train_filter is defined as np.where(np.logical_and(x_train<=5,x_train>=9)).

At the very first step of training, I get this error:

InvalidArgumentError:  Received a label value of 9 which is outside the valid range of [0, 5).  Label values: 5 9 7 8 9 8 7 6 8 7 6 9 5 5 8 7 6 9 9 7 6 7 6 8 7 7 9 7 6 8 5 6

This makes sense because I originally trained the network to classify in the range [0,5), but now I want to do the range [5,10). Did I miss a step here? I'm not sure what I'm missing... How do I define what each output neuron corresponds to?

Here is my model summary:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_7 (Flatten)          (None, 784)               0
_________________________________________________________________
dense_49 (Dense)             (None, 100)               78500
_________________________________________________________________
batch_normalization_10 (Batc (None, 100)               400
_________________________________________________________________
dropout_5 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_50 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_11 (Batc (None, 100)               400
_________________________________________________________________
dropout_6 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_51 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_12 (Batc (None, 100)               400
_________________________________________________________________
dropout_7 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_52 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_13 (Batc (None, 100)               400
_________________________________________________________________
dropout_8 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_53 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_14 (Batc (None, 100)               400
_________________________________________________________________
dropout_9 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_55 (Dense)             (None, 5)                 505
=================================================================
Total params: 121,405
Trainable params: 505
Non-trainable params: 120,900
_________________________________________________________________


问:
Vuelidate Issues with 'this' reference in a requireif
I have a vuejs component that uses vuelidate. Here are my validations:

```<code> validations: {
     invoice: {
         dueDate: {
             required,
         },
         tax: {
             required: requiredIf(function () {
                 return this.invoice.taxable;
             }),
        }
    },
</code>```

I have a property called 'invoice' that has a property taxable (boolean) so I need to require the tax field if this property es set to true, but for some reason 'this' is 'undefined' at this moment. I've also tried with the arrow function, same result. I've used this in a vuejs instance in a js file but for some reason when I moved to a separate component it's not working. What am I doing wrong? Thanks in advance!

答:
As it was suggested on by ssc-hrep it turns out that invoice is a nested model that should be passed as argument to the function:</p>

```<code>validations: {
        invoice: {
            dueDate: {
                required,
            },
            tax: {
                required: requiredIf((invoice) => {
                    return invoice.taxable;
                }),
            }
        },
</code>```

Body:
I have a vuejs component that uses vuelidate. Here are my validations:

 validations: {
     invoice: {
         dueDate: {
             required,
         },
         tax: {
             required: requiredIf(function () {
                 return this.invoice.taxable;
             }),
        }
    },

I have a property called 'invoice' that has a property taxable (boolean) so I need to require the tax field if this property es set to true, but for some reason 'this' is 'undefined' at this moment. I've also tried with the arrow function, same result. I've used this in a vuejs instance in a js file but for some reason when I moved to a separate component it's not working. What am I doing wrong? Thanks in advance!

Body:
As it was suggested on by ssc-hrep it turns out that invoice is a nested model that should be passed as argument to the function:

validations: {
        invoice: {
            dueDate: {
                required,
            },
            tax: {
                required: requiredIf((invoice) => {
                    return invoice.taxable;
                }),
            }
        },


问:
Problem with using printf in OpenCL kernel
I use OpenCL 2.0 on AMD. The code is pretty simple. If I use 1 printf, the work is good. But if i add a second printf, then there will be crooked data.
My Code in host C++:

```<code>cl_int errcode;
// Get available platforms
vector<Platform> platforms;
Platform::get(&platforms);
// Select the default platform and create a context using this platform and the GPU
cl_context_properties cps[3] = {
    CL_CONTEXT_PLATFORM,
    (cl_context_properties)(platforms[0])(),
    0
};
Context context(CL_DEVICE_TYPE_GPU, cps);

vector<Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

CommandQueue queue = CommandQueue(context, devices[0]);

// Read source file
string name;
name += "CalcN.cl";
std::ifstream sourceFile(name);
std::string sourceCode(
    std::istreambuf_iterator<char>(sourceFile),
    (std::istreambuf_iterator<char>()));
Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length() + 1));

Program program = Program(context, source);

errcode = program.build(devices);
if (errcode != CL_SUCCESS)
{
    cout << "There were error during build kernel code. Please, check program code. Errcode = " << errcode << "\n";
    cout << "BUILD LOG: " + program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) + "\n";
    getchar();
}

// Make kernel
Kernel kernel(program, "Optimization");

NDRange global(1);
queue.enqueueNDRangeKernel(kernel, 0, global);
</code>```

My Code in kernel:

```<code>__kernel void Optimization()
{
   for(int i = 0;i<100;i++)
   {
       printf("%d",i);
       printf("%d",i);
   }
}
</code>```

Console with One printf

And console with Two printf:

I’ve already asked about this problem more than once, but no one knows.

答: The problem was with the video card drivers. Today they released an update that fixes this bug.</p>

Body:
I use OpenCL 2.0 on AMD. The code is pretty simple. If I use 1 printf, the work is good. But if i add a second printf, then there will be crooked data.
My Code in host C++:

cl_int errcode;
// Get available platforms
vector<Platform> platforms;
Platform::get(&platforms);
// Select the default platform and create a context using this platform and the GPU
cl_context_properties cps[3] = {
    CL_CONTEXT_PLATFORM,
    (cl_context_properties)(platforms[0])(),
    0
};
Context context(CL_DEVICE_TYPE_GPU, cps);

vector<Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

CommandQueue queue = CommandQueue(context, devices[0]);

// Read source file
string name;
name += "CalcN.cl";
std::ifstream sourceFile(name);
std::string sourceCode(
    std::istreambuf_iterator<char>(sourceFile),
    (std::istreambuf_iterator<char>()));
Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length() + 1));

Program program = Program(context, source);

errcode = program.build(devices);
if (errcode != CL_SUCCESS)
{
    cout << "There were error during build kernel code. Please, check program code. Errcode = " << errcode << "\n";
    cout << "BUILD LOG: " + program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) + "\n";
    getchar();
}

// Make kernel
Kernel kernel(program, "Optimization");

NDRange global(1);
queue.enqueueNDRangeKernel(kernel, 0, global);

My Code in kernel:

__kernel void Optimization()
{
   for(int i = 0;i<100;i++)
   {
       printf("%d",i);
       printf("%d",i);
   }
}

Console with One printf

And console with Two printf:

I’ve already asked about this problem more than once, but no one knows.


Title: How can I reassign multiple MultiIndex columns at once in pandas?

Body:
Given two versions of the same dataset, one stacked and the other not.

>>> a = pandas_datareader.DataReader(["MSFT", "AAPL"], "yahoo")
>>> a
Attributes   Adj Close                   Close                    High                     Low                    Open                  Volume
Symbols           MSFT        AAPL        MSFT        AAPL        MSFT        AAPL        MSFT        AAPL        MSFT        AAPL        MSFT        AAPL
Date
2015-06-01   42.744289  120.306801   47.230000  130.539993   47.770000  131.389999   46.619999  130.050003   47.060001  130.279999  28837300.0  32112800.0
2015-06-02   42.463726  119.772255   46.919998  129.960007   47.349998  130.660004   46.619999  129.320007   46.930000  129.860001  21498300.0  33667600.0
2015-06-03   42.400375  119.919716   46.849998  130.119995   47.740002  130.940002   46.820000  129.899994   47.369999  130.660004  28002200.0  30983500.0
2015-06-04   41.956924  119.219307   46.360001  129.360001   47.160000  130.580002   46.200001  128.910004   46.790001  129.580002  27745500.0  38450100.0
2015-06-05   41.757805  118.564957   46.139999  128.649994   46.520000  129.690002   45.840000  128.360001   46.310001  129.500000  25438100.0  35626800.0
...                ...         ...         ...         ...         ...         ...         ...         ...         ...         ...         ...         ...
2020-05-22  183.509995  318.890015  183.509995  318.890015  184.460007  319.230011  182.539993  315.350006  183.190002  315.769989  20826900.0  20450800.0
2020-05-26  181.570007  316.730011  181.570007  316.730011  186.500000  324.239990  181.100006  316.500000  186.339996  323.500000  36073600.0  31380500.0
2020-05-27  181.809998  318.109985  181.809998  318.109985  181.990005  318.709991  176.600006  313.089996  180.199997  316.140015  39517100.0  28236300.0
2020-05-28  181.399994  318.250000  181.399994  318.250000  184.149994  323.440002  180.380005  315.630005  180.740005  316.769989  33810200.0  33390200.0
2020-05-29  183.250000  317.940002  183.250000  317.940002  184.270004  321.149994  180.410004  316.470001  182.729996  319.250000  42130400.0  38383100.0

>>> b = a.stack()
>>> b
Attributes           Adj Close       Close        High         Low        Open      Volume
Date       Symbols
2015-06-01 MSFT      42.744289   47.230000   47.770000   46.619999   47.060001  28837300.0
           AAPL     120.306801  130.539993  131.389999  130.050003  130.279999  32112800.0
2015-06-02 MSFT      42.463726   46.919998   47.349998   46.619999   46.930000  21498300.0
           AAPL     119.772255  129.960007  130.660004  129.320007  129.860001  33667600.0
2015-06-03 MSFT      42.400375   46.849998   47.740002   46.820000   47.369999  28002200.0
...                        ...         ...         ...         ...         ...         ...
2020-05-26 AAPL     316.730011  316.730011  324.239990  316.500000  323.500000  31380500.0
2020-05-27 MSFT     181.809998  181.809998  181.990005  176.600006  180.199997  39492600.0
           AAPL     318.109985  318.109985  318.709991  313.089996  316.140015  28211100.0
2020-05-28 MSFT     181.580002  181.580002  182.470001  180.389999  180.740005   9760951.0
           AAPL     319.850006  319.850006  321.070007  315.630005  316.769989  10119124.0

I'm trying to get a couple of columns from a, transform them and reassign them to the dataset. This works perfectly with b.

>>> b[["Close", "High"]] = b[["Close", "High"]].pct_change().fillna(0)
>>> b
Attributes           Adj Close     Close      High         Low        Open      Volume
Date       Symbols
2015-06-01 MSFT      42.744289  0.000000  0.000000   46.619999   47.060001  28837300.0
           AAPL     120.306801  1.763921  1.750471  130.050003  130.279999  32112800.0
2015-06-02 MSFT      42.463726 -0.640570 -0.639623   46.619999   46.930000  21498300.0
           AAPL     119.772255  1.769821  1.759451  129.320007  129.860001  33667600.0
2015-06-03 MSFT      42.400375 -0.639504 -0.634624   46.820000   47.369999  28002200.0
...                        ...       ...       ...         ...         ...         ...
2020-05-26 AAPL     316.730011  0.744396  0.738552  316.500000  323.500000  31380500.0
2020-05-27 MSFT     181.809998 -0.425978 -0.438718  176.600006  180.199997  39492600.0
           AAPL     318.109985  0.749684  0.751250  313.089996  316.140015  28211100.0
2020-05-28 MSFT     181.580002 -0.429191 -0.427473  180.389999  180.740005   9760951.0
           AAPL     319.850006  0.761483  0.759577  315.630005  316.769989  10119124.0

[2516 rows x 6 columns]

But the same doesn't work for a.

>>> a[["Close", "High"]] = a[["Close", "High"]].pct_change().fillna(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/renatomz/.local/lib/python3.8/site-packages/pandas/core/frame.py", line 2935, in __setitem__
    self._setitem_array(key, value)
  File "/home/renatomz/.local/lib/python3.8/site-packages/pandas/core/frame.py", line 2961, in _setitem_array
    raise ValueError("Columns must be same length as key")
ValueError: Columns must be same length as key

This is perfectly possible if I where to do it column by column. I'm using a for loop as a temporary solution, but it seems inefficient and unclean to me.

>>> a["Close"] = a["Close"].pct_change().fillna(0)
>>> a
Attributes   Adj Close                 Close                  High                     Low                    Open                  Volume
Symbols           MSFT        AAPL      MSFT      AAPL        MSFT        AAPL        MSFT        AAPL        MSFT        AAPL        MSFT        AAPL
Date
2015-06-01   42.744289  120.306801  0.000000  0.000000   47.770000  131.389999   46.619999  130.050003   47.060001  130.279999  28837300.0  32112800.0
2015-06-02   42.463726  119.772255 -0.006564 -0.004443   47.349998  130.660004   46.619999  129.320007   46.930000  129.860001  21498300.0  33667600.0
2015-06-03   42.400375  119.919716 -0.001492  0.001231   47.740002  130.940002   46.820000  129.899994   47.369999  130.660004  28002200.0  30983500.0
2015-06-04   41.956924  119.219307 -0.010459 -0.005841   47.160000  130.580002   46.200001  128.910004   46.790001  129.580002  27745500.0  38450100.0
2015-06-05   41.757805  118.564957 -0.004745 -0.005489   46.520000  129.690002   45.840000  128.360001   46.310001  129.500000  25438100.0  35626800.0
...                ...         ...       ...       ...         ...         ...         ...         ...         ...         ...         ...         ...
2020-05-21  183.429993  316.850006 -0.012011 -0.007455  186.669998  320.890015  183.289993  315.869995  185.399994  318.660004  29119500.0  25672200.0
2020-05-22  183.509995  318.890015  0.000436  0.006438  184.460007  319.230011  182.539993  315.350006  183.190002  315.769989  20826900.0  20450800.0
2020-05-26  181.570007  316.730011 -0.010572 -0.006774  186.500000  324.239990  181.100006  316.500000  186.339996  323.500000  36073600.0  31380500.0
2020-05-27  181.809998  318.109985  0.001322  0.004357  181.990005  318.709991  176.600006  313.089996  180.199997  316.140015  39492600.0  28211100.0
2020-05-28  183.561005  322.510010  0.009631  0.013832  183.820007  323.000000  180.389999  315.630005  180.740005  316.769989  15009134.0  16107365.0

I'm writing this as part of a program that should be agnostic to whether columns are a MultiIndex or not, is there any cleaner/faster way I could do that without looping over the columns?

Body:
You can get a multi-index and adapt with it.

a[["Close", "High"]].columns

MultiIndex([('Close', 'MSFT'),
            ('Close', 'AAPL'),
            ( 'High', 'MSFT'),
            ( 'High', 'AAPL')],
           names=['Attributes', 'Symbols'])

a[[('Close', 'MSFT'),('Close', 'AAPL'),( 'High', 'MSFT'),( 'High', 'AAPL')]] = a[[('Close', 'MSFT'),('Close', 'AAPL'),( 'High', 'MSFT'),( 'High', 'AAPL')]].pct_change().fillna(0)

Attributes  Adj Close   Close   High    Low Open    Volume
Symbols MSFT    AAPL    MSFT    AAPL    MSFT    AAPL    MSFT    AAPL    MSFT    AAPL    MSFT    AAPL
Date
2015-06-01  42.744289   120.306801  0.000000    0.000000    0.000000    0.000000    46.619999   130.050003  47.060001   130.279999  28837300.0  32112800.0
2015-06-02  42.463726   119.772255  -inf    -inf    -0.008792   -0.005556   46.619999   129.320007  46.930000   129.860001  21498300.0  33667600.0
2015-06-03  42.400375   119.919716  -0.772704   -1.277080   0.008237    0.002143    46.820000   129.899994  47.369999   130.660004  28002200.0  30983500.0
2015-06-04  41.956924   119.219307  6.010459    -5.744469   -0.012149   -0.002749   46.200001   128.910004  46.790001   129.580002  27745500.0  38450100.0
2015-06-05  41.757805   118.564957  -0.546270   -0.060285   -0.013571   -0.006816   45.840000   128.360001  46.310001   129.500000  25438100.0  35626800.0
... ... ... ... ... ... ... ... ... ... ... ... ...
2020-05-22  183.509995  318.890015  -1.036311   -1.863583   -0.011839   -0.005173   182.539993  315.350006  183.190002  315.769989  20826900.0  20450800.0
2020-05-26  181.570007  316.730011  -25.238713  -2.052047   0.011059    0.015694    181.100006  316.500000  186.339996  323.500000  36073600.0  31380500.0
2020-05-27  181.809998  318.109985  -1.125029   -1.643233   -0.024182   -0.017055   176.600006  313.089996  180.199997  316.140015  39517100.0  28236300.0
2020-05-28  181.399994  318.250000  -2.706163   -0.898978   0.011869    0.014841    180.380005  315.630005  180.740005  316.769989  33810200.0  33390200.0
2020-05-29  183.250000  317.940002  -5.522368   -3.213063   0.000652    -0.007080   180.410004  316.470001  182.729996  319.250000  42130400.0  38383100.0
1259 rows × 12 columns


问:
Adding some content to a <text> tag through JS
Bit stuck on getting this to work.

Had issues with the backend changing a string from x to x*. Please take the Asterix literally.

I am trying to get around this by using 'contains()' JQuery to detect the text, and apply a class to it.

```<code><text fill="#FF8201" style="font-size: 13.2px;" x="0" y="327.58888888888885" fill-opacity="1">JIMMY</text>
</code>```

Javascript:

```<code> $(document).ready(function(){
 $("text:contains(JIMMY)").addClass('an');
 });
</code>```

CSS:

```<code>text.an::after {
content: '*';
}
</code>```

But it's not working. Not sure why...

答:
Here is a vanilla Javascript solution in which we create a function called changeText which takes two arguments queryText: the text to search for and appendText the text to be appended at the end of the queryText.

//function searches for all <text> elements within svg tags for the queryText
//  and then appends them with the appendText
function changeText(queryText, appendText) {
    let textElements = document.querySelectorAll('svg text'); // get all text elements within SVG as a NodeList
    textElements.forEach(el => {  // go through each text element
        if (el.innerHTML === queryText) { // if the innerHTML matches the query HTML then
            el.innerHTML = el.innerHTML + appendText; // append the text
        }
    })
}

document.addEventListener("DOMContentLoaded", function(){
    //pass in the search text and the appending text as arguments
    changeText('JIMMY', '*');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="400" height="500">
  <text fill="#FF8201" style="font-size: 13.2px;" x="0" y="10" fill-opacity="1">JIMMY</text>
  <text fill="#FF8201" style="font-size: 13.2px;" x="0" y="30" fill-opacity="1">NOT JIMMY</text>
</svg></code>```

Body:
Bit stuck on getting this to work.

Had issues with the backend changing a string from x to x*. Please take the Asterix literally.

I am trying to get around this by using 'contains()' JQuery to detect the text, and apply a class to it.

<text fill="#FF8201" style="font-size: 13.2px;" x="0" y="327.58888888888885" fill-opacity="1">JIMMY</text>

Javascript:

 $(document).ready(function(){
 $("text:contains(JIMMY)").addClass('an');
 });

CSS:

text.an::after {
content: '*';
}

But it's not working. Not sure why...

Body:
Here is a vanilla Javascript solution in which we create a function called changeText which takes two arguments queryText: the text to search for and appendText the text to be appended at the end of the queryText.

//function searches for all <text> elements within svg tags for the queryText
//  and then appends them with the appendText
function changeText(queryText, appendText) {
    let textElements = document.querySelectorAll('svg text'); // get all text elements within SVG as a NodeList
    textElements.forEach(el => {  // go through each text element
        if (el.innerHTML === queryText) { // if the innerHTML matches the query HTML then
            el.innerHTML = el.innerHTML + appendText; // append the text
        }
    })
}

document.addEventListener("DOMContentLoaded", function(){
    //pass in the search text and the appending text as arguments
    changeText('JIMMY', '*');
});

<svg width="400" height="500">
  <text fill="#FF8201" style="font-size: 13.2px;" x="0" y="10" fill-opacity="1">JIMMY</text>
  <text fill="#FF8201" style="font-size: 13.2px;" x="0" y="30" fill-opacity="1">NOT JIMMY</text>
</svg>


问:
Winforms - best directory / project structure
Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app.

Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this.  In addition, isolate third party dependencies into implementation projects and then have interface exported projects that consumers reference

View.csproj

BusinessLogic.csproj

Data.csproj

CalculatorService.Exported.csproj (interfaces)

CalculatorService.MyCalcImpl.csproj (one implementation)

CalculatorService.MyCalcImpl2.csproj (another implementation)

Also, in terms of folder structure, what is better nesting:

Interfaces

---IFoo

---IData

Impl

---Foo

---Data

or

Product

---Interfaces/IProduct

---Impl/Product

Foo

---Impl/Foo

---Interfaces/IFoo

All trying to push for decoupled dependencies on abstractions and quick ability to changed implementations.

Thoughts? Best practices?

答:
Bit of a late answer but may as well chime in.

I have been personally using folders based on the actual type of item it is. For example:

```<code>- Project
    + Forms
    + Classes
    + UserControls
    + Resources
    + Data
</code>```

So I end up with:

```<code>new Forms.AboutForm().ShowDialog();
Controls.Add(new Controls.UberTextBox());
</code>```

OwnerDisplayName: akantro

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: akantro

Body:
Bit of a late answer but may as well chime in.

I have been personally using folders based on the actual type of item it is. For example:

- Project
    + Forms
    + Classes
    + UserControls
    + Resources
    + Data

So I end up with:

new Forms.AboutForm().ShowDialog();
Controls.Add(new Controls.UberTextBox());

ContentLicense: CC BY-SA 3.0


问:
Iterating through specific part of array in PHP
In PHP, what is the best way of iterating and passing values through the phases part of the code. The only parts that need to be iterated through is commented in the code.

```<code>  $schedule = \Stripe\SubscriptionSchedule::create([
    'customer' => 'cus_HMDwmb8iAV0X7k',
    'start_date' => $start_date,
    'end_behavior' => 'cancel',
      'phases' => [

        // Start Iteration
        [
          'end_date' => $end_date,
          'proration_behavior' => 'none',
          'plans' => [
            [
              'price_data' => [
                'unit_amount' => $unit_amount,
                'currency' => 'usd',
                'product' => $stripe_product_id,
                'recurring' => [
                    'interval' => 'year',
                ],
              ],
            ],
          ],
        ],
      // End Iteration

      ],
  ]);
}
</code>```

Any help is appreciated and code examples are always useful.

答:
Using for-each loop without key

```<code>foreach($array['phases'] as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '```'; var_dump($item);
}
```

<p>Using foreach loop with key</p>

```foreach($array['phases'] as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}
```

<p>Using for loop</p>

```for ($i = 0; $i < count($array['phases']); $i++) {
    echo $array['phases'][$i]['filename'];
    echo $array['phases'][$i]['filepath'];
}
```

Body:
In PHP, what is the best way of iterating and passing values through the phases part of the code. The only parts that need to be iterated through is commented in the code.

  $schedule = \Stripe\SubscriptionSchedule::create([
    'customer' => 'cus_HMDwmb8iAV0X7k',
    'start_date' => $start_date,
    'end_behavior' => 'cancel',
      'phases' => [

        // Start Iteration
        [
          'end_date' => $end_date,
          'proration_behavior' => 'none',
          'plans' => [
            [
              'price_data' => [
                'unit_amount' => $unit_amount,
                'currency' => 'usd',
                'product' => $stripe_product_id,
                'recurring' => [
                    'interval' => 'year',
                ],
              ],
            ],
          ],
        ],
      // End Iteration

      ],
  ]);
}

Any help is appreciated and code examples are always useful.

Body:
Using for-each loop without key

foreach($array['phases'] as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

Using foreach loop with key

foreach($array['phases'] as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}

Using for loop

for ($i = 0; $i < count($array['phases']); $i++) {
    echo $array['phases'][$i]['filename'];
    echo $array['phases'][$i]['filepath'];
}


问:
Has anyone gotten vue-cli and sass-loader to successfully import their CSS loaders on native? (vue-cli-plugin-nativescript-vue)
I've setup my vue.config.js in my Nativescript-Vue / vue-cli@3.0 project to automatically include my global.scss file into my vue templates.  That works great when serving on web, but not on my native emulators.

After running vue inspect (vue inspect -- --env.ios > out-ios.js) my out-ios.js shows sass-loaders prependData: '$PLATFORM: ios;' instead of my @import "styles/global.scss"; that appears in out-web.js. I'm curious if anyone has had this issue or solved it, as I've run out of ideas.

link to my vue.config.js module.export: https://stackoverflow.com/a/62078502/3547640

答:
Posting for future reference if anyone is experiencing similar issues getting SCSS files imported to their nativescript vue templates, my solution involved absolute paths and the vue-cli-plugin-sass-resources plugin.</p>

```<code>// vue.config.js
module.exports = {
    pluginOptions: {
        sassResources: {
            resources: path.resolve(__dirname, './src/styles/global.scss'),
        },
    },
}
</code>```

Body:
Posting for future reference if anyone is experiencing similar issues getting SCSS files imported to their nativescript vue templates, my solution involved absolute paths and the vue-cli-plugin-sass-resources plugin.

// vue.config.js
module.exports = {
    pluginOptions: {
        sassResources: {
            resources: path.resolve(__dirname, './src/styles/global.scss'),
        },
    },
}


问:
git - Visual studio team explorer is showing changes that are not actually there
I have been experimenting with git-svn and git integration within Visual Studio 2013 for a short period of time. One issue I'm having is that Visual studio is showing many files as part of the "Included changes" (i.e "modified" files) when in fact they have no changes.

At first glance, research suggest that similar problems appear when line-ending issues exist but:

A) Git in the console runs fine (i.e. git status shows no changes exist).

B) Git line ending normalization has been turned off (both by "git config --global core.autocrlf false" and a "* text=off line" in the .gitattributes file)

Any ideas?

答:
From @Vonc answer, I had checked and found even VS 2015 also still using libgit2, you can confirm it on the "%PROGRAMFILES(x86)%\Microsoft Visual Studio 14.0\Web\External\git" folder.

To confirm is it the files modification is real in Git-SCM, just use the standard Git and run the command below to see the changes.

```<code>git diff --name-status
</code>```

Most likely you will see no changes.

Btw, I found VS 2017 is switched to use standard Git-SCM. If you open using this version, it will don't have any issue.

Body:
From @Vonc answer, I had checked and found even VS 2015 also still using libgit2, you can confirm it on the "%PROGRAMFILES(x86)%\Microsoft Visual Studio 14.0\Web\External\git" folder.

To confirm is it the files modification is real in Git-SCM, just use the standard Git and run the command below to see the changes.

git diff --name-status

Most likely you will see no changes.

Btw, I found VS 2017 is switched to use standard Git-SCM. If you open using this version, it will don't have any issue.


问:
VBA - looking for solution to my simple dynamic looping sum calculation
I'm a novice trying to learn VBA. I've got a looping question: I have a simple set of numbers that are grouped in rows of three. I'm hoping to sum them up individually in column f. How could I create a dynamic range in order to loop through these to get the totals?

layout and workings are below - I don't think I have my dynamic range formula correct either. Any help is gratefully appreciated:

basic test data

```<code>Sub testing1000b()

Dim rng As Range
Dim lAnswer As Long
Dim lastrow As Long
Dim firstrow As Long

Dim addrow As Long

Range("e:f").ClearContents
addrow = 6
firstrow = Range("b" & addrow).Row
lastrow = Range("b" & firstrow).End(xlDown).Row
Range("b & firstrow" & "b & lastrow") = rng
lAnswer = WorksheetFunction.Sum(rng)
Range("f6").Value = lAnswer

End Sub
</code>```

答:
You can create a dynamic range with the code bellow.
You need to use [Set] when object is assigned to a variable.

```<code>Set rng = Range("b" & firstrow & ":" & "b" & lastrow)
</code>```

this is a sample code.

```<code>Sub testing1000b()

  Dim rng As Range
  Dim lAnswer As Long
  Dim lastrow As Long
  Dim firstrow As Long

  Dim addrow As Long: addrow = 6

  Range("e:f").ClearContents

  firstrow = Range("b" & addrow).Row
  lastrow = Range("b" & firstrow).End(xlDown).Row

  For i = 0 To 3
    Set rng = Range("b" & firstrow & ":" & "b" & lastrow)
    Range("f" & firstrow) = WorksheetFunction.Sum(rng)
    firstrow = Range("b" & lastrow).End(xlDown).Row
    lastrow = Range("b" & firstrow).End(xlDown).Row
  Next i

End Sub
</code>```

Body:
I'm a novice trying to learn VBA. I've got a looping question: I have a simple set of numbers that are grouped in rows of three. I'm hoping to sum them up individually in column f. How could I create a dynamic range in order to loop through these to get the totals?

layout and workings are below - I don't think I have my dynamic range formula correct either. Any help is gratefully appreciated:

basic test data

Sub testing1000b()

Dim rng As Range
Dim lAnswer As Long
Dim lastrow As Long
Dim firstrow As Long

Dim addrow As Long

Range("e:f").ClearContents
addrow = 6
firstrow = Range("b" & addrow).Row
lastrow = Range("b" & firstrow).End(xlDown).Row
Range("b & firstrow" & "b & lastrow") = rng
lAnswer = WorksheetFunction.Sum(rng)
Range("f6").Value = lAnswer

End Sub

Body:
You can create a dynamic range with the code bellow.
You need to use [Set] when object is assigned to a variable.

Set rng = Range("b" & firstrow & ":" & "b" & lastrow)

this is a sample code.

Sub testing1000b()

  Dim rng As Range
  Dim lAnswer As Long
  Dim lastrow As Long
  Dim firstrow As Long

  Dim addrow As Long: addrow = 6

  Range("e:f").ClearContents

  firstrow = Range("b" & addrow).Row
  lastrow = Range("b" & firstrow).End(xlDown).Row

  For i = 0 To 3
    Set rng = Range("b" & firstrow & ":" & "b" & lastrow)
    Range("f" & firstrow) = WorksheetFunction.Sum(rng)
    firstrow = Range("b" & lastrow).End(xlDown).Row
    lastrow = Range("b" & firstrow).End(xlDown).Row
  Next i

End Sub


问:
How to include metadata with Stripe Checkout client-only implementation?
I'm using Stripe Checkout's client-only implementation as I have no access to a server (building on Webflow). Implementation is very easy; you just embed some JS. Impressive stuff.

BUT. I'd really like to pass metadata along through the purchase, to be accessible in the purchase info that Zapier uses for a new Strip purchase zap.

The relevant section of the Stripe JS code snippet embedded client-side on my site is this:

stripe.redirectToCheckout({
      lineItems: [{price: 'sku_TKTKTKTKT', quantity: 1}],
      mode: 'payment',
      successUrl: 'https://blahblah.com/success',
      cancelUrl: 'https://blahblah.com/canceled'
})```

I've tried adding a metadata: 'blahblah' to this JSON; didn't work.

I tried payment_intent_data.metadata: 'blahblah' based on this Stripe doc, also to no avail.

Lastly, you can add metadata key-value pairs to the product itself within the Stripe dashboard. Also didn't work.

So does anybody know how to send metadata using Stripe Checkout client-only implementation?

Thanks!

答: Passing metadata on Checkout is only supported with the client-server integration of Checkout and is not supported on client-only Checkout.

Body:
I'm using Stripe Checkout's client-only implementation as I have no access to a server (building on Webflow). Implementation is very easy; you just embed some JS. Impressive stuff.

BUT. I'd really like to pass metadata along through the purchase, to be accessible in the purchase info that Zapier uses for a new Strip purchase zap.

The relevant section of the Stripe JS code snippet embedded client-side on my site is this:

stripe.redirectToCheckout({
      lineItems: [{price: 'sku_TKTKTKTKT', quantity: 1}],
      mode: 'payment',
      successUrl: 'https://blahblah.com/success',
      cancelUrl: 'https://blahblah.com/canceled'
})

I've tried adding a metadata: 'blahblah' to this JSON; didn't work.

I tried payment_intent_data.metadata: 'blahblah' based on this Stripe doc, also to no avail.

Lastly, you can add metadata key-value pairs to the product itself within the Stripe dashboard. Also didn't work.

So does anybody know how to send metadata using Stripe Checkout client-only implementation?

Thanks!


问:
How to create a 1.5 spaced text view in iOS?
I have a large chunk of text in a text view, and I was interested in making the line spacing 1.5 or double. Is there an way I can do this? Thanks!</p>

答:
Edit: my mistake, did not realize that UIFont's metrics are so constrained. Below is what I actually do:

I would render the text as html in a web view. You have the full control of CSS.


问:
Is it possible to create complex images (like cross functional flowchart) with Graphviz?
I need to create a complex image with lanes (like a cross functional flowchart). Is it possible to use Graphviz to automatically (based on a csv file) generate something like the picture below? If not, how can I achieve that?

答:
Technically, Graphviz could probably do it, but the spline connecting the 12 triangular nodes would be the only "easy" part of the effort.  For everything else, you would explicitly position/draw the nodes, swimlanes, and arrow edges.  Ugh!
The dpic variant of the pic language is closer fit, but I don't think it supports rotated text

I'd look at TikZ, Asymptote, and/or straight SVG

I don't know what your input file looks like, but the mapping to your output language will be challenging.  Good luck.


问:
Having Statement and Where Statement producing inconsistent results regarding Pokemon data
this is my first question. Go easy please!

I am doing an SQL project in KhanAcademy.  My source data are lines 1-181 of this pokemon database (that is, all gen 1 pokemon), and I am running some queries regarding the attack stats of the pokemon.

Running SELECT Type_1, COUNT(*) FROM pokemon WHERE "Attack" > 120 GROUP BY Type_1;, I get 15 Total Pokemon grouped by 9 different types, which is what I expect.

However, when I attempt a HAVING statement to find the number of types of Pokemon with at least one pokemon with over 120 Attack, it returns only 4 types.

This is the code: SELECT Type_1 AS "type" FROM pokemon GROUP BY type_1 HAVING "Attack" > 120;.

To show an example, one pokemon that is missing from my 2nd query is Machamp: INSERT INTO pokemon(Number,Name,Type_1,Type_2,Total,HP,Attack,Defense,Sp_Atk,Sp_Def,Speed,Generation,Legendary) VALUES (68,'Machamp','Fighting',NULL,505,90,130,80,65,85,55,1,'False');

I'm not sure what is wrong from my 2nd query.  Please help if you can.

答:
This query:

```<code>SELECT Type_1 AS "type"
FROM pokemon
GROUP BY type_1
HAVING "Attack" > 120;
</code>```

is not valid SQL and should be returning an error.  Why?  Because the HAVING takes place after the GROUP BY.  And Attack is not defined.  It would need to be in an activation function such as:

```<code>HAVING MAX(Attack) > 120
</code>```

This version of the query is logically equivalent to:

```<code>SELECT p.type
FROM (SELECT Type_1 AS "type", MAX(Attack) as max_attack
      FROM pokemon
      GROUP BY type_1
     ) p
WHERE max_Attack > 120
</code>```

Body:
This query:

SELECT Type_1 AS "type"
FROM pokemon
GROUP BY type_1
HAVING "Attack" > 120;

is not valid SQL and should be returning an error.  Why?  Because the HAVING takes place after the GROUP BY.  And Attack is not defined.  It would need to be in an activation function such as:

HAVING MAX(Attack) > 120

This version of the query is logically equivalent to:

SELECT p.type
FROM (SELECT Type_1 AS "type", MAX(Attack) as max_attack
      FROM pokemon
      GROUP BY type_1
     ) p
WHERE max_Attack > 120


问:
How to deploy a spring web application to an apache web server
So I'm a complete beginner(started programming 4 months ago) so bear with me please, i have this spring web application with an apache tomcat web server auto installed with it, and it's working quite fine in a local host. </p>

<p>I've bought a server a few days ago and installed the apache2 web server on it, and am currently trying to figure out how to configure my spring application to work as the controller handling any request that's sent to the server, but don't seem to find anything. </p>

答: There was probably an error while deploying the application to tomcat. I suggest checking the application log.</p>

Body:
So I'm a complete beginner(started programming 4 months ago) so bear with me please, i have this spring web application with an apache tomcat web server auto installed with it, and it's working quite fine in a local host.

I've bought a server a few days ago and installed the apache2 web server on it, and am currently trying to figure out how to configure my spring application to work as the controller handling any request that's sent to the server, but don't seem to find anything.


问:
How do I end my custom action on assistant?
I have a very simple action that just gives me some status and then I want to end it, no conversation, nothing else, just get the status and end it. Right now I'm doing this:

```<code>agent.add(message1);
agent.add(message2);
agent.end('done');
</code>```

I've also tried (as you'll see on the code below just doing agent.end(completeMessage); but assistant keeps waiting for me to do more, my action doesn't end.

I've made a totally simple sample to demostrate, test intent is the one that has the end() call:

Code:

```<code>'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');

const fetch = require("node-fetch");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }
  function testIntent(agent) {
    agent.end('done');
  }

 intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('test intent', testIntent);
  agent.handleRequest(intentMap);
});
</code>```

Anyone have any ideas of how I can make my action just totally end when I called test intent?

答:
If you are using the dialogflow-fulfillment library with Actions on Google, you can only have two simple responses (text or SSML strings). Since your code calls agent.end() after two messages have already been set, it may be ignored.

Instead you can call it as

```<code>agent.add(message1);
agent.end(message2);
</code>```

The documentation for agent is for the WebhookClient object. If you want to skip the library, there is also the webhook response JSON documentation.

Body:
I have a very simple action that just gives me some status and then I want to end it, no conversation, nothing else, just get the status and end it. Right now I'm doing this:

agent.add(message1);
agent.add(message2);
agent.end('done');

I've also tried (as you'll see on the code below just doing agent.end(completeMessage); but assistant keeps waiting for me to do more, my action doesn't end.

I've made a totally simple sample to demostrate, test intent is the one that has the end() call:

Code:

'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');

const fetch = require("node-fetch");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }
  function testIntent(agent) {
    agent.end('done');
  }

 intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('test intent', testIntent);
  agent.handleRequest(intentMap);
});

Anyone have any ideas of how I can make my action just totally end when I called test intent?

Body:
If you are using the dialogflow-fulfillment library with Actions on Google, you can only have two simple responses (text or SSML strings). Since your code calls agent.end() after two messages have already been set, it may be ignored.

Instead you can call it as

agent.add(message1);
agent.end(message2);

The documentation for agent is for the WebhookClient object. If you want to skip the library, there is also the webhook response JSON documentation.


问:
How to create JSON object in php without key name?
I am trying to create JSON Object and array in php. but It creates unwanted indexes (keys).Is there any way I can create object without Key name like $temp_obj-> No Key here $all_products_array; ???? Thanks in advance

This is How am I trying...

```<code>$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;

$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
    $all_products_array = array();
    $all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
    $temp_obj->all_products_array_inside[$i] = $all_products_array;
}

$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';
</code>```

It will produce below result where index/key named "1" and "all_products_array_inside" are unwanted. Because I have to go myfinalobl->all_products_array->all_products_array_inside[1].product_id
but i want easy like myfinalobl->all_products_array[i].product_id

Is there any way I can create object without Key name like
  $temp_obj-> No Key here $all_products_array; ????

```<code>{
    "myfinalobj": {
        "1": {
            "combo_info": {
                "combo_id": "1",
                "combo_name": "Supper_deal",
            },
            "all_products_array": {
                "all_products_array_inside": {
                    "1": {
                        "product_id": "1",
                        "product_name": "TV"
                    },
                    "2": {
                        "product_id": "2",
                        "product_name": "Laptop"
                    }
                }
            }
        }
    }
}
</code>```

答:
You are creating the key yourself (from $i), so just don't do that...

$myfinalobj->myfinalobj[$i] = $myObj;
```

<p>Here you have <code>[$i]</code> - remove it:</p>

<pre class="lang-php prettyprint-override"><code>$myfinalobj->myfinalobj = $myObj;
</code>```

Body:
I am trying to create JSON Object and array in php. but It creates unwanted indexes (keys).Is there any way I can create object without Key name like $temp_obj-> No Key here $all_products_array; ???? Thanks in advance

This is How am I trying...

$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;

$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
    $all_products_array = array();
    $all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
    $temp_obj->all_products_array_inside[$i] = $all_products_array;
}

$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';

It will produce below result where index/key named "1" and "all_products_array_inside" are unwanted. Because I have to go myfinalobl->all_products_array->all_products_array_inside[1].product_id
but i want easy like myfinalobl->all_products_array[i].product_id

Is there any way I can create object without Key name like
  $temp_obj-> No Key here $all_products_array; ????

{
    "myfinalobj": {
        "1": {
            "combo_info": {
                "combo_id": "1",
                "combo_name": "Supper_deal",
            },
            "all_products_array": {
                "all_products_array_inside": {
                    "1": {
                        "product_id": "1",
                        "product_name": "TV"
                    },
                    "2": {
                        "product_id": "2",
                        "product_name": "Laptop"
                    }
                }
            }
        }
    }
}

Body:
You are creating the key yourself (from $i), so just don't do that...

$myfinalobj->myfinalobj[$i] = $myObj;

Here you have [$i] - remove it:

$myfinalobj->myfinalobj = $myObj;


问:
reverse serialize() -jquery
I sent my data (json) for an ajax request with this code;

```<code>var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,
</code>```

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

答: Yeah. You just need to acces like <code>$pass = $_POST['pass']</code> :). </p>

Title: reverse serialize() -jquery

Body:
I sent my data (json) for an ajax request with this code;

var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

Body: Yeah. You just need to acces like $pass = $_POST['pass'] :).


问:
Pandas Detect Non-Numberic Data types
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

```<code>     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00
</code>```

print(df.dtypes) gives me this:

```<code>value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object
</code>```

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

答:
How about using np.isreal? Here we can get a list of columns that do not have all real numbers.

```<code>cols = [c for c in df.columns if not df[c].map(np.isreal).all()]
</code>```

And this will print out the problem columns for users.

```<code>if len(cols) != 0:
    print('The following columns have non-real number values:')
    for c in cols:
        print(c)
</code>```

Title: Pandas Detect Non-Numberic Data types

Body:
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00

print(df.dtypes) gives me this:

value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

Body:
How about using np.isreal? Here we can get a list of columns that do not have all real numbers.

cols = [c for c in df.columns if not df[c].map(np.isreal).all()]

And this will print out the problem columns for users.

if len(cols) != 0:
    print('The following columns have non-real number values:')
    for c in cols:
        print(c)


问:
Rust different types when referring to same file
I've come across a problem while attempting to use a custom enum across multiple files in Rust. I would expect to be able to write one file that contains this enum and reference it from multiple files (file_a.rs runs a function that returns a Shape enum, main.rs matches the type, but it expects types::Shape and finds a file_a::types::Shape). The outcome I expect is that both are of type types::Shape, but this does not seem to be the case.

In the past, to fix this problem, I have simply put all of the code that creates these conflicts into the same file. This does not seem like a proper solution, and especially not a professional one.

I have not been able to find any articles or questions that deal with using enums across different files in the way that I am (please direct me to them if you can).

How can I use an enum across multiple files while keeping it's type the same across all of them?

Here is a small example that demonstrates the problem. The errors occur in main.rs in the match statement.

Directory structure:

```<code>src
|    main.rs
|____core
|   |    types.rs
|   |    file_a.rs
</code>```

/src/main.rs:

#[path = "./core/types.rs"]
mod types;
use types::*;

#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;

fn main()
{
    match return_a_shape()
    {
        Shape::CIRCLE => println!("circle"),        // expected enum `file_a::types::Shape`, found enum `types::Shape`
        Shape::SQUARE => println!("square"),        // expected enum `file_a::types::Shape`, found enum `types::Shape`
        Shape::TRIANGLE => println!("triangle"),    // expected enum `file_a::types::Shape`, found enum `types::Shape`
        _ => println!("unknown shape"),
    }
}
```

<p>/src/core/file_a.rs:</p>

<pre class="lang-rust prettyprint-override"><code>mod types;
use types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}
</code>```

/src/types.rs:

pub enum Shape
{
    SQUARE,
    CIRCLE,
    TRIANGLE,
}
```

答:
I'm just studying rust, but as far as I understand, the problem here is not in the enum, but in the mod. This keyword turns one module into a submodule of another module. So, when you make types into a submodule of both file_a and main, it is imported twice as two different modules.

You can delete mod types; line from the file_a.rs and import it from parent module as use super::types::*;.

use super::types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}
```

<hr>

<p>Or you can import <code>types</code> module into the <code>file_a</code> but not in the <code>main</code> module, and reexport it:</p>

<p>file_a.rs</p>

<pre class="lang-rust prettyprint-override"><code>pub mod types; // Import types as a submodule and reexport it
use types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}

</code>```

main.rs

#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;
use file_a::types::*; // Use types submodule from the file_a module

fn main()
{
    match return_a_shape()
    {
        Shape::CIRCLE => println!("circle"),
        Shape::SQUARE => println!("square"),
        Shape::TRIANGLE => println!("triangle"),
        _ => println!("unknown shape"),
    }
}
```

Body:
I've come across a problem while attempting to use a custom enum across multiple files in Rust. I would expect to be able to write one file that contains this enum and reference it from multiple files (file_a.rs runs a function that returns a Shape enum, main.rs matches the type, but it expects types::Shape and finds a file_a::types::Shape). The outcome I expect is that both are of type types::Shape, but this does not seem to be the case.

In the past, to fix this problem, I have simply put all of the code that creates these conflicts into the same file. This does not seem like a proper solution, and especially not a professional one.

I have not been able to find any articles or questions that deal with using enums across different files in the way that I am (please direct me to them if you can).

How can I use an enum across multiple files while keeping it's type the same across all of them?

Here is a small example that demonstrates the problem. The errors occur in main.rs in the match statement.

Directory structure:

src
|    main.rs
|____core
|   |    types.rs
|   |    file_a.rs

/src/main.rs:

#[path = "./core/types.rs"]
mod types;
use types::*;

#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;

fn main()
{
    match return_a_shape()
    {
        Shape::CIRCLE => println!("circle"),        // expected enum `file_a::types::Shape`, found enum `types::Shape`
        Shape::SQUARE => println!("square"),        // expected enum `file_a::types::Shape`, found enum `types::Shape`
        Shape::TRIANGLE => println!("triangle"),    // expected enum `file_a::types::Shape`, found enum `types::Shape`
        _ => println!("unknown shape"),
    }
}

/src/core/file_a.rs:

mod types;
use types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}

/src/types.rs:

pub enum Shape
{
    SQUARE,
    CIRCLE,
    TRIANGLE,
}

Body:
I'm just studying rust, but as far as I understand, the problem here is not in the enum, but in the mod. This keyword turns one module into a submodule of another module. So, when you make types into a submodule of both file_a and main, it is imported twice as two different modules.

You can delete mod types; line from the file_a.rs and import it from parent module as use super::types::*;.

use super::types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}

Or you can import types module into the file_a but not in the main module, and reexport it:

file_a.rs

pub mod types; // Import types as a submodule and reexport it
use types::*;

pub fn return_a_shape() -> Shape
{
    return Shape::CIRCLE;
}

main.rs

#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;
use file_a::types::*; // Use types submodule from the file_a module

fn main()
{
    match return_a_shape()
    {
        Shape::CIRCLE => println!("circle"),
        Shape::SQUARE => println!("square"),
        Shape::TRIANGLE => println!("triangle"),
        _ => println!("unknown shape"),
    }
}


问:
Connecting to existing Mongoose connection through MongoStore - Error: TypeError: Cannot read property 'Store' of undefined
I'm trying to store my express-sessions on cloud.mongodb through existing connection with mongoose. The problem is that when i pass mongoose.connection as parameter of connection to
new MongoStore({mongooseConnection:mongoose.connection}) I get the following Error

```<code>  const Store = connect.Store || connect.session.Store
                                                 ^

TypeError: Cannot read property 'Store' of undefined
</code>```

I've seen for possible solutions but seems like everyone has the same configuration as me and still works. I was wondering if the fact that the connection to the database is slower than having it locally and maybe reaches first to the new Mongostore() than establishing a connection.

Here is some of my code for reference.

```<code>mongoose.connect(`mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@cluster0-kdrae.mongodb.net/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority`,{useNewUrlParser:true,useUnifiedTopology:true});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(expressSession({
  secret:process.env.EXPRESS_SESSION_SECRET,
  store: new MongoStore({///Here I get the suggestion from the IDE
    mongooseConnection:mongoose.connection
  }),
  resave:false,
  saveUninitialized:true,
  secure:true
}));
app.use(passport.initialize(undefined));
app.use(passport.session(undefined));
app.use(flash());
</code>```

I also get a suggestion from the IDE which I highlighted in the code which says:
Argument type {mongooseConnection} is not assignable to parameter type (options?: session.SessionOptions) => express.RequestHandler

答:
Digging more I see that I had forgotten to set express-session on the require like this var MongoStore = require('connect-mongo')(expressSession);

ref. Express-session mongodb session not persisting

Body:
I'm trying to store my express-sessions on cloud.mongodb through existing connection with mongoose. The problem is that when i pass mongoose.connection as parameter of connection to
new MongoStore({mongooseConnection:mongoose.connection}) I get the following Error

  const Store = connect.Store || connect.session.Store
                                                 ^

TypeError: Cannot read property 'Store' of undefined

I've seen for possible solutions but seems like everyone has the same configuration as me and still works. I was wondering if the fact that the connection to the database is slower than having it locally and maybe reaches first to the new Mongostore() than establishing a connection.

Here is some of my code for reference.

mongoose.connect(`mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@cluster0-kdrae.mongodb.net/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority`,{useNewUrlParser:true,useUnifiedTopology:true});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(expressSession({
  secret:process.env.EXPRESS_SESSION_SECRET,
  store: new MongoStore({///Here I get the suggestion from the IDE
    mongooseConnection:mongoose.connection
  }),
  resave:false,
  saveUninitialized:true,
  secure:true
}));
app.use(passport.initialize(undefined));
app.use(passport.session(undefined));
app.use(flash());

I also get a suggestion from the IDE which I highlighted in the code which says:
Argument type {mongooseConnection} is not assignable to parameter type (options?: session.SessionOptions) => express.RequestHandler


问:
Misuse of a pointer is producing a segmentation fault. I'm still not sure how to correct it though
After doing some reading, I feel like I understand what is going wrong here, but I am not sure how to fix it. As far as I understand, the issue is with how I wrote the input of an array in line 4 (emphasized). The issue itself is that when I run the code the first time in any IDE it works fine, but then when I try to play around with the numbers, it treats the new array as if it shares a size with the first one, even when it doesn't. It seems like I should be rewriting line 4 in some alternate way so as not to abuse the pointer, but I'm not sure how.</p>

```<code>using namespace std;

void INSERTIONSORT(int* A) { //THIS IS LINE 4
    int i;
    int key;
    for (int j = 0; j < sizeof(A); j++) {
        key = A[j];
        i = j - 1;
        while (i >= 0 && A[i] > key) {
            A[i + 1] = A[i];
            i = i - 1;
        }
        A[i + 1] = key;
    }
}

void display(int* A) {
    for (int i = 0; i <= sizeof(A)-1; i++)
        cout << A[i] << " ";
    cout << endl;
}

int main() {
    int myArray[] = { 2,1,4,3 };
    cout << "Array before Sorting: ";
    display(myArray);
    INSERTIONSORT(myArray);
    cout << "Array after Sorting: ";
    display(myArray);
    return 0;
}```
</code>```

答:
This line is the problem:

```<code>for (int j = 0; j < sizeof(A); j++) {
</code>```

what you need is the size of your array (the number of elements), what you get is the size of your pointer in bytes (=4, for 32-bit systems), generally you want to explicitly pass the array size or use some kind of container (std::vector) that knows its own size.

Body:
After doing some reading, I feel like I understand what is going wrong here, but I am not sure how to fix it. As far as I understand, the issue is with how I wrote the input of an array in line 4 (emphasized). The issue itself is that when I run the code the first time in any IDE it works fine, but then when I try to play around with the numbers, it treats the new array as if it shares a size with the first one, even when it doesn't. It seems like I should be rewriting line 4 in some alternate way so as not to abuse the pointer, but I'm not sure how.

using namespace std;

void INSERTIONSORT(int* A) { //THIS IS LINE 4
    int i;
    int key;
    for (int j = 0; j < sizeof(A); j++) {
        key = A[j];
        i = j - 1;
        while (i >= 0 && A[i] > key) {
            A[i + 1] = A[i];
            i = i - 1;
        }
        A[i + 1] = key;
    }
}

void display(int* A) {
    for (int i = 0; i <= sizeof(A)-1; i++)
        cout << A[i] << " ";
    cout << endl;
}

int main() {
    int myArray[] = { 2,1,4,3 };
    cout << "Array before Sorting: ";
    display(myArray);
    INSERTIONSORT(myArray);
    cout << "Array after Sorting: ";
    display(myArray);
    return 0;
}```

Body:
This line is the problem:

for (int j = 0; j < sizeof(A); j++) {

what you need is the size of your array (the number of elements), what you get is the size of your pointer in bytes (=4, for 32-bit systems), generally you want to explicitly pass the array size or use some kind of container (std::vector) that knows its own size.


问:
Update item in array in Vuex store when component is changed
In my Vuex store there is an array of Notes. Each Note is represented by a <textarea>. I have a NoteArray component that displays each Note:

// NoteArray.vue
export default {
  name: "NoteArray",
  components: { Note },
  computed: {
    ...mapState({
      notes: state => state.notes // get array of Notes from store
    })
  },
  template: `

      <Note :contents.sync="note.contents"></Note>

`
}
```
<pre class="lang-js prettyprint-override"><code>// Note.vue
export default {
  name: "Note",
  props: ["contents"], // recieve contents from NoteArray
  template: `<textarea v-model="contents"></textarea>`
}
</code>```

This setup would probably work fine if I weren't using Vuex, but I want the contents of each Note to be represented by a single array in my store:

// index.ts
let store = new Vuex.Store({
  state: {
    notes: [{contents: ""}] // will have a mutation to add/remove notes
  }
}
```
<p>Right now I'm using <code>v-model</code> to attach the contents of each Note to itself. This works fine for a one-way binding - the initial state of the Notes propagates nicely down. The problem arises upon attempting to change a Note. The <code>sync</code> modifier would be used here to establish a two-way binding without me needing to define any input events.</p>
<p>Not so for Vuex - I can only modify the state using a mutation. With strict mode enabled the above example results in the error <code>[vuex] do not mutate vuex store state outside mutation handlers</code>.</p>
<p>The fix here is to define a mutation that is called by a given Note on <code>@input</code> that changes the value of that Note's <code>contents</code>. The only way I can think of would be to define a mutation that accesses the content and changes it (instead of <code>v-model</code> and <code>sync</code>):</p>
<pre class="lang-js prettyprint-override"><code>// index.ts
...
  mutations: {
    update_note(state, payload) {
      state.notes[payload.index] = payload.context
    }
  }
...
</code>```

...but that requires that each Note knows, and is able to pass to the mutation, its own index in the state.notes array. Each Note is entirely unaware of its context, though - they don't have this information.

I'm not sure where to go from here - how can I have the value of each Note's contents be updated in the store when they're changed by the user? I want NoteArray and Note to remain their own components.

Implementation of the above sample: https://codesandbox.io/s/keen-moser-oe63d

答:
After a bit of digging, it turns out all you have to do is ditch v-model and $emit('update:contents', $event.target.value) on @input event of <textarea>. Everything else my initial answer contained is not actually needed.

Here's a working example.

As you can see, the notes are updated without any commit and they are displayed in App.vue correctly. I placed the test in App.vue to make sure they're updated in the state, not only in the vm of NoteList.vue.

I added unique identifiers because I discovered that, without them, when removing a note <textarea>s would display the wrong contents (from the next note in the notes array).

This is precisely why key-ing by index is to be avoided. (Read the warning at the end of this documentation section).

Now, to be totally fair, I don't really understand why modifying through .sync doesn't trigger the "don't mutate outside the store" warning. To answer that, one would have to dig into what exactly does .sync do. Or maybe it has to do with not changing the structure of the object. Not really sure.

Anyways, the correct way of doing it would be to dispatch an action on update:contents which would commit a mutation which would update the store:

Example: https://codesandbox.io/s/frosty-feather-lhurk?file=/src/components/NoteList.vue.

Another note: as shown by this discussion, prop.sync didn't use to "magically work" out of the box before on state properties, so it did need the dispatch + commit which apparently are no longer needed.

Body:
In my Vuex store there is an array of Notes. Each Note is represented by a <textarea>. I have a NoteArray component that displays each Note:

// NoteArray.vue
export default {
  name: "NoteArray",
  components: { Note },
  computed: {
    ...mapState({
      notes: state => state.notes // get array of Notes from store
    })
  },
  template: `

      <Note :contents.sync="note.contents"></Note>

`
}

// Note.vue
export default {
  name: "Note",
  props: ["contents"], // recieve contents from NoteArray
  template: `<textarea v-model="contents"></textarea>`
}

This setup would probably work fine if I weren't using Vuex, but I want the contents of each Note to be represented by a single array in my store:

// index.ts
let store = new Vuex.Store({
  state: {
    notes: [{contents: ""}] // will have a mutation to add/remove notes
  }
}

Right now I'm using v-model to attach the contents of each Note to itself. This works fine for a one-way binding - the initial state of the Notes propagates nicely down. The problem arises upon attempting to change a Note. The sync modifier would be used here to establish a two-way binding without me needing to define any input events.

Not so for Vuex - I can only modify the state using a mutation. With strict mode enabled the above example results in the error [vuex] do not mutate vuex store state outside mutation handlers.

The fix here is to define a mutation that is called by a given Note on @input that changes the value of that Note's contents. The only way I can think of would be to define a mutation that accesses the content and changes it (instead of v-model and sync):

// index.ts
...
  mutations: {
    update_note(state, payload) {
      state.notes[payload.index] = payload.context
    }
  }
...

...but that requires that each Note knows, and is able to pass to the mutation, its own index in the state.notes array. Each Note is entirely unaware of its context, though - they don't have this information.

I'm not sure where to go from here - how can I have the value of each Note's contents be updated in the store when they're changed by the user? I want NoteArray and Note to remain their own components.

Implementation of the above sample: https://codesandbox.io/s/keen-moser-oe63d


答:
That's the classical problem of the Vuex state pattern when binding array values (or any complex values) directly into components. This is discussed in detail in the Vue forum (https://forum.vuejs.org/t/vuex-best-practices-for-complex-objects/10143).

Basically, the idea here is to only store an array with ID's. These ID's then reference to an object, where the object key is the ID and the object value is the actual data. If you break down your data structure like this, you are able to directly bind to the store. The main goal is to have flat structures in the store and only arrays with ID's in it.

In your example, you don't actually need the array, you can directly use an object. This would then look like this:

Store:

```<code>const state = {
  notes: {
    1: {
      contents: 'test'
    },
    2: {
      contents: 'hi, I\'m a note.'
    }
  }
};
</code>```

To bind directly to the store, it is recommended to use computed properties with defined setters and getters. Here is an example:

```<code>props: {
  noteId: {
    type: Number,
    required: true
},
computed: {
  note: {
    get () {
      return this.$store.state.notes[this.noteId];
    },
    set (value) {
      this.$store.commit('setNote', {
        id: this.noteId,
        value: value
      });
    }
  }
}
</code>```

This value (note) is now two-way bound to the Vuex store. It automatically refreshes the value in the store. If you are returning an object in the getter, you should probably first create a copy of this object (deep-clone), otherwise you are directly mutating that object.

There are many utility tools to map this two-way binding behavior into a component (see e.g. https://vuex.vuejs.org/guide/state.html#the-mapstate-helper).

Title: Update item in array in Vuex store when component is changed

Body:
That's the classical problem of the Vuex state pattern when binding array values (or any complex values) directly into components. This is discussed in detail in the Vue forum (https://forum.vuejs.org/t/vuex-best-practices-for-complex-objects/10143).

Basically, the idea here is to only store an array with ID's. These ID's then reference to an object, where the object key is the ID and the object value is the actual data. If you break down your data structure like this, you are able to directly bind to the store. The main goal is to have flat structures in the store and only arrays with ID's in it.

In your example, you don't actually need the array, you can directly use an object. This would then look like this:

Store:

const state = {
  notes: {
    1: {
      contents: 'test'
    },
    2: {
      contents: 'hi, I\'m a note.'
    }
  }
};

To bind directly to the store, it is recommended to use computed properties with defined setters and getters. Here is an example:

props: {
  noteId: {
    type: Number,
    required: true
},
computed: {
  note: {
    get () {
      return this.$store.state.notes[this.noteId];
    },
    set (value) {
      this.$store.commit('setNote', {
        id: this.noteId,
        value: value
      });
    }
  }
}

This value (note) is now two-way bound to the Vuex store. It automatically refreshes the value in the store. If you are returning an object in the getter, you should probably first create a copy of this object (deep-clone), otherwise you are directly mutating that object.

There are many utility tools to map this two-way binding behavior into a component (see e.g. https://vuex.vuejs.org/guide/state.html#the-mapstate-helper).


答:
I attempt a HAVING statement to find the number of types of Pokemon with at least one pokemon with over 120 Attack

If you want to count how many types of pokemon have at least one pokemon that has more than 120 attacks, then you could add another level of aggregation on top of your existing query, like:

```<code>select count(*) no_types
from (select 1 from pokemon where attack > 120 group by type_1) t
</code>```

Note that the subquery uses select 1: we don't actually need it to return some specific column, all we want to know is how many rows it contains - hence select 1, which makes the intent explicit.

Or, we could use count(distinct), which avoids the need for a subquery:

```<code>select count(distinct type_1) no_types from pokemon where attack > 120
</code>```

Title: Having Statement and Where Statement producing inconsistent results regarding Pokemon data

Body:
this is my first question. Go easy please!

I am doing an SQL project in KhanAcademy.  My source data are lines 1-181 of this pokemon database (that is, all gen 1 pokemon), and I am running some queries regarding the attack stats of the pokemon.

Running SELECT Type_1, COUNT(*) FROM pokemon WHERE "Attack" > 120 GROUP BY Type_1;, I get 15 Total Pokemon grouped by 9 different types, which is what I expect.

However, when I attempt a HAVING statement to find the number of types of Pokemon with at least one pokemon with over 120 Attack, it returns only 4 types.

This is the code: SELECT Type_1 AS "type" FROM pokemon GROUP BY type_1 HAVING "Attack" > 120;.

To show an example, one pokemon that is missing from my 2nd query is Machamp: INSERT INTO pokemon(Number,Name,Type_1,Type_2,Total,HP,Attack,Defense,Sp_Atk,Sp_Def,Speed,Generation,Legendary) VALUES (68,'Machamp','Fighting',NULL,505,90,130,80,65,85,55,1,'False');

I'm not sure what is wrong from my 2nd query.  Please help if you can.

Body:
I attempt a HAVING statement to find the number of types of Pokemon with at least one pokemon with over 120 Attack

If you want to count how many types of pokemon have at least one pokemon that has more than 120 attacks, then you could add another level of aggregation on top of your existing query, like:

select count(*) no_types
from (select 1 from pokemon where attack > 120 group by type_1) t

Note that the subquery uses select 1: we don't actually need it to return some specific column, all we want to know is how many rows it contains - hence select 1, which makes the intent explicit.

Or, we could use count(distinct), which avoids the need for a subquery:

select count(distinct type_1) no_types from pokemon where attack > 120


问:
Transact-SQL: How do I tokenize a string?
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

```<code>SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner
</code>```

Thanks.

答:
One possible solution is that you take the string and split it into your tokens and the for each token insert it into a temp table and then join you temp table to your search table and in the join do a like '%' + tokenColumn + '%'  to get all your rows that contain a value from your tokens

Here's an example of splitting the string: http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx

Body:
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner

Thanks.


问:
CSS: border-color command causing strange shadow when element viewed on mobile device
something strange is happening in my css.

I'm working on a custom view for the Quantity Box on a WooCommerce product page. It renders fine on Chrome Developer tools for both mobile/desktop but when I look on my actual phone I get a strange shadow near the top border above the quantity number.

This is my code

#smntcswcb{
        height:35px;
        width:60px;
        padding: 8px 18px 8px 18px !important;
        border:2px solid !important;
        border-radius: 0px !important;
        color:#333 !important;
        font-size: 15px !important;
        border-color: #e5e5e5 !important;
}
```

<p>When I remove the border color line it goes away, but I would like to keep the gray border without the shadow. Please help.</p>

<p>Edit: </p>

<p>Here is the HTML code for the elements</p>

<pre class="lang-html prettyprint-override"><code><div class="quantity">
    <label class="screen-reader-text" for="smntcswcb">Quantity </label>
    <input class="minus" type="button" value="-">
    <input type="number" id="smntcswcb" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" inputmode="numeric">
    <input class="plus" type="button" value="+">
</div>
</code>```

Here is the CSS code for class="minus"

.minus{
    background: none;
    text-align: center;
    width:48px !important;
    height:35px;
    padding: 2px 0px 0px 0px !important;
    background-color: #fff !important;
    border:2px solid transparent !important;
    border-radius: 0px !important;
    border-color: #e5e5e5 !important;
    color:#333 !important;
    margin-right: -4px;
    color:#000 !important;
    font-size: 24px !important;
    font-weight:900 !important;
    position: relative;
}
```

<p>Here is the CSS code for the class "plus"</p>

<pre class="lang-css prettyprint-override"><code>.plus{
    height:35px !important;
    width:48px !important;
    padding: 2px 0px 0px 0px !important;
    background-color: #fff !important;
    border:2px solid transparent !important;
    border-radius: 0px !important;
    border-color: #e5e5e5 !important;
    color:#333 !important;
    margin-left: -4px;
    font-size: 24px !important;
    font-weight:900 !important;
}
</code>```

Here is the code for the parent class "quantity". I am using flex to make the items on the same height

.single_variation_wrap .quantity{
    display: flex;
}
```

答:
I found a solution. For anyone else who experiences this it seems that Iphone does not display shadows correctly.

The answer was found on this post

iPhone iOS will not display box-shadow properly

The fix was to add

```<code>-webkit-appearance: none;
</code>```

Body:
something strange is happening in my css.

I'm working on a custom view for the Quantity Box on a WooCommerce product page. It renders fine on Chrome Developer tools for both mobile/desktop but when I look on my actual phone I get a strange shadow near the top border above the quantity number.

This is my code

#smntcswcb{
        height:35px;
        width:60px;
        padding: 8px 18px 8px 18px !important;
        border:2px solid !important;
        border-radius: 0px !important;
        color:#333 !important;
        font-size: 15px !important;
        border-color: #e5e5e5 !important;
}

When I remove the border color line it goes away, but I would like to keep the gray border without the shadow. Please help.

Edit:

Here is the HTML code for the elements

    Quantity
    <input class="minus" type="button" value="-">
    <input type="number" id="smntcswcb" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" inputmode="numeric">
    <input class="plus" type="button" value="+">

Here is the CSS code for class="minus"

.minus{
    background: none;
    text-align: center;
    width:48px !important;
    height:35px;
    padding: 2px 0px 0px 0px !important;
    background-color: #fff !important;
    border:2px solid transparent !important;
    border-radius: 0px !important;
    border-color: #e5e5e5 !important;
    color:#333 !important;
    margin-right: -4px;
    color:#000 !important;
    font-size: 24px !important;
    font-weight:900 !important;
    position: relative;
}

Here is the CSS code for the class "plus"

.plus{
    height:35px !important;
    width:48px !important;
    padding: 2px 0px 0px 0px !important;
    background-color: #fff !important;
    border:2px solid transparent !important;
    border-radius: 0px !important;
    border-color: #e5e5e5 !important;
    color:#333 !important;
    margin-left: -4px;
    font-size: 24px !important;
    font-weight:900 !important;
}

Here is the code for the parent class "quantity". I am using flex to make the items on the same height

.single_variation_wrap .quantity{
    display: flex;
}

Body:
I found a solution. For anyone else who experiences this it seems that Iphone does not display shadows correctly.

The answer was found on this post

iPhone iOS will not display box-shadow properly

The fix was to add

-webkit-appearance: none;


问:
How do I display an object's class type, and create a sorted, comma separated list?
My problem states:

Create a class, called DataManager, that is used to keep track of simple statistics associated with a set of files.  Each file is expected to contain tab-separated lines of similar data.  Implement the methods below for full credit.

init: The DataManager constructor accepts no parameters other than self.  The constructor creates the following attributes:
      #1) a dictionary attribute, called data, to store the data (the dictionary maps index integers to lists of values).
      #2) an integer attribute, called recordnum, to store the current index value (should always be the index of the next record to add).
      #3) a list attribute, called file_list, to store the file or files that will be added.

repr: Displays the type of object (DataManager) and a comma separated list of the files that have been added to the object.  This list of file names must be sorted.

I keep getting either a TypeError or an AttributeError for my repr method. How do I correct this?

My current code:

```<code>  #Method: __init__
    #Data is a dictionary, recordnum is an integer,
    #file_list is a list to store added file(s).
    #Self, Dict, Int, List -> Self
    def __init__ (self):

        self.data = {}
        self.file_list = []
        self.recordnum = 0

    #Method: __repr__
    def __repr__ (self):

         return type(object)
         return str(sorted(self.file_list.split(','))
</code>```

答:
Usually a repper returns a precise string representation of the object that allows you to recreate it with eval:

eval(repr(instance)) --> instance

in your case, that could be something like this:

```<code>class MyQuestion:

    def __init__ (self, file_list):
        self.data = {}
        self.file_list = file_list[:]
        self.recordnum = 0

    def __repr__ (self):
         return f'{self.__class__.__name__}({sorted(self.file_list)})'

MyQuestion([2, 4, 6, 1, 3])

# ---> 'MyQuestion([1, 2, 3, 4, 6])'
</code>```

Body:
My problem states:

Create a class, called DataManager, that is used to keep track of simple statistics associated with a set of files.  Each file is expected to contain tab-separated lines of similar data.  Implement the methods below for full credit.

init: The DataManager constructor accepts no parameters other than self.  The constructor creates the following attributes:
      #1) a dictionary attribute, called data, to store the data (the dictionary maps index integers to lists of values).
      #2) an integer attribute, called recordnum, to store the current index value (should always be the index of the next record to add).
      #3) a list attribute, called file_list, to store the file or files that will be added.

repr: Displays the type of object (DataManager) and a comma separated list of the files that have been added to the object.  This list of file names must be sorted.

I keep getting either a TypeError or an AttributeError for my repr method. How do I correct this?

My current code:

  #Method: __init__
    #Data is a dictionary, recordnum is an integer,
    #file_list is a list to store added file(s).
    #Self, Dict, Int, List -> Self
    def __init__ (self):

        self.data = {}
        self.file_list = []
        self.recordnum = 0

    #Method: __repr__
    def __repr__ (self):

         return type(object)
         return str(sorted(self.file_list.split(','))

Body:
Usually a repper returns a precise string representation of the object that allows you to recreate it with eval:

eval(repr(instance)) --> instance

in your case, that could be something like this:

class MyQuestion:

    def __init__ (self, file_list):
        self.data = {}
        self.file_list = file_list[:]
        self.recordnum = 0

    def __repr__ (self):
         return f'{self.__class__.__name__}({sorted(self.file_list)})'

MyQuestion([2, 4, 6, 1, 3])

# ---> 'MyQuestion([1, 2, 3, 4, 6])'


问:
how can I extract a position of values that match a logical selection in a matrix in r?
How can I extract the position of every 0 per column in a following matrix:

```<code>bm <- matrix(c(0,1,0,1,1,1,0,1,1,1,1,0,0,0,0),5,3)
</code>```

that gives a matrix like:

```<code>+---+---+---+
| x | y | z |
+---+---+---+
| 0 | 1 | 1 |
+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
</code>```

So I want to have a data frame or matrix in whichever form it's easier with the positions of each 0 according to the rows or column position. Something like:

```<code>+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
+---+---+---+
| 3 |   | 3 |
+---+---+---+
|   |   | 4 |
+---+---+---+
|   |   | 5 |
+---+---+---+
|   |   |   |
+---+---+---+
</code>```

It's a very basic question that I did not find an answer right away yet.

答:
You can find row/column index of each position where bm = 0

```<code>mat <- which(bm == 0, arr.ind = TRUE)

#     row col
#[1,]   1   1
#[2,]   3   1
#[3,]   2   2
#[4,]   2   3
#[5,]   3   3
#[6,]   4   3
#[7,]   5   3
</code>```

Matrices/Dataframes cannot have unequal length, so we can split row index by column index to get a named list.

```<code>split(mat[, 1], mat[, 2])

#$`1`
#[1] 1 3

#$`2`
#[1] 2

#$`3`
#[1] 2 3 4 5
</code>```

Body:
How can I extract the position of every 0 per column in a following matrix:

bm <- matrix(c(0,1,0,1,1,1,0,1,1,1,1,0,0,0,0),5,3)

that gives a matrix like:

+---+---+---+
| x | y | z |
+---+---+---+
| 0 | 1 | 1 |
+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+

So I want to have a data frame or matrix in whichever form it's easier with the positions of each 0 according to the rows or column position. Something like:

+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
+---+---+---+
| 3 |   | 3 |
+---+---+---+
|   |   | 4 |
+---+---+---+
|   |   | 5 |
+---+---+---+
|   |   |   |
+---+---+---+

It's a very basic question that I did not find an answer right away yet.

Body:
You can find row/column index of each position where bm = 0

mat <- which(bm == 0, arr.ind = TRUE)

#     row col
#[1,]   1   1
#[2,]   3   1
#[3,]   2   2
#[4,]   2   3
#[5,]   3   3
#[6,]   4   3
#[7,]   5   3

Matrices/Dataframes cannot have unequal length, so we can split row index by column index to get a named list.

split(mat[, 1], mat[, 2])

#$`1`
#[1] 1 3

#$`2`
#[1] 2

#$`3`
#[1] 2 3 4 5


问:
How to make youtube-dl support non ASCII characters?
When downloading videos from youtube using youtube-dl everything works as it should except one thing, If the file name contains non english charachters like accented e or arabic charachters etc. they are completed skipped.

Ex: "Stromae - ta fête" would be downloaded with file name "Stromae - ta fte"

Kindly advise what changes should I make to support such charachters in the filename.

答:
It worked for my using Python 3.6 instead of 2.7

Using Python 2.7 y get the following message when trying to download some videos:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 76: ordinal not in range(128)
</code>```

With Python 3.6 I get the video downloaded without entering any extra parameters.

Body:
It worked for my using Python 3.6 instead of 2.7

Using Python 2.7 y get the following message when trying to download some videos:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 76: ordinal not in range(128)

With Python 3.6 I get the video downloaded without entering any extra parameters.


问:
python yaml load_all fetching wrong Keys
yaml.load all requires space after ":" to recognize the right key. If it does not find the space it will use the whole key value pair as key and then give None as value.

See below: OP print has 'B2_key:B2_VAL': None

```<code>test_item = "A1: {B1_key: b1_val, B2_key:B2_VAL}"
yaml_iterator = yaml.load_all(test_item, Loader=yaml.Loader)
op = {}
for item in yaml_iterator:
    op.update(item)
print(op)

Output print: {'A1': {'B1_key': 'b1_val', 'B2_key:B2_VAL': None}}
</code>```

I understand we can just have IP file in the right format. But is there a way we can handle it? i want users to not be care about spaces.

One way can be to inspect the the OP dict and handle it there.

Please advice best way to handle this. Thanks in advance.

答:
The YAML syntax explicitly states that a colon must be followed by a space. You therefore have two options:

Require your users to write in YAML (even if that means they have to add a space after the colon when specifying keys); or,

Use a half-thought-out format somewhat resembling YAML, for which you do not have a parser already built, and which does not allow keys with a colon in them.

Go with option 1.

Body:
yaml.load all requires space after ":" to recognize the right key. If it does not find the space it will use the whole key value pair as key and then give None as value.

See below: OP print has 'B2_key:B2_VAL': None

test_item = "A1: {B1_key: b1_val, B2_key:B2_VAL}"
yaml_iterator = yaml.load_all(test_item, Loader=yaml.Loader)
op = {}
for item in yaml_iterator:
    op.update(item)
print(op)

Output print: {'A1': {'B1_key': 'b1_val', 'B2_key:B2_VAL': None}}

I understand we can just have IP file in the right format. But is there a way we can handle it? i want users to not be care about spaces.

One way can be to inspect the the OP dict and handle it there.

Please advice best way to handle this. Thanks in advance.