问:
Failed to import container images error fabric_e_invalid_operation
I am trying to deploy a Linux container on Service Fabric Cluster with Linux (Preview) hosted on Azure.

I am having problem where I cannot run my Service Fabric Application with 1 Nginx service with following error:

Error event: SourceId='System.Hosting', Property='Download:1.0:1.0'.
  There was an error during download.Failed to download container image

I've investigate the log files and found some messages that seems correlated with the error:

```<code>2017-07-05 08:20:23.833,Info,29803,30481,Hosting.ProcessActivationManager,Processing Ipc message with action DownloadContainerImages
2017-07-05 08:20:23.834,Info,29803,30481,Hosting.DockerProcessManager,Starting dockerprocessmanager processName /usr/bin/docker, args daemon -H localhost:2375 -H unix:///var/run/docker.sock
2017-07-05 08:20:23.834,Info,30547,30481,Common.ProcessWait,completed 0 waiters
2017-07-05 08:20:23.837,Info,29803,30481,Hosting.DockerProcessManager,Docker process has started. 29806
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerImageDownloader,Failed to get history for Image, error Failed to connect to any resolved endpoint
2017-07-05 08:20:23.850,Info,30492,30481,Hosting.ContainerImageDownloader,CheckDecrement count 0
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerActivator,Failed to import docker image error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.850,Info,30492,30481,Transport.Enqueue@7f4cbda4ef20,9aff2afa-8f9e-a34e-9d67-4bf57c605eb8:120476 true  125B @ qsize 0/0B
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ProcessActivationManager,DownloadContainerImages returned FABRIC_E_INVALID_OPERATION
2017-07-05 08:20:23.855,Info,29705,30566,Transport.Msg_Dispatch@7f42be16bc20,9aff2afa-8f9e-a34e-9d67-4bf57c605eb8:120476 true 1 125B
2017-07-05 08:20:23.855,Warning,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Failed to import container images error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.855,Info,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Download container images count 1 for activationcontext  error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.855,Warning,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Download: Download:LinuxContainerServiceFabricApplicationType_App1:NginxGuestContainerPkg:1.0:1.0, ErrorCode=FABRIC_E_INVALID_OPERATION, RetryCount=7
</code>```

But I do not understand what is the reason it Failed to get history for Image, error Failed to connect to any resolved endpoint. Here is my ServiceManifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="NginxGuestContainerPkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>
    <!-- This is the name of your ServiceType.
         The UseImplicitHost attribute indicates this is a guest service. -->
    <StatelessServiceType ServiceTypeName="NginxGuestContainerType" UseImplicitHost="true" />
  </ServiceTypes>

  <!-- Code package is your service executable. -->
  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <!-- Follow this link for more information about deploying Windows containers to Service Fabric: https://aka.ms/sfguestcontainers -->
      <ContainerHost>
        <ImageName>library/nginx:1.13.0-alpine-perl</ImageName>
      </ContainerHost>
    </EntryPoint>
    <!-- Pass environment variables to your container: -->
    <!--
    <EnvironmentVariables>
      <EnvironmentVariable Name="VariableName" Value="VariableValue"/>
    </EnvironmentVariables>
    -->
  </CodePackage>

  <!-- Config package is the contents of the Config directoy under PackageRoot that contains an
       independently-updateable and versioned set of custom configuration settings for your service. -->
  <ConfigPackage Name="Config" Version="1.0.0" />

  <Resources>
    <Endpoints>
      <!-- This endpoint is used by the communication listener to obtain the port on which to
           listen. Please note that if your service is partitioned, this port is shared with
           replicas of different partitions that are placed in your code. -->
      <Endpoint Name="NginxGuestContainerTypeEndpoint" Protocol="http" UriScheme="http" Port="80" />
    </Endpoints>
  </Resources>
</ServiceManifest>
</code>```

And my ApplicationManifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest ApplicationTypeName="LinuxContainerServiceFabricApplicationType"
                     ApplicationTypeVersion="1.0.0"
                     xmlns="http://schemas.microsoft.com/2011/01/fabric"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parameters>
    <Parameter Name="NginxGuestContainer_InstanceCount" DefaultValue="-1" />
  </Parameters>
  <!-- Import the ServiceManifest from the ServicePackage. The ServiceManifestName and ServiceManifestVersion
       should match the Name and Version attributes of the ServiceManifest element defined in the
       ServiceManifest.xml file. -->
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="NginxGuestContainerPkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
    <Policies>
      <ResourceGovernancePolicy CodePackageRef="Code" CpuShares="500" MemoryInMB="1024" MemorySwapInMB="4084" MemoryReservationInMB="1024" />
      <ContainerHostPolicies CodePackageRef="Code">
        <RepositoryCredentials AccountName="someusername" Password="" PasswordEncrypted="false"/>
        <PortBinding ContainerPort="80" EndpointRef="NginxGuestContainerTypeEndpoint"/>
      </ContainerHostPolicies>
    </Policies>
  </ServiceManifestImport>
  <DefaultServices>
    <!-- The section below creates instances of service types, when an instance of this
         application type is created. You can also create one or more instances of service type using the
         ServiceFabric PowerShell module.

         The attribute ServiceTypeName below must match the name defined in the imported ServiceManifest.xml file. -->
    <Service Name="NginxGuestContainer">
      <StatelessService ServiceTypeName="NginxGuestContainerType" InstanceCount="[NginxGuestContainer_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
  </DefaultServices>
</ApplicationManifest>
</code>```

Can you help me point out what am I doing wrong here? Thank you.

Update

I am not sure whether this is causing the issue or not, but when I do SSH to the one of the SF node, I've found that the Docker service are stopped. When I try to start it and do a manual pull, one minute later it will stop automatically. Here is the logs from systemctl:

```<code>Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.835329455Z" level=info msg="Loading containers: done."
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.946744849Z" level=info msg="Daemon has completed initialization"
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.946809649Z" level=info msg="Docker daemon" commit=02c1d87 graphdriver=aufs version=17.06.0-ce
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.961652188Z" level=info msg="API listen on /var/run/docker.sock"
Jul 05 09:25:51 default000000 systemd[1]: Started Docker Application Container Engine.
Jul 05 09:26:53 default000000 systemd[1]: Stopping Docker Application Container Engine...
Jul 05 09:26:53 default000000 dockerd[41096]: time="2017-07-05T09:26:53.919115662Z" level=info msg="Processing signal 'terminated'"
Jul 05 09:26:53 default000000 dockerd[41096]: time="2017-07-05T09:26:53.954315756Z" level=info msg="stopping containerd after receiving terminated"
Jul 05 09:26:54 default000000 systemd[1]: Stopped Docker Application Container Engine.
Jul 05 09:26:55 default000000 systemd[1]: Stopped Docker Application Container Engine.
</code>```

答:
```<code> <ContainerHost>
    <ImageName>library/nginx:1.13.0-alpine-perl</ImageName>
  </ContainerHost>
</code>```

Seems suspect...  Is this resolvable?  Your log stated:

2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerImageDownloader,Failed to get history for Image, error Failed to connect to any resolved endpoint

I'm doing something similar with the AzureCR

```<code>  <ContainerHost>
    <ImageName>xxxxxx.azurecr.io/hedge-app:298</ImageName>
  </ContainerHost>
</code>```

Can you pull the image from the CLI ?

Body:
I am trying to deploy a Linux container on Service Fabric Cluster with Linux (Preview) hosted on Azure.

I am having problem where I cannot run my Service Fabric Application with 1 Nginx service with following error:

Error event: SourceId='System.Hosting', Property='Download:1.0:1.0'.
  There was an error during download.Failed to download container image

I've investigate the log files and found some messages that seems correlated with the error:

2017-07-05 08:20:23.833,Info,29803,30481,Hosting.ProcessActivationManager,Processing Ipc message with action DownloadContainerImages
2017-07-05 08:20:23.834,Info,29803,30481,Hosting.DockerProcessManager,Starting dockerprocessmanager processName /usr/bin/docker, args daemon -H localhost:2375 -H unix:///var/run/docker.sock
2017-07-05 08:20:23.834,Info,30547,30481,Common.ProcessWait,completed 0 waiters
2017-07-05 08:20:23.837,Info,29803,30481,Hosting.DockerProcessManager,Docker process has started. 29806
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerImageDownloader,Failed to get history for Image, error Failed to connect to any resolved endpoint
2017-07-05 08:20:23.850,Info,30492,30481,Hosting.ContainerImageDownloader,CheckDecrement count 0
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerActivator,Failed to import docker image error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.850,Info,30492,30481,Transport.Enqueue@7f4cbda4ef20,9aff2afa-8f9e-a34e-9d67-4bf57c605eb8:120476 true  125B @ qsize 0/0B
2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ProcessActivationManager,DownloadContainerImages returned FABRIC_E_INVALID_OPERATION
2017-07-05 08:20:23.855,Info,29705,30566,Transport.Msg_Dispatch@7f42be16bc20,9aff2afa-8f9e-a34e-9d67-4bf57c605eb8:120476 true 1 125B
2017-07-05 08:20:23.855,Warning,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Failed to import container images error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.855,Info,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Download container images count 1 for activationcontext  error FABRIC_E_INVALID_OPERATION.
2017-07-05 08:20:23.855,Warning,29583,30566,Hosting.DownloadManager@9a8431474352dcc2e88fa9ad6af912b1:131437078006900280,Download: Download:LinuxContainerServiceFabricApplicationType_App1:NginxGuestContainerPkg:1.0:1.0, ErrorCode=FABRIC_E_INVALID_OPERATION, RetryCount=7

But I do not understand what is the reason it Failed to get history for Image, error Failed to connect to any resolved endpoint. Here is my ServiceManifest:

<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="NginxGuestContainerPkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>

    <StatelessServiceType ServiceTypeName="NginxGuestContainerType" UseImplicitHost="true" />
  </ServiceTypes>

  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>

      <ContainerHost>
        <ImageName>library/nginx:1.13.0-alpine-perl</ImageName>
      </ContainerHost>
    </EntryPoint>

  </CodePackage>

  <ConfigPackage Name="Config" Version="1.0.0" />

  <Resources>
    <Endpoints>

      <Endpoint Name="NginxGuestContainerTypeEndpoint" Protocol="http" UriScheme="http" Port="80" />
    </Endpoints>
  </Resources>
</ServiceManifest>

And my ApplicationManifest:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest ApplicationTypeName="LinuxContainerServiceFabricApplicationType"
                     ApplicationTypeVersion="1.0.0"
                     xmlns="http://schemas.microsoft.com/2011/01/fabric"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parameters>
    <Parameter Name="NginxGuestContainer_InstanceCount" DefaultValue="-1" />
  </Parameters>

  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="NginxGuestContainerPkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
    <Policies>
      <ResourceGovernancePolicy CodePackageRef="Code" CpuShares="500" MemoryInMB="1024" MemorySwapInMB="4084" MemoryReservationInMB="1024" />
      <ContainerHostPolicies CodePackageRef="Code">
        <RepositoryCredentials AccountName="someusername" Password="" PasswordEncrypted="false"/>
        <PortBinding ContainerPort="80" EndpointRef="NginxGuestContainerTypeEndpoint"/>
      </ContainerHostPolicies>
    </Policies>
  </ServiceManifestImport>
  <DefaultServices>

    <Service Name="NginxGuestContainer">
      <StatelessService ServiceTypeName="NginxGuestContainerType" InstanceCount="[NginxGuestContainer_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
  </DefaultServices>
</ApplicationManifest>

Can you help me point out what am I doing wrong here? Thank you.

Update

I am not sure whether this is causing the issue or not, but when I do SSH to the one of the SF node, I've found that the Docker service are stopped. When I try to start it and do a manual pull, one minute later it will stop automatically. Here is the logs from systemctl:

Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.835329455Z" level=info msg="Loading containers: done."
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.946744849Z" level=info msg="Daemon has completed initialization"
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.946809649Z" level=info msg="Docker daemon" commit=02c1d87 graphdriver=aufs version=17.06.0-ce
Jul 05 09:25:51 default000000 dockerd[41096]: time="2017-07-05T09:25:51.961652188Z" level=info msg="API listen on /var/run/docker.sock"
Jul 05 09:25:51 default000000 systemd[1]: Started Docker Application Container Engine.
Jul 05 09:26:53 default000000 systemd[1]: Stopping Docker Application Container Engine...
Jul 05 09:26:53 default000000 dockerd[41096]: time="2017-07-05T09:26:53.919115662Z" level=info msg="Processing signal 'terminated'"
Jul 05 09:26:53 default000000 dockerd[41096]: time="2017-07-05T09:26:53.954315756Z" level=info msg="stopping containerd after receiving terminated"
Jul 05 09:26:54 default000000 systemd[1]: Stopped Docker Application Container Engine.
Jul 05 09:26:55 default000000 systemd[1]: Stopped Docker Application Container Engine.

Body:
 <ContainerHost>
    <ImageName>library/nginx:1.13.0-alpine-perl</ImageName>
  </ContainerHost>

Seems suspect...  Is this resolvable?  Your log stated:

2017-07-05 08:20:23.850,Warning,30492,30481,Hosting.ContainerImageDownloader,Failed to get history for Image, error Failed to connect to any resolved endpoint

I'm doing something similar with the AzureCR

  <ContainerHost>
    <ImageName>xxxxxx.azurecr.io/hedge-app:298</ImageName>
  </ContainerHost>

Can you pull the image from the CLI ?


来源: stackexchange

问:
Redisson - RSortedSet
I need to preserve the ordering of elements added to a SET in Redis. In order to do that, I am using RSortedSet with a custom comparator.

The problem am facing here is, unlike RSetCache I am not able to expire the elements in this SET.

Is there a work-around to achieve this use case ?.

答:
First of all, RSortedSet is implemented on top of a Redis LIST, not a SET. There is a RScoredSortedSet which is implemented on top of a Redis ZSET.

To achieve element expiry, as a work around, you can wrap it with another RExpirable object before adding into the RSortedSet. You just need to do some extra house keeping yourself: when you get an RExpirable object but it does not exist (isExists returns false), it means it is now expired. You can then delete it from the RSortedSet by yourself.

ContentLicense: CC BY-SA 3.0

Title: Redisson - RSortedSet


问:
Please provide me the logic to print the result using PRINTF
need an programming logic to print an 4 decimal points

```<code>  EX: scalar should be 0 to -5
  value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
  value = 123   ,scalar = -5  then print result = 0.0012 (4 decimals)**
  required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )
</code>```

I tried like this:

```<code> divisor =  std::pow(10,std::abs(scalar));

 **Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**
</code>```

I'm not allowed to use  float , setprecision() .

It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)

std::int32_t divisor = static_cast(std::pow( 10.0F,  std::abs( Scalar)) );

but int the above result modulus scalar value with 0 are not considering.
      **Please provide me the logic to print the above result with scalar condition

答:
In this homework exercise you are expected to perform your own number formatting, rather than using that of a library.

For instance, to format and output 100 as "100"

```<code>int accum = 100;
int position = 0;
while (accum > 0)
{
   printf("%d", accum % 10);
   accum /= 10;
   position += 1;
}
</code>```

For your homework assignment, you need to modify the above loop so that it puts a printf(".") in the correct place in the output number. Your answer is likely to involve multiplying accum before the loop and testing position relative to scalar

Body:
need an programming logic to print an 4 decimal points

  EX: scalar should be 0 to -5
  value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
  value = 123   ,scalar = -5  then print result = 0.0012 (4 decimals)**
  required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )

I tried like this:

 divisor =  std::pow(10,std::abs(scalar));

 **Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**

I'm not allowed to use  float , setprecision() .

It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)

std::int32_t divisor = static_cast(std::pow( 10.0F,  std::abs( Scalar)) );

but int the above result modulus scalar value with 0 are not considering.
      **Please provide me the logic to print the above result with scalar condition

Body:
In this homework exercise you are expected to perform your own number formatting, rather than using that of a library.

For instance, to format and output 100 as "100"

int accum = 100;
int position = 0;
while (accum > 0)
{
   printf("%d", accum % 10);
   accum /= 10;
   position += 1;
}

For your homework assignment, you need to modify the above loop so that it puts a printf(".") in the correct place in the output number. Your answer is likely to involve multiplying accum before the loop and testing position relative to scalar


问:
Incorrect: usage of hyperopt with tensorflow
In the following code, I have modified the Deep MNIST example from the tensorflow tutorials (official).

Modifications -- Added weight decay into the loss function and also modifying the weights as well. (If its incorrect please do let me know).

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

from hyperopt import STATUS_OK, STATUS_FAIL

Flags2=None

def build_and_optimize(hp_space):
    global Flags2
    Flags2 = {}
    Flags2['dp'] = hp_space['dropout_global']
    Flags2['wd'] = hp_space['wd']

    res = main(Flags2)

    results = {
        'loss': res,
        'status': STATUS_OK
    }
    return results

def deepnn(x):
    """deepnn builds the graph for a deep net for classifying digits.
        args:
            x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of piexs in a standard MNIST image.

        returns:
            a tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values equal to the logits of classifying the digit into one of classes (the digits 0-9). keep_prob is a scalar placeholder for the probability of dropout.
    """

    # reshape to use within a convolutional neural net
    # last dimension is for "features" - there is only one here, since images are
    # grayscale -- it would be 3 for RGB, 4 for RGBA, etc.
    x_image = tf.reshape(x, [-1, 28, 28, 1])
    wd = tf.placeholder(tf.float32)

    # first convolutional layer - maps one grayscale image to 32 feature maps
    W_conv1 = weight_variable([5, 5, 1, 32], wd)
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

    # pooling layer - downsamples by 2X
    h_pool1 = max_pool_2X2(h_conv1)

    # second convolutional layer --maps 32 feature maps to 64
    W_conv2 = weight_variable([5, 5, 32, 64], wd)
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

    # second pooling layer - downsamples by 2X
    h_pool2 = max_pool_2X2(h_conv2)

    # fully connected layer 1 -- after 2 round of downsampleing, our 28x28 image
    # is done to 7x7x64 feature maps --maps this to 1025 features.
    W_fc1 = weight_variable([7*7*64, 1024], wd)
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    # dropout - controls the complexity of the model, prevents co-adaptation of features.
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # map the 1024 features to 10 classes, one for each digit
    W_fc2 = weight_variable([1024, 10], wd)
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    return y_conv, keep_prob, wd

def conv2d(x, W):
    """conv2d returns a 2d convolution layer with full stride."""
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2X2(x):
    """max_pool_2x2 downsamples a feature map by 2X."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                            strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape, wd = None):
    """weight_variable generates a weight variable of a given shape."""
    initial = tf.truncated_normal(shape, stddev=0.1)
    # weight decay
    if wd is not None:
        weight_decay = tf.multiply(tf.nn.l2_loss(initial), wd, name = 'weight_loss')
        tf.add_to_collection('losses', weight_decay)
    return tf.Variable(initial)

def bias_variable(shape):
    """bias_variable generates a bias variable of a given shape."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def main(_):
    global Flags2
    if Flags2 is None:
        Flags2 = {}
    if 'keep_prob' not in Flags2:
        Flags2 = {}
        Flags2['dp'] = 1.0
        Flags2['wd'] = 0.0

    print(Flags2)

    # import data
    mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)

    # create the model
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])

    # build the graph for the deep net
    y_conv, keep_prob, wd = deepnn(x)

    cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
    # adding weight decay
    tf.add_to_collection('losses', cross_entropy)
    total_loss = tf.add_n(tf.get_collection('losses'), name='total_loss')

    train_step = tf.train.AdamOptimizer(1e-4).minimize(total_loss)
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for i in range(1000):
            batch =mnist.train.next_batch(200)

            if i % 100 == 0:
                train_accuracy = accuracy.eval(feed_dict={
                    x: batch[0], y_:batch[1], keep_prob: Flags2['dp'], wd: Flags2['wd']})
                print('step %d, training accuracy %g' %(i, train_accuracy))
            train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: Flags2['dp'], wd: Flags2['wd']})

        test_accuracy = accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0, wd: Flags2['wd']})
        print('test accuracy %g' % test_accuracy)

    return  test_accuracy

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', type=str,
                        default='/tmp/tensorflow/mnist/input_data',
                        help='directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

Hyperopt is used to tune the hyper-parameters (weight decay factor and dropout probability).

```<code>from hyperopt import fmin, tpe, hp, Trials

import pickle
import traceback

from my_mnist_convnet import build_and_optimize

space = {
    'dropout_global': hp.uniform('conv_dropout_prob', 0.4, 0.6),
    'wd': hp.uniform('wd', 0.0, 0.01)
}

def run_a_trail():
    """Run one TPE meta optimisation step and save its results."""
    max_evals = nb_evals = 3

    print("Attempt to resume a past training if it exists:")

    try:
        trials = pickle.load(open("results.pkl", "rb"))
        print("Found saved Trials! Loading...")
        max_evals = len(trials.trials) + nb_evals
        print("Rerunning from {} trials to add another one.".format(
            len(trials.trials)))
    except:
        trials = Trials()
        print("Starting from scratch: new trials.")

    best = fmin(
        build_and_optimize,
        space,
        algo=tpe.suggest,
        trials=trials,
        max_evals=max_evals
    )
    pickle.dump(trials, open("results.pkl", "wb"))

    print(best)

    return

def plot_base_and_best_models():
    return

if __name__ == "__main__":
    """plot the model and run the optimisation forever (and save results)."""
    run_a_trail()
</code>```

When hyperopt code is used, the code runs fine for only one TPE run, however, if the number of trails is increased then it reports the following error.

```<code>self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Shape [-1,784] has negative dimensions
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
</code>```

答:
This problem is most likely arising because each call to build_and_optimize() is adding nodes to the same TensorFlow graph, and the tf.train.AdamOptimizer is attempting to optimize variables from all of the previous graphs in addition to the current graph. To work around this problem, modify build_and_optimize() so that it runs main() in a different TensorFlow graph, using the following change:

```<code>def build_and_optimize(hp_space):
    global Flags2
    Flags2 = {}
    Flags2['dp'] = hp_space['dropout_global']
    Flags2['wd'] = hp_space['wd']

    # Create a new, empty graph for each trial to avoid interference from
    # previous trials.
    with tf.Graph().as_default():
        res = main(Flags2)

    results = {
        'loss': res,
        'status': STATUS_OK
    }
    return results
</code>```

Body:
In the following code, I have modified the Deep MNIST example from the tensorflow tutorials (official).

Modifications -- Added weight decay into the loss function and also modifying the weights as well. (If its incorrect please do let me know).

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

from hyperopt import STATUS_OK, STATUS_FAIL

Flags2=None

def build_and_optimize(hp_space):
    global Flags2
    Flags2 = {}
    Flags2['dp'] = hp_space['dropout_global']
    Flags2['wd'] = hp_space['wd']

    res = main(Flags2)

    results = {
        'loss': res,
        'status': STATUS_OK
    }
    return results

def deepnn(x):
    """deepnn builds the graph for a deep net for classifying digits.
        args:
            x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of piexs in a standard MNIST image.

        returns:
            a tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values equal to the logits of classifying the digit into one of classes (the digits 0-9). keep_prob is a scalar placeholder for the probability of dropout.
    """

    # reshape to use within a convolutional neural net
    # last dimension is for "features" - there is only one here, since images are
    # grayscale -- it would be 3 for RGB, 4 for RGBA, etc.
    x_image = tf.reshape(x, [-1, 28, 28, 1])
    wd = tf.placeholder(tf.float32)

    # first convolutional layer - maps one grayscale image to 32 feature maps
    W_conv1 = weight_variable([5, 5, 1, 32], wd)
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

    # pooling layer - downsamples by 2X
    h_pool1 = max_pool_2X2(h_conv1)

    # second convolutional layer --maps 32 feature maps to 64
    W_conv2 = weight_variable([5, 5, 32, 64], wd)
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

    # second pooling layer - downsamples by 2X
    h_pool2 = max_pool_2X2(h_conv2)

    # fully connected layer 1 -- after 2 round of downsampleing, our 28x28 image
    # is done to 7x7x64 feature maps --maps this to 1025 features.
    W_fc1 = weight_variable([7*7*64, 1024], wd)
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    # dropout - controls the complexity of the model, prevents co-adaptation of features.
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # map the 1024 features to 10 classes, one for each digit
    W_fc2 = weight_variable([1024, 10], wd)
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    return y_conv, keep_prob, wd

def conv2d(x, W):
    """conv2d returns a 2d convolution layer with full stride."""
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2X2(x):
    """max_pool_2x2 downsamples a feature map by 2X."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                            strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape, wd = None):
    """weight_variable generates a weight variable of a given shape."""
    initial = tf.truncated_normal(shape, stddev=0.1)
    # weight decay
    if wd is not None:
        weight_decay = tf.multiply(tf.nn.l2_loss(initial), wd, name = 'weight_loss')
        tf.add_to_collection('losses', weight_decay)
    return tf.Variable(initial)

def bias_variable(shape):
    """bias_variable generates a bias variable of a given shape."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def main(_):
    global Flags2
    if Flags2 is None:
        Flags2 = {}
    if 'keep_prob' not in Flags2:
        Flags2 = {}
        Flags2['dp'] = 1.0
        Flags2['wd'] = 0.0

    print(Flags2)

    # import data
    mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)

    # create the model
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])

    # build the graph for the deep net
    y_conv, keep_prob, wd = deepnn(x)

    cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
    # adding weight decay
    tf.add_to_collection('losses', cross_entropy)
    total_loss = tf.add_n(tf.get_collection('losses'), name='total_loss')

    train_step = tf.train.AdamOptimizer(1e-4).minimize(total_loss)
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for i in range(1000):
            batch =mnist.train.next_batch(200)

            if i % 100 == 0:
                train_accuracy = accuracy.eval(feed_dict={
                    x: batch[0], y_:batch[1], keep_prob: Flags2['dp'], wd: Flags2['wd']})
                print('step %d, training accuracy %g' %(i, train_accuracy))
            train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: Flags2['dp'], wd: Flags2['wd']})

        test_accuracy = accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0, wd: Flags2['wd']})
        print('test accuracy %g' % test_accuracy)

    return  test_accuracy

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', type=str,
                        default='/tmp/tensorflow/mnist/input_data',
                        help='directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Hyperopt is used to tune the hyper-parameters (weight decay factor and dropout probability).

from hyperopt import fmin, tpe, hp, Trials

import pickle
import traceback

from my_mnist_convnet import build_and_optimize

space = {
    'dropout_global': hp.uniform('conv_dropout_prob', 0.4, 0.6),
    'wd': hp.uniform('wd', 0.0, 0.01)
}

def run_a_trail():
    """Run one TPE meta optimisation step and save its results."""
    max_evals = nb_evals = 3

    print("Attempt to resume a past training if it exists:")

    try:
        trials = pickle.load(open("results.pkl", "rb"))
        print("Found saved Trials! Loading...")
        max_evals = len(trials.trials) + nb_evals
        print("Rerunning from {} trials to add another one.".format(
            len(trials.trials)))
    except:
        trials = Trials()
        print("Starting from scratch: new trials.")

    best = fmin(
        build_and_optimize,
        space,
        algo=tpe.suggest,
        trials=trials,
        max_evals=max_evals
    )
    pickle.dump(trials, open("results.pkl", "wb"))

    print(best)

    return

def plot_base_and_best_models():
    return

if __name__ == "__main__":
    """plot the model and run the optimisation forever (and save results)."""
    run_a_trail()

When hyperopt code is used, the code runs fine for only one TPE run, however, if the number of trails is increased then it reports the following error.

self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Shape [-1,784] has negative dimensions
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

Body:
This problem is most likely arising because each call to build_and_optimize() is adding nodes to the same TensorFlow graph, and the tf.train.AdamOptimizer is attempting to optimize variables from all of the previous graphs in addition to the current graph. To work around this problem, modify build_and_optimize() so that it runs main() in a different TensorFlow graph, using the following change:

def build_and_optimize(hp_space):
    global Flags2
    Flags2 = {}
    Flags2['dp'] = hp_space['dropout_global']
    Flags2['wd'] = hp_space['wd']

    # Create a new, empty graph for each trial to avoid interference from
    # previous trials.
    with tf.Graph().as_default():
        res = main(Flags2)

    results = {
        'loss': res,
        'status': STATUS_OK
    }
    return results


问:
merge two arrays and assign values
how can I merge two arrays and assign the value from array B to all from array a[x] like this:

```<code>var areas = [];
var values = [];
values[0] = "aaa";
values[1] = "bbb";
areas[0] = ["A","B","C"];
areas[1] = ["D","E","F"];
</code>```

and the expected value would be:

```<code>array_three[0] = ["A" => "aaa","B" => "aaa", "C" => "aaa"];
array_three[1] = ["D" => "bbb","E" => "bbb", "F" => "bbb"];
</code>```

Do I have to use map or forEach for that?

答:
Use map and reduce like this:

var areas = [
  ["A","B","C"],
  ["D","E","F"]
];
var values = ["aaa", "bbb"];

var result = values.map(function(value, i) {
  return areas[i].reduce(function(obj, area) {
    obj[area] = value;
    return obj;
  }, {});
});

console.log(result);```
</div>
</div>
</p>

<p>Or shortly using ES6's arrow functions:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var areas = [
  ["A","B","C"],
  ["D","E","F"]
];
var values = ["aaa", "bbb"];

var result = values.map((value, i) => areas[i].reduce((obj, area) => (obj[area] = value, obj), {}));

console.log(result);</code>```

Title: merge two arrays and assign values

Body:
how can I merge two arrays and assign the value from array B to all from array a[x] like this:

var areas = [];
var values = [];
values[0] = "aaa";
values[1] = "bbb";
areas[0] = ["A","B","C"];
areas[1] = ["D","E","F"];

and the expected value would be:

array_three[0] = ["A" => "aaa","B" => "aaa", "C" => "aaa"];
array_three[1] = ["D" => "bbb","E" => "bbb", "F" => "bbb"];

Do I have to use map or forEach for that?

Body:
Use map and reduce like this:

var areas = [
  ["A","B","C"],
  ["D","E","F"]
];
var values = ["aaa", "bbb"];

var result = values.map(function(value, i) {
  return areas[i].reduce(function(obj, area) {
    obj[area] = value;
    return obj;
  }, {});
});

console.log(result);

Or shortly using ES6's arrow functions:

var areas = [
  ["A","B","C"],
  ["D","E","F"]
];
var values = ["aaa", "bbb"];

var result = values.map((value, i) => areas[i].reduce((obj, area) => (obj[area] = value, obj), {}));

console.log(result);


问:
Nicely formatted numbers in SQL Server
How do I do the following in Microsoft SQL Server 2005?

```<code>DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
ELSE CAST(@PCT AS Varchar) END AS newPct
</code>```

I'm trying to drop the .0 if the percent ends in a whole number.

答:
Try casting to a float first.  The rules for casting from a float to a varchar are different from the rules for a decimal to a varchar.  The following seems to work for me:</p>

```<code>select cast(cast(@PCT as float) as varchar) as 'newPct'
</code>```

ContentLicense: CC BY-SA 2.5

Title: Nicely formatted numbers in SQL Server

Body:
How do I do the following in Microsoft SQL Server 2005?

DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
ELSE CAST(@PCT AS Varchar) END AS newPct

I'm trying to drop the .0 if the percent ends in a whole number.

Body:
Try casting to a float first.  The rules for casting from a float to a varchar are different from the rules for a decimal to a varchar.  The following seems to work for me:

select cast(cast(@PCT as float) as varchar) as 'newPct'


问:
Evaluating Rascal's Performance?
I want to evaluate the performance of Rascal for a given rewrite system that I've written.  I'm wondering if there's a good way of doing it?

Ideally, I'd generate some compiled Java classes from the system and then run them manually against my inputs.  Is there an easy or recommended way to do it?

Cheers,

答:
One way to do this is to use the functions in the library util::Benchmark. Typically, you could write something like
cpuType( (){ call_the_function_I_want_to_observe(); } ). This will execute your function and print the cpu time used.

Note that Rascal can be executed in two ways: interpreted and compiled which makes a big difference when measuring performance. We are working hard at the moment to fully integrate the compiler in the Eclipse IDE, but a stand alone version is available as well. This can be called as java -Xss8m -jar rascal-0.8.4-SNAPSHOT.jar --compiledREPL followed by at least values for directories for sources (--src), and binaries (--bin). Here rascal-0.8.4-SNAPSHOT.jar (but most likely named differently) is downloaded from the https://update.rascal-mpl.org/console/rascal-shell-unstable.jar.

If you need more information, don't hesitate to ask for more details: this part of our tool chain is unfortunately still undocumented.

Title: Evaluating Rascal's Performance?


问:
Finding PHP CodeSniffer rules
How do I find the PHP CodeSniffer rules that I need?

For example I would like function arguments and arrays to not be spaced like this

```<code>function asd( $var, $var2 = '' ) {
    $array = [ $arg, $arg2 ];
}
</code>```

Instead it should be like this:

```<code>function asd($var, $var2 = '') {
    $array = [$arg, $arg2];
}
</code>```

And I'd like phpcbf to be able to fix these, but I have no idea how to find what rules do that.

答:
There is no documentation for PHPCS rules (I will get around to this one day) so the only way to figure out what rules you need is to run PHPCS over some sample code.

For this example, I've put your sample bad code into a temp.php file:

```<code><?php
function asd( $var, $var2 = '' ) {
    $array = [ $arg, $arg2 ];
}
</code>```

Then I run PHPCS over it using the included standards. I use the -s command line argument to make sure I can see the sniff codes as well. I get this output:

```<code>$ phpcs temp.php --standard=Generic,Squiz,PEAR,PSR2,Zend -s

FILE: temp.php
---------------------------------------------------------------------------------------------------------------------------------------------
FOUND 17 ERRORS AND 5 WARNINGS AFFECTING 4 LINES
---------------------------------------------------------------------------------------------------------------------------------------------
 1 | ERROR   | [ ] The PHP open tag does not have a corresponding PHP close tag (Generic.PHP.ClosingPHPTag.NotFound)
 1 | ERROR   | [ ] Missing file doc comment (Squiz.Commenting.FileComment.Missing)
 2 | WARNING | [ ] The method parameter $var is never used (Generic.CodeAnalysis.UnusedFunctionParameter.Found)
 2 | WARNING | [ ] The method parameter $var2 is never used (Generic.CodeAnalysis.UnusedFunctionParameter.Found)
 2 | WARNING | [ ] Consider putting global function "asd" in a static class (Squiz.Functions.GlobalFunction.Found)
 2 | ERROR   | [ ] Missing file doc comment (PEAR.Commenting.FileComment.Missing)
 2 | ERROR   | [ ] Missing function doc comment (Squiz.Commenting.FunctionComment.Missing)
 2 | ERROR   | [x] Expected 2 blank lines before function; 0 found (Squiz.WhiteSpace.FunctionSpacing.Before)
 2 | ERROR   | [ ] Missing function doc comment (PEAR.Commenting.FunctionComment.Missing)
 2 | ERROR   | [x] Expected 0 spaces between opening bracket and argument "$var"; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingAfterOpen)
 2 | WARNING | [ ] Variable "var2" contains numbers but this is discouraged (Zend.NamingConventions.ValidVariableName.ContainsNumbers)
 2 | ERROR   | [x] Expected 0 spaces between argument "$var2" and closing bracket; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingBeforeClose)
 2 | ERROR   | [x] Opening brace should be on a new line (Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine)
 2 | ERROR   | [x] Opening brace should be on a new line (Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine)
 2 | ERROR   | [x] Opening brace should be on a new line (PEAR.Functions.FunctionDeclaration.BraceOnSameLine)
 3 | ERROR   | [x] Tabs must be used to indent lines; spaces are not allowed (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
 3 | ERROR   | [x] Short array syntax is not allowed (Generic.Arrays.DisallowShortArraySyntax.Found)
 3 | ERROR   | [x] Array with multiple values cannot be declared on a single line (Squiz.Arrays.ArrayDeclaration.SingleLineNotAllowed)
 3 | WARNING | [ ] Variable "arg2" contains numbers but this is discouraged (Zend.NamingConventions.ValidVariableName.ContainsNumbers)
 4 | ERROR   | [x] Expected //end asd() (Squiz.Commenting.ClosingDeclarationComment.Missing)
 4 | ERROR   | [x] Expected 1 blank line before closing function brace; 0 found
   |         |     (Squiz.WhiteSpace.FunctionClosingBraceSpace.SpacingBeforeClose)
 4 | ERROR   | [x] File must not end with a newline character (Generic.Files.EndFileNoNewline.Found)
---------------------------------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 12 MARKED SNIFF VIOLATIONS AUTOMATICALLY
---------------------------------------------------------------------------------------------------------------------------------------------

Time: 84ms; Memory: 8Mb
</code>```

Then I pick out the messages that you want to keep. Probably these two fixable errors:

```<code> 2 | ERROR   | [x] Expected 0 spaces between opening bracket and argument "$var"; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingAfterOpen)
 2 | ERROR   | [x] Expected 0 spaces between argument "$var2" and closing bracket; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingBeforeClose)
</code>```

So you might try including the whole Squiz.Functions.FunctionDeclarationArgumentSpacing sniff in your custom standard and see if you like the results. If not, you can put just those two messages into your standard and that will ignore the rest of the sniff.

You will notice that no errors were reported for the spaces at the start and end of your short array. This tells me that there is no sniff included with PHPCS that checks for this, so you would have to write a custom sniff if you want to enforce it.

This isn't obviously a pretty way of getting this information and docs would be far better, but it's the way I figure out which sniffs can be used to check code (and if a sniff is available) so I thought I'd post it as an answer. Hopefully it helps a little.

Title: Finding PHP CodeSniffer rules

Body:
How do I find the PHP CodeSniffer rules that I need?

For example I would like function arguments and arrays to not be spaced like this

function asd( $var, $var2 = '' ) {
    $array = [ $arg, $arg2 ];
}

Instead it should be like this:

function asd($var, $var2 = '') {
    $array = [$arg, $arg2];
}

And I'd like phpcbf to be able to fix these, but I have no idea how to find what rules do that.

Body:
There is no documentation for PHPCS rules (I will get around to this one day) so the only way to figure out what rules you need is to run PHPCS over some sample code.

For this example, I've put your sample bad code into a temp.php file:

<?php
function asd( $var, $var2 = '' ) {
    $array = [ $arg, $arg2 ];
}

Then I run PHPCS over it using the included standards. I use the -s command line argument to make sure I can see the sniff codes as well. I get this output:

$ phpcs temp.php --standard=Generic,Squiz,PEAR,PSR2,Zend -s

FILE: temp.php
---------------------------------------------------------------------------------------------------------------------------------------------
FOUND 17 ERRORS AND 5 WARNINGS AFFECTING 4 LINES
---------------------------------------------------------------------------------------------------------------------------------------------
 1 | ERROR   | [ ] The PHP open tag does not have a corresponding PHP close tag (Generic.PHP.ClosingPHPTag.NotFound)
 1 | ERROR   | [ ] Missing file doc comment (Squiz.Commenting.FileComment.Missing)
 2 | WARNING | [ ] The method parameter $var is never used (Generic.CodeAnalysis.UnusedFunctionParameter.Found)
 2 | WARNING | [ ] The method parameter $var2 is never used (Generic.CodeAnalysis.UnusedFunctionParameter.Found)
 2 | WARNING | [ ] Consider putting global function "asd" in a static class (Squiz.Functions.GlobalFunction.Found)
 2 | ERROR   | [ ] Missing file doc comment (PEAR.Commenting.FileComment.Missing)
 2 | ERROR   | [ ] Missing function doc comment (Squiz.Commenting.FunctionComment.Missing)
 2 | ERROR   | [x] Expected 2 blank lines before function; 0 found (Squiz.WhiteSpace.FunctionSpacing.Before)
 2 | ERROR   | [ ] Missing function doc comment (PEAR.Commenting.FunctionComment.Missing)
 2 | ERROR   | [x] Expected 0 spaces between opening bracket and argument "$var"; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingAfterOpen)
 2 | WARNING | [ ] Variable "var2" contains numbers but this is discouraged (Zend.NamingConventions.ValidVariableName.ContainsNumbers)
 2 | ERROR   | [x] Expected 0 spaces between argument "$var2" and closing bracket; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingBeforeClose)
 2 | ERROR   | [x] Opening brace should be on a new line (Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine)
 2 | ERROR   | [x] Opening brace should be on a new line (Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine)
 2 | ERROR   | [x] Opening brace should be on a new line (PEAR.Functions.FunctionDeclaration.BraceOnSameLine)
 3 | ERROR   | [x] Tabs must be used to indent lines; spaces are not allowed (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
 3 | ERROR   | [x] Short array syntax is not allowed (Generic.Arrays.DisallowShortArraySyntax.Found)
 3 | ERROR   | [x] Array with multiple values cannot be declared on a single line (Squiz.Arrays.ArrayDeclaration.SingleLineNotAllowed)
 3 | WARNING | [ ] Variable "arg2" contains numbers but this is discouraged (Zend.NamingConventions.ValidVariableName.ContainsNumbers)
 4 | ERROR   | [x] Expected //end asd() (Squiz.Commenting.ClosingDeclarationComment.Missing)
 4 | ERROR   | [x] Expected 1 blank line before closing function brace; 0 found
   |         |     (Squiz.WhiteSpace.FunctionClosingBraceSpace.SpacingBeforeClose)
 4 | ERROR   | [x] File must not end with a newline character (Generic.Files.EndFileNoNewline.Found)
---------------------------------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 12 MARKED SNIFF VIOLATIONS AUTOMATICALLY
---------------------------------------------------------------------------------------------------------------------------------------------

Time: 84ms; Memory: 8Mb

Then I pick out the messages that you want to keep. Probably these two fixable errors:

 2 | ERROR   | [x] Expected 0 spaces between opening bracket and argument "$var"; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingAfterOpen)
 2 | ERROR   | [x] Expected 0 spaces between argument "$var2" and closing bracket; 1 found
   |         |     (Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingBeforeClose)

So you might try including the whole Squiz.Functions.FunctionDeclarationArgumentSpacing sniff in your custom standard and see if you like the results. If not, you can put just those two messages into your standard and that will ignore the rest of the sniff.

You will notice that no errors were reported for the spaces at the start and end of your short array. This tells me that there is no sniff included with PHPCS that checks for this, so you would have to write a custom sniff if you want to enforce it.

This isn't obviously a pretty way of getting this information and docs would be far better, but it's the way I figure out which sniffs can be used to check code (and if a sniff is available) so I thought I'd post it as an answer. Hopefully it helps a little.


问:
How do I directly modify a Google Chrome Extension File? (.CRX)
I'm not sure in which languages those extensions are, I think the are written in Html, Javascript or JSON. As far as I know they are "compressed" in a .CRX file.

It is possible to directly modify the html, js, json of a Chrome Extension (or whatever language they use)?

答:
A signed CRX file has a header that will cause most/all unzippers to barf. This is not the easiest way to go about it, but here's how to do it from a bash command line.

The basic idea is to find where the original unsigned zipfile begins, then copy the CRX file to a zip file but exclude the CRX header.

hexdump -C the_extension.crx | more

Look in the output for the start of the zip file, which are the ASCII bytes "PK". In the sample I tried, the PK was at offset 0x132. (From reading the CRX spec, I think this number will vary from file to file because of different signature lengths.) That number is what we'll use in the next step.

dd if=the_extension.crx of=the_extension.zip bs=1 skip=0x132 (For the skip parameter, substitute the offset you found in the previous step.)

Now unzip the .zip that you just created.

Fiddle with the files in the unzipped directory, then either install the unsigned/unpacked extension into your Chrome installation, or else repackage it just as you would any other Chrome extension.

I'm sure that there is a more concise way to do this. Bash experts, please improve on my answer.


问:
Centering an unordered list
Have an image with a h2 that's centered to it, and want the list below it to also be centered. Been struggling for just over an hour now and don't seem to be getting anywhere with it. Any suggestions?

.images {
  display: inline-block;
  text-align: center;
  width: 33%;
  /* all ements align to the largest element within the div */
  vertical-align: top;
}

.images ol {
  width: 70%;
}

.images ol li {
  line-height: 1.2em;
  border: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images">
  <h3>Panacotta Vanilla</h3>
  <img src="photo1.png.png">
  <p>recipe ingridients</p>
  <ol>
    <li>Macro free Ranged Chicken</li>
    <li>Cover chicken in almond meal</li>
    <li>Add cayenne pepper, chilli flakes, mixed herbs and paprika</li>
    <li>Cook until all pink of chicken disappears Salad
    </li>

  </ol>
</div></code>```

答:
Change the position property of your div to absolute or relative.  Then you should be able to position it.  Then use margin: auto to put it in center.

```<code>position: relative;
margin: auto;
</code>```

Adding this to your your css or

```<code>position: absolute;
left: 400px; //<!--Change this to position it manually-->
</code>```

Title: Centering an unordered list

Body:
Have an image with a h2 that's centered to it, and want the list below it to also be centered. Been struggling for just over an hour now and don't seem to be getting anywhere with it. Any suggestions?

.images {
  display: inline-block;
  text-align: center;
  width: 33%;
  /* all ements align to the largest element within the div */
  vertical-align: top;
}

.images ol {
  width: 70%;
}

.images ol li {
  line-height: 1.2em;
  border: 0;
}

Panacotta Vanilla

recipe ingridients

Macro free Ranged Chicken

Cover chicken in almond meal

Add cayenne pepper, chilli flakes, mixed herbs and paprika

Cook until all pink of chicken disappears Salad

Body:
Change the position property of your div to absolute or relative.  Then you should be able to position it.  Then use margin: auto to put it in center.

position: relative;
margin: auto;

Adding this to your your css or

position: absolute;
left: 400px; //<!--Change this to position it manually-->


问:
How to reload/reopen the same form C#
I want to reload the current form (not the main form) whenever both of the radio buttons are unchecked. I did this but it won't work.</p>

```<code>StreamWriter sw;
using (sw = File.CreateText(path))
{
    if (OnewayRadio.Checked == true)
    {
        sw.WriteLine("One Way Ticket");
    }
    else if (RoundRadio.Checked == true)
    {
        sw.WriteLine("Round Trip");
    }
    else
    {
        MessageBox.Show("You have not selected your type of trip!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        sw.Close();
        File.Delete(path);
        sw = File.CreateText(path);
    }
    sw.WriteLine("Name: " + name.Text);
    sw.WriteLine("Number: " + number.Text);
}
</code>```

答:
A common practice is to open a form using ShowDialog

When your code in the form completes executing it will set a public  DialogResult

The caller can then read the DialogResult and take any necessary action.

In your case, you can set the DialogResult to Retry for this specific instance. The opener can then run a loop and continue to show the form again while ShowDialog() == DialogResult.Retry

```<code>Form2 testDialog = new Form2();

// Show testDialog as a modal dialog and determine if DialogResult = OK.
while (testDialog.ShowDialog() == DialogResult. Retry)
{
    testDialog.Dispose();
    testDialog = null;
    testDialog = new Form2();
}
</code>```

Title: How to reload/reopen the same form C#

Body:
I want to reload the current form (not the main form) whenever both of the radio buttons are unchecked. I did this but it won't work.

StreamWriter sw;
using (sw = File.CreateText(path))
{
    if (OnewayRadio.Checked == true)
    {
        sw.WriteLine("One Way Ticket");
    }
    else if (RoundRadio.Checked == true)
    {
        sw.WriteLine("Round Trip");
    }
    else
    {
        MessageBox.Show("You have not selected your type of trip!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        sw.Close();
        File.Delete(path);
        sw = File.CreateText(path);
    }
    sw.WriteLine("Name: " + name.Text);
    sw.WriteLine("Number: " + number.Text);
}

Body:
A common practice is to open a form using ShowDialog

When your code in the form completes executing it will set a public  DialogResult

The caller can then read the DialogResult and take any necessary action.

In your case, you can set the DialogResult to Retry for this specific instance. The opener can then run a loop and continue to show the form again while ShowDialog() == DialogResult.Retry

Form2 testDialog = new Form2();

// Show testDialog as a modal dialog and determine if DialogResult = OK.
while (testDialog.ShowDialog() == DialogResult. Retry)
{
    testDialog.Dispose();
    testDialog = null;
    testDialog = new Form2();
}


问:
Remove a specific item from a list by iterating
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

```<code>>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]
</code>```

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

答:
So you've exposed a little of the python implementation. Basically, an array powers the python list, and it is simply incrementing the array index by 1.  So it'll go to a[0], a[1], a[2]... and check before each iteration that it's not gonna run off the end of the array.  As you remove the first item '1' from the list, '2' moves to a[0].  The array now looks like [2,3,4,5].  The iterator is now pointing to a[1], so now  '3' gets removed.  Finally, skipping over '4', '5' gets removed.

```<code>a = [1,2,3,4,5]

for i in a:
  print("a:%s i=%s"%(a,i))
  a.remove(i)

print("final a: %s"%a)
</code>```

Gives the output

```<code>a:[1, 2, 3, 4, 5] i=1
a:[2, 3, 4, 5] i=3
a:[2, 4, 5] i=5
final a: [2, 4]
</code>```

Here's the real nuts and bolts if you're interested.
https://github.com/python/cpython/blob/master/Objects/listobject.c#L2832

Body:
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

Body:
So you've exposed a little of the python implementation. Basically, an array powers the python list, and it is simply incrementing the array index by 1.  So it'll go to a[0], a[1], a[2]... and check before each iteration that it's not gonna run off the end of the array.  As you remove the first item '1' from the list, '2' moves to a[0].  The array now looks like [2,3,4,5].  The iterator is now pointing to a[1], so now  '3' gets removed.  Finally, skipping over '4', '5' gets removed.

a = [1,2,3,4,5]

for i in a:
  print("a:%s i=%s"%(a,i))
  a.remove(i)

print("final a: %s"%a)

Gives the output

a:[1, 2, 3, 4, 5] i=1
a:[2, 3, 4, 5] i=3
a:[2, 4, 5] i=5
final a: [2, 4]

Here's the real nuts and bolts if you're interested.
https://github.com/python/cpython/blob/master/Objects/listobject.c#L2832


问:
Closing HTML <input> tag issue
Why don't the HTML <input> tags get a closing tag like other HTML tags and what would go wrong if we do close the input tag?

I tried to Google and I found the standard to write a input tag like this <input type="text" name="name">  not closing it with a </input>.

I personally felt the problem when I created an input tag for Radio buttons using

```<code>var DOM_tag = document.createElement("input");
</code>```

This though created a radio button, but the TextNode I appended to the radio button with

```<code>document.createTextNode("Radio Label");
</code>```

does not work. It simply shows the radio button with no Radio Label as in this case.

Though I can see the complete code:

```<code><input id="my_id" type="radio" name="radio_name">Radio Label</input>
</code>```

What is explanation?

P.S.

The main problem that occurred to me is the automatically closing of input tag as I mentioned in the question as I am using var DOM_tag = document.createElement("input");  which automatically creates a closing tag. What should I do about that?

答:
You can try:

```<code>var label = document.createTextNode("Radio Label");
document.createElement("input").prop({type="text"});
document.write(input.append(label));
</code>```

might work, might not. (It didn't work for me, but I can't figure out why not... I thought it would.) If that helps, great. (I'm still learning JavaScript.)

Otherwise, stick with the standard answer of using:

```<code><input id="my_id" type="radio" name="radio_name" />
<label for="my_id">Radio Label</label>
</code>```

That is what I normally would do.

ContentLicense: CC BY-SA 4.0

Title: Closing HTML <input> tag issue

Body:
Why don't the HTML <input> tags get a closing tag like other HTML tags and what would go wrong if we do close the input tag?

I tried to Google and I found the standard to write a input tag like this <input type="text" name="name">  not closing it with a </input>.

I personally felt the problem when I created an input tag for Radio buttons using

var DOM_tag = document.createElement("input");

This though created a radio button, but the TextNode I appended to the radio button with

document.createTextNode("Radio Label");

does not work. It simply shows the radio button with no Radio Label as in this case.

Though I can see the complete code:

<input id="my_id" type="radio" name="radio_name">Radio Label</input>

What is explanation?

P.S.

The main problem that occurred to me is the automatically closing of input tag as I mentioned in the question as I am using var DOM_tag = document.createElement("input");  which automatically creates a closing tag. What should I do about that?

Body:
You can try:

var label = document.createTextNode("Radio Label");
document.createElement("input").prop({type="text"});
document.write(input.append(label));

might work, might not. (It didn't work for me, but I can't figure out why not... I thought it would.) If that helps, great. (I'm still learning JavaScript.)

Otherwise, stick with the standard answer of using:

<input id="my_id" type="radio" name="radio_name" />
<label for="my_id">Radio Label</label>

That is what I normally would do.


问:
How to convert sql query with addition and join to linq
I have a working sql query that I have been trying to convert to linq for the past couple of days.  I have read several posts both here and on various site, but have not been successful in any of my attempts to convert this to a working linq query.

The parts that I am specifically having problems with deal with the math (adding individual scores to get the total_score value) and getting the values from the Schools table so I can pass them to my view.

Here is the sql query:

```<code>SELECT bowler_name, school_name, bowler_gm1, bowler_gm2, bowler_gm3, bowler_gm4, bowler_gm5, bowler_gm6, (ISNULL([bowler_gm1],0)+ISNULL([bowler_gm2],0)+ISNULL([bowler_gm3],0)+ISNULL([bowler_gm4],0)+ISNULL([bowler_gm5],0)+ISNULL([bowler_gm6],0)) AS total_score
FROM Bowlers
JOIN Schools ON Schools.school_id = Bowlers.school_id
ORDER BY total_score DESC;
</code>```

Here is as far as I get with the linq query before things start breaking:

```<code>from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select b;
</code>```

Any help would be much appreciated.  Thanks!

答:
Something like this should help you on your way.

```<code>from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select new {
  bowler_name = b.bowler_name,
  ...
  totalscore = bowler_gm1 + bowler_gm2 + bowler_gm3 ...
};
</code>```

Note it would be much easier to handle nulls if you were to create a BowlerGame table with
GameID as PK, BowlerID as FK to bowler, GameNumber as game number and finally Score as that game's score

Body:
I have a working sql query that I have been trying to convert to linq for the past couple of days.  I have read several posts both here and on various site, but have not been successful in any of my attempts to convert this to a working linq query.

The parts that I am specifically having problems with deal with the math (adding individual scores to get the total_score value) and getting the values from the Schools table so I can pass them to my view.

Here is the sql query:

SELECT bowler_name, school_name, bowler_gm1, bowler_gm2, bowler_gm3, bowler_gm4, bowler_gm5, bowler_gm6, (ISNULL([bowler_gm1],0)+ISNULL([bowler_gm2],0)+ISNULL([bowler_gm3],0)+ISNULL([bowler_gm4],0)+ISNULL([bowler_gm5],0)+ISNULL([bowler_gm6],0)) AS total_score
FROM Bowlers
JOIN Schools ON Schools.school_id = Bowlers.school_id
ORDER BY total_score DESC;

Here is as far as I get with the linq query before things start breaking:

from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select b;

Any help would be much appreciated.  Thanks!

Body:
Something like this should help you on your way.

from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select new {
  bowler_name = b.bowler_name,
  ...
  totalscore = bowler_gm1 + bowler_gm2 + bowler_gm3 ...
};

Note it would be much easier to handle nulls if you were to create a BowlerGame table with
GameID as PK, BowlerID as FK to bowler, GameNumber as game number and finally Score as that game's score


问:
How to mock a final class with mockito
I have a final class, something like this:

```<code>public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}
</code>```

I am using this class in some other class like this:

```<code>public class Seasons{

   RainOnTrees rain = new RainOnTrees();

   public void findSeasonAndRain(){

        rain.startRain();

    }
}
</code>```

and in my JUnit test class for Seasons.java I want to mock the RainOnTrees class. How can I do this with Mockito?

答:
Just to follow up. Please add this line to your gradle file:

```<code>testCompile group: 'org.mockito', name: 'mockito-inline', version: '2.8.9'
</code>```

I have tried various version of mockito-core and mockito-all. Neither of them work.

Title: How to mock a final class with mockito

Body:
I have a final class, something like this:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

I am using this class in some other class like this:

public class Seasons{

   RainOnTrees rain = new RainOnTrees();

   public void findSeasonAndRain(){

        rain.startRain();

    }
}

and in my JUnit test class for Seasons.java I want to mock the RainOnTrees class. How can I do this with Mockito?

Body:
Just to follow up. Please add this line to your gradle file:

testCompile group: 'org.mockito', name: 'mockito-inline', version: '2.8.9'

I have tried various version of mockito-core and mockito-all. Neither of them work.


问:
Linux bash: grep with regex error
I am trying to detect a NIC is configured or not. (On Ubuntu 1604, so the main configuration file will be /etc/network/interfaces).

I prepared a regex to search the configure from the interfaces file like below:

```<code>^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0
</code>```

This regex works when I put it in grep command directly; but if I put this regex into a variable then used it in grep, then grep will throw error:

```<code>grep: Invalid regular expression
</code>```

Can you please help to figure out why put that it does not work that put regex into a variable?

Thanks!

```<code>root@ci-1-0:/home/lisa# mainfn=/etc/network/interfaces
root@ci-1-0:/home/lisa# nic_name=eth0
root@ci-1-0:/home/lisa# pattern="^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+$nic_name"
root@ci-1-0:/home/lisa# echo $pattern
^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0

root@ci-1-0:/home/lisa# grep -E "^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0" $mainfn
auto eth0
iface eth0 inet dhcp

root@ci-1-0:/home/lisa# grep -E $pattern $mainfn
grep: Invalid regular expression
</code>```

答:
On my OS Sierra terminal, your example gives a slightly different error message:

```<code>> grep -E $pattern filename
grep: brackets ([ ]) not balanced
</code>```

But if I wrap the pattern in quotes, it works fine:

```<code>> grep -E "$pattern" filename
auto eth0
iface eth0 inet dhcp
</code>```

The issue is that without quotes, the space in your pattern is being interpreted as a separator between arguments:

```<code>grep -E ^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0 filename
          ^ HERE                             ^ (and also here)
</code>```

In other words, it is trying to search for an invalid regex ^[ (with unbalanced brackets, hence my error message), in three files: "\t]*(auto|iface|mapping|allow-.*)[", "\t]+eth0" (which obviously do not exist), and "filename".

As a general rule in bash, it's a good idea to wrap any use of variables in quotes like this, to avoid such whitespace issues.

Title: Linux bash: grep with regex error

Body:
I am trying to detect a NIC is configured or not. (On Ubuntu 1604, so the main configuration file will be /etc/network/interfaces).

I prepared a regex to search the configure from the interfaces file like below:

^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0

This regex works when I put it in grep command directly; but if I put this regex into a variable then used it in grep, then grep will throw error:

grep: Invalid regular expression

Can you please help to figure out why put that it does not work that put regex into a variable?

Thanks!

root@ci-1-0:/home/lisa# mainfn=/etc/network/interfaces
root@ci-1-0:/home/lisa# nic_name=eth0
root@ci-1-0:/home/lisa# pattern="^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+$nic_name"
root@ci-1-0:/home/lisa# echo $pattern
^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0

root@ci-1-0:/home/lisa# grep -E "^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0" $mainfn
auto eth0
iface eth0 inet dhcp

root@ci-1-0:/home/lisa# grep -E $pattern $mainfn
grep: Invalid regular expression

Body:
On my OS Sierra terminal, your example gives a slightly different error message:

> grep -E $pattern filename
grep: brackets ([ ]) not balanced

But if I wrap the pattern in quotes, it works fine:

> grep -E "$pattern" filename
auto eth0
iface eth0 inet dhcp

The issue is that without quotes, the space in your pattern is being interpreted as a separator between arguments:

grep -E ^[ \t]*(auto|iface|mapping|allow-.*)[ \t]+eth0 filename
          ^ HERE                             ^ (and also here)

In other words, it is trying to search for an invalid regex ^[ (with unbalanced brackets, hence my error message), in three files: "\t]*(auto|iface|mapping|allow-.*)[", "\t]+eth0" (which obviously do not exist), and "filename".

As a general rule in bash, it's a good idea to wrap any use of variables in quotes like this, to avoid such whitespace issues.


问:
Best way to retrieve values from lots of Winform controls?
I'm working on a project that required me to design a form with a lot of text fields and a few buttons. Because of Visual Studio's auto-generated code, I have about 150+ text fields that I need to be able to get the value from in a class separate from the form.

Part of the form is that there are tabs each containing similar layouts, but there are minor differences in between them. Because of the way tabs work, I have to have different names for each of the fields shared between tabs, rather than being able to access that field relative to the specified tab. This is what has led to so many form controls.

My question is this... currently I am working on a class to allow me to take the value from all of these text fields and run a string replace on a document template (a Word XML file) to overwrite placeholders with the values in the related text fields. Is there a more efficient way to do this than just creating an accessor method for each member of the form and using it to pass the value to the string.Replace() method?

I'm new to C#, so this was the only way I could think of to approach the problem.

答:
If I understand your question correctly, you want to update all textbox controls in bulk for your WinForm application.

Luckily WinForm controls are mostly derived from the Control class which offers the .Name and .Text of a Control object.

You could do that using this code:

```<code>// Loop through all controls in the form
foreach(Control control in this.Controls)
{
   if(control is TextBox)
   {
      // DO WORK
   }
}
</code>```

You can gain access to the Name or Text within the loop by calling control.Text or control.Name.

Does this answer your question?

Body:
If I understand your question correctly, you want to update all textbox controls in bulk for your WinForm application.

Luckily WinForm controls are mostly derived from the Control class which offers the .Name and .Text of a Control object.

You could do that using this code:

// Loop through all controls in the form
foreach(Control control in this.Controls)
{
   if(control is TextBox)
   {
      // DO WORK
   }
}

You can gain access to the Name or Text within the loop by calling control.Text or control.Name.

Does this answer your question?


问:
Get selected ngModel value in Angular / Ionic 2?
How can I get the selected option in constructor / function, using Angular / Ionic 2?

```<code><ion-item>
    <ion-label>Quantity</ion-label>
    <ion-select [(ngModel)]="qty">
        <ion-option value="1" selected="true">1</ion-option>
        <ion-option value="2">2</ion-option>
        <ion-option value="3">3</ion-option>
    </ion-select>
</ion-item>

<button ion-button full (click)="addToCart()">Buy Now</button>
</code>```

I've tried this:

```<code>export class ProductPage {
    qty: any;

    constructor(public navCtrl: NavController) {

    }

    addToCart() {
        console.log(this.qty);
    }
}
</code>```

答:
```<code><ion-item>
    <ion-label>Quantity</ion-label>
    <ion-select [(ngModel)]="qty">
        <ion-option [value]="1" selected="true">1</ion-option>
        <ion-option [value]="2">2</ion-option>
        <ion-option [value]="3">3</ion-option>
    </ion-select>
</ion-item>
</code>```

try this

```<code>export class ProductPage implements OnInit{
    qty: any;

    ngOnInit() {
        console.log(this.qty);
    }
}
</code>```

Please read : https://angular.io/guide/lifecycle-hooks

Body:
How can I get the selected option in constructor / function, using Angular / Ionic 2?

<ion-item>
    <ion-label>Quantity</ion-label>
    <ion-select [(ngModel)]="qty">
        <ion-option value="1" selected="true">1</ion-option>
        <ion-option value="2">2</ion-option>
        <ion-option value="3">3</ion-option>
    </ion-select>
</ion-item>

<button ion-button full (click)="addToCart()">Buy Now</button>

I've tried this:

export class ProductPage {
    qty: any;

    constructor(public navCtrl: NavController) {

    }

    addToCart() {
        console.log(this.qty);
    }
}

Body:
<ion-item>
    <ion-label>Quantity</ion-label>
    <ion-select [(ngModel)]="qty">
        <ion-option [value]="1" selected="true">1</ion-option>
        <ion-option [value]="2">2</ion-option>
        <ion-option [value]="3">3</ion-option>
    </ion-select>
</ion-item>

try this

export class ProductPage implements OnInit{
    qty: any;

    ngOnInit() {
        console.log(this.qty);
    }
}

Please read : https://angular.io/guide/lifecycle-hooks


问:
Python unittest: 'self' is not defined
I am new to unittest. I am trying to skip test cases based on values in a list.

```<code>class UESpecTest(unittest.TestCase):
    global testcases_exec_list
    testcases = []
    testcases = testcases_exec_list
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given")
    def test_retrieve_spec_info(self):
        read_spec_info.open_csv(self.spec_info)
        assert (bool(self.spec_info) == True) #Raise assertion if dictionary is empty
</code>```

I am getting the below error

```<code>  File "test_ue_cap_main.py", line 39, in UESpecTest
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given")
NameError: name 'self' is not defined
</code>```

I am not sure why self is undefined here.

答:
self is not a magic variable like this in Java and Javascript. That is why you have to define it as the first parameter in methods. If self isn't defined as a parameter or some other kind of variable, it's just not defined, like any other variable. Its name is purely conventional.

(Although if self was equivalent to this it still wouldn't make sense because there's no instance in question, just the class)

When you're at the class level, you can use other variables at the class level normally. For example:

```<code>class A:
    x = 1
    y = 2
    z = x + y  # 3
</code>```

So you can remove the self and just say '0' not in testcases.

Also, you have some weird stuff going on:

```<code>global testcases_exec_list
testcases = []
testcases = testcases_exec_list
</code>```

The line testcases = [] is completely redundant because you immediately override it.

The line global testcases_exec_list is probably useless (depending on the rest of the class definition) because global is for assignment, not access.

Why are you defining testcases if you already have testcases_exec_list? Do you understand that this makes them the same list, rather than making a copy?

Title: Python unittest: 'self' is not defined

Body:
I am new to unittest. I am trying to skip test cases based on values in a list.

class UESpecTest(unittest.TestCase):
    global testcases_exec_list
    testcases = []
    testcases = testcases_exec_list
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given")
    def test_retrieve_spec_info(self):
        read_spec_info.open_csv(self.spec_info)
        assert (bool(self.spec_info) == True) #Raise assertion if dictionary is empty

I am getting the below error

  File "test_ue_cap_main.py", line 39, in UESpecTest
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given")
NameError: name 'self' is not defined

I am not sure why self is undefined here.

Body:
self is not a magic variable like this in Java and Javascript. That is why you have to define it as the first parameter in methods. If self isn't defined as a parameter or some other kind of variable, it's just not defined, like any other variable. Its name is purely conventional.

(Although if self was equivalent to this it still wouldn't make sense because there's no instance in question, just the class)

When you're at the class level, you can use other variables at the class level normally. For example:

class A:
    x = 1
    y = 2
    z = x + y  # 3

So you can remove the self and just say '0' not in testcases.

Also, you have some weird stuff going on:

global testcases_exec_list
testcases = []
testcases = testcases_exec_list

The line testcases = [] is completely redundant because you immediately override it.

The line global testcases_exec_list is probably useless (depending on the rest of the class definition) because global is for assignment, not access.

Why are you defining testcases if you already have testcases_exec_list? Do you understand that this makes them the same list, rather than making a copy?


答:
self is not defined because self doesn't exist. At class definition time, self has not been created yet. The only time Python creates self, is when you are calling a bound method on an instance of your class. self is still a normal variable Python implicitly passes to bound methods.

So in your case, you don't need self, just use testcase as is:

```<code>@unittest.skipIf('0' not in testcases, "Testcase input not given")
</code>```

When inside of a class's namespace, variables defined there can be used normally as if they were global:

```<code>>>> class Class:
    attr1 = 0
    print(attr1)

0
>>>
</code>```

Title: Python unittest: 'self' is not defined

Body:
self is not defined because self doesn't exist. At class definition time, self has not been created yet. The only time Python creates self, is when you are calling a bound method on an instance of your class. self is still a normal variable Python implicitly passes to bound methods.

So in your case, you don't need self, just use testcase as is:

@unittest.skipIf('0' not in testcases, "Testcase input not given")

When inside of a class's namespace, variables defined there can be used normally as if they were global:

>>> class Class:
    attr1 = 0
    print(attr1)

0
>>>


问:
Element.classList Cannot read property 'toggle'
I'm getting this error:

Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLTableCellElement.toto

Can someone help?

```<code>var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;

function toto(e){
    /*this.style.cssText='background-color:white';*/
    comments.classList.toggle('.maClasse');
}

for (var i = 0; i < numComments; i += 1) {
    comments[i].addEventListener('click', toto, false);
}
</code>```

答:
It's good!</p>

```<code>var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;

//function toto(e){
    //this.style.cssText='background-color:white';
    //comments.classList.toggle('.maClasse')
    function myFunction() {
        this.classList.toggle("maClasse");
    };
//}

for (var i = 0; i < numComments; i += 1) {
    comments[i].addEventListener('click', myFunction, false);
}
</code>```

Body:
I'm getting this error:

Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLTableCellElement.toto

Can someone help?

var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;

function toto(e){
    /*this.style.cssText='background-color:white';*/
    comments.classList.toggle('.maClasse');
}

for (var i = 0; i < numComments; i += 1) {
    comments[i].addEventListener('click', toto, false);
}

Body:
It's good!

var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;

//function toto(e){
    //this.style.cssText='background-color:white';
    //comments.classList.toggle('.maClasse')
    function myFunction() {
        this.classList.toggle("maClasse");
    };
//}

for (var i = 0; i < numComments; i += 1) {
    comments[i].addEventListener('click', myFunction, false);
}


问:
The correct and clean way to not render a child template in a parent template in Ember
I am overhauling an old project to use ember with firebase for persisting data. It is a restaurant site, I added authentication and I am allowing admin users to add and delete menu items from the restaurant's menu.

My route is set up as follows

```<code>Router.map(function() {
  this.route('menu', function() {
    this.route('add');
  });
});
</code>```

the model functions are working properly but due to the nested route as you add menu items, the menu template grows and grows and pushes the add form way beneath the fold. My question is what is the correct way to get it so that localhost/menu doesn't render when you are on localhost/menu/add?

答:
First option

So it seems that menu and menu.add routes are not related much.
First suggestion is separating them as they are unrelated routes:

```<code>  this.route('add-menu');
  this.route('show-menu');
</code>```

Second option

But if they are related a bit, one better suggestion is to create a new route to list the menu items. Such as:

```<code>this.route('menu', function() {
  this.route('add');
  this.route('list');
});
</code>```

By this way, the menu route's template will be empty. (In the menu route, you may want to add a redirect hook to redirect menu routes to menu.list.)

Third option

But I think a far better suggestion is using index routes. Instead of defining the list route above, use index route. The index route will list the menu items.

Have a look at this twiddle.

Index Routes from the Ember Guides.

Body:
I am overhauling an old project to use ember with firebase for persisting data. It is a restaurant site, I added authentication and I am allowing admin users to add and delete menu items from the restaurant's menu.

My route is set up as follows

Router.map(function() {
  this.route('menu', function() {
    this.route('add');
  });
});

the model functions are working properly but due to the nested route as you add menu items, the menu template grows and grows and pushes the add form way beneath the fold. My question is what is the correct way to get it so that localhost/menu doesn't render when you are on localhost/menu/add?

Body:
First option

So it seems that menu and menu.add routes are not related much.
First suggestion is separating them as they are unrelated routes:

  this.route('add-menu');
  this.route('show-menu');

Second option

But if they are related a bit, one better suggestion is to create a new route to list the menu items. Such as:

this.route('menu', function() {
  this.route('add');
  this.route('list');
});

By this way, the menu route's template will be empty. (In the menu route, you may want to add a redirect hook to redirect menu routes to menu.list.)

Third option

But I think a far better suggestion is using index routes. Instead of defining the list route above, use index route. The index route will list the menu items.

Have a look at this twiddle.

Index Routes from the Ember Guides.


问:
Can't use preg_replace inside a static function, why?
Is there any reason why I can't use preg_replace inside a static function? when I move the code out of it, it works perfectly. Any ideas?</p>

答:
Funny, because this works fine:

```<code>class obnoxiousWeasel {

  public static function callMeDoItIDareYa($omgudid)
  {
    return preg_replace("/(, you don\'t listen)/", '...',  $omgudid);
  }

}

$pieceofmymind = "ok, but what's the point, you don't listen";

$reply = obnoxiousWeasel::callMeDoItIDareYa($pieceofmymind);

echo $reply;
</code>```

returns: "ok, but what's the point..."

We will need to see your code before we can tell you what is wrong. Using preg_replace inside a static function is definitely not the problem.

Edit: I actually edited the above useless function to improve it. Might as well face it, I'm addicted to refactoring.

Body:
Funny, because this works fine:

class obnoxiousWeasel {

  public static function callMeDoItIDareYa($omgudid)
  {
    return preg_replace("/(, you don\'t listen)/", '...',  $omgudid);
  }

}

$pieceofmymind = "ok, but what's the point, you don't listen";

$reply = obnoxiousWeasel::callMeDoItIDareYa($pieceofmymind);

echo $reply;

returns: "ok, but what's the point..."

We will need to see your code before we can tell you what is wrong. Using preg_replace inside a static function is definitely not the problem.

Edit: I actually edited the above useless function to improve it. Might as well face it, I'm addicted to refactoring.


问:
Hover on divs changes background smoothly
I made a quick hub for two websites I created and I wanted to have two divs centered side by side, so that when you put your mouse over each div, it changes the body background image. I have made it so that when you hover over it, it changes the background but, its not smooth.

I really want to learn java script and I feel like this a good experience for me, thanks for any help

I'm using jQuery and Bootstrap.

Is there a way to just use css? if there isn't a way then its fine.

HTML:

```<code><body>
  <div class="container">
    <div class="row vertical-center">
      <div class="col-md-6">
        <div class="fre">
          <h3>Howdy</h3>
          <a href="http://www.google.com">
            <div class="fre-moveleft smooth" id="fre">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="med">
          <h3>Partner</h3>
          <a href="http://www.google.com">
            <div class="med-moveright smooth" id="med">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</code>```

CSS:

```<code>.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/*
body {
    background-image: url(../images/kabobi.jpg);

}
*/

/*
body .fre-moveleft:hover {
    background-image: url(http://img.mynet.com/ha2/tayyip.jpg);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
*/
</code>```

JS:

```<code>$("#med").hover(function() {
  $('body').css("background", "url(https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
});

$("#fre").hover(function() {
  $('body').css("background", "url(https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
});
</code>```

JSFiddle

答:
Sure, you can add a transition to the body like this:

```<code>body {
    -webkit-transition: background-image 0.2s ease-in-out;
    transition: background-image 0.2s ease-in-out;
}
</code>```

https://jsfiddle.net/zdwksre7/

This css will transition between the background in the body

Also, you can start experimenting adding classes with javascript with timeouts, so you can add more custom effects. Like fade, opacity, animate, etc. (Like, on hover, add the class 'fade' to the body (this class can have opacity: 0, and add to the body instead of a background-image, a opacity transition, wait 250ms, and then remove the class fade and change the background. This will make a smooth opacity transition between backgrounds)

You can see an example here
https://jsfiddle.net/866wwr0f/

Body:
I made a quick hub for two websites I created and I wanted to have two divs centered side by side, so that when you put your mouse over each div, it changes the body background image. I have made it so that when you hover over it, it changes the background but, its not smooth.

I really want to learn java script and I feel like this a good experience for me, thanks for any help

I'm using jQuery and Bootstrap.

Is there a way to just use css? if there isn't a way then its fine.

HTML:

Howdy

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

Partner

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

CSS:

.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/*
body {
    background-image: url(../images/kabobi.jpg);

}
*/

/*
body .fre-moveleft:hover {
    background-image: url(http://img.mynet.com/ha2/tayyip.jpg);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
*/

JS:

$("#med").hover(function() {
  $('body').css("background", "url(https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
});

$("#fre").hover(function() {
  $('body').css("background", "url(https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
});

JSFiddle

Body:
Sure, you can add a transition to the body like this:

body {
    -webkit-transition: background-image 0.2s ease-in-out;
    transition: background-image 0.2s ease-in-out;
}

https://jsfiddle.net/zdwksre7/

This css will transition between the background in the body

Also, you can start experimenting adding classes with javascript with timeouts, so you can add more custom effects. Like fade, opacity, animate, etc. (Like, on hover, add the class 'fade' to the body (this class can have opacity: 0, and add to the body instead of a background-image, a opacity transition, wait 250ms, and then remove the class fade and change the background. This will make a smooth opacity transition between backgrounds)

You can see an example here
https://jsfiddle.net/866wwr0f/