问:
How come GHCi doesn't display the polymorphic type in this error message?
I am ascribing the type of a variable with type Num a => a -> a to Int, which throws an error, as expected. However, the error isn't exactly as I expected.

GHCi

```<code>λ> let x = typeInference 1
λ> :t x
x :: Num a => a -> a
λ> x :: Int

<interactive>:141:1: error:
    • Couldn't match expected type 'Int'
                  with actual type 'Integer -> Integer'
    • Probable cause: 'x' is applied to too few arguments
      In the expression: x :: Int
      In an equation for 'it': it = x :: Int
λ>
</code>```

typeInferance definition

```<code>typeInference :: Num a => a -> a -> a
typeInference x y = x + y + 1
</code>```

I expected the error message to say with actual type 'Num a => a -> a', which is the polymorphic type, why doesn't it? Does this have to do with GHCi's type defaulting?

答:
This is indeed because of GHCi's type defaulting.

The rules for this are described in section 4.3.4 of the Haskell 2010 Report and this part is especially relevant:

Each defaultable variable is replaced by the first type in the default list that is an instance of all the ambiguous variable’s classes. It is a static error if no such type is found.

Every variable that is defaultable is replaced by what it defaults to, which is the operation that occurs before the error message is produced.

Type defaulting must occur before type checking, when there is an ambiguous type. In particular, if the type class constraint were kept around instead of defaulted, the expression x :: Int would have an ambiguous type in it as defined in

We say that an expression e has an ambiguous type if, in its type ∀ u'. cx  ⇒  t, there is a type variable u in u' that occurs in cx but not in t. Such types are invalid.

(Taken from the Haskell 2010 Report, replacing u with an overbar with u').

Since, if the type were valid, the overall expression would have a type variable (the one constrained by Num) that does not appear in the resulting type (Int) (and the type variable cannot be unified away), the defaulting must occur here before the type checking.

This can be made a bit more explicit by realizing that we are type checking

```<code>(x :: forall a. Num a => a -> a) :: Int
</code>```

It looks like, during unification, if the outermost type constructor does not match ((->) on the left-hand side and Int on the right-hand side), it must default because it cannot automatically go deeper into the unification (as it could if the outermost type constructor here on the right-hand side were also (->)).

Here are a few more examples I've tested which follow this behavior:

```<code>ghci> :set -XExplicitForAll
ghci> (x :: forall a. Num a => a -> a) :: Char -> Char  -- Outermost constructor matches, so 'a' can get unified with Char and the 'a' type variable disappears

<interactive>:5:2: error:
    • No instance for (Num Char)
        arising from an expression type signature
    • In the expression:
          (x :: forall a. Num a => a -> a) :: Char -> Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Char -> Char
ghci> (x :: forall a. Num a => a -> a) :: Maybe Char

<interactive>:8:2: error:
    • Couldn't match expected type ‘Maybe Char’
                  with actual type ‘Integer -> Integer’
    • In the expression: (x :: forall a. Num a => a -> a) :: Maybe Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Maybe Char
ghci> (x :: forall a. Num a => a -> a) :: Either Char Bool

<interactive>:10:2: error:
    • Couldn't match expected type ‘Either Char Bool’
                  with actual type ‘Integer -> Integer’
    • In the expression:
          (x :: forall a. Num a => a -> a) :: Either Char Bool
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Either Char Bool
ghci> (x :: forall a. Num a => (,) a a) :: Either Char Bool

<interactive>:11:2: error:
    • Couldn't match expected type ‘Either Char Bool’
                  with actual type ‘(Integer, Integer)’
    • In the expression:
          (x :: forall a. Num a => (,) a a) :: Either Char Bool
      In an equation for ‘it’:
          it = (x :: forall a. Num a => (,) a a) :: Either Char Bool
ghci> (x :: forall a. Num a => (,) a a) :: Char

<interactive>:12:2: error:
    • Couldn't match expected type ‘Char’
                  with actual type ‘(Integer, Integer)’
    • In the expression: (x :: forall a. Num a => (,) a a) :: Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => (,) a a) :: Char
</code>```

Body:
I am ascribing the type of a variable with type Num a => a -> a to Int, which throws an error, as expected. However, the error isn't exactly as I expected.

GHCi

λ> let x = typeInference 1
λ> :t x
x :: Num a => a -> a
λ> x :: Int

<interactive>:141:1: error:
    • Couldn't match expected type 'Int'
                  with actual type 'Integer -> Integer'
    • Probable cause: 'x' is applied to too few arguments
      In the expression: x :: Int
      In an equation for 'it': it = x :: Int
λ>

typeInferance definition

typeInference :: Num a => a -> a -> a
typeInference x y = x + y + 1

I expected the error message to say with actual type 'Num a => a -> a', which is the polymorphic type, why doesn't it? Does this have to do with GHCi's type defaulting?

Body:
This is indeed because of GHCi's type defaulting.

The rules for this are described in section 4.3.4 of the Haskell 2010 Report and this part is especially relevant:

Each defaultable variable is replaced by the first type in the default list that is an instance of all the ambiguous variable’s classes. It is a static error if no such type is found.

Every variable that is defaultable is replaced by what it defaults to, which is the operation that occurs before the error message is produced.

Type defaulting must occur before type checking, when there is an ambiguous type. In particular, if the type class constraint were kept around instead of defaulted, the expression x :: Int would have an ambiguous type in it as defined in

We say that an expression e has an ambiguous type if, in its type ∀ u'. cx  ⇒  t, there is a type variable u in u' that occurs in cx but not in t. Such types are invalid.

(Taken from the Haskell 2010 Report, replacing u with an overbar with u').

Since, if the type were valid, the overall expression would have a type variable (the one constrained by Num) that does not appear in the resulting type (Int) (and the type variable cannot be unified away), the defaulting must occur here before the type checking.

This can be made a bit more explicit by realizing that we are type checking

(x :: forall a. Num a => a -> a) :: Int

It looks like, during unification, if the outermost type constructor does not match ((->) on the left-hand side and Int on the right-hand side), it must default because it cannot automatically go deeper into the unification (as it could if the outermost type constructor here on the right-hand side were also (->)).

Here are a few more examples I've tested which follow this behavior:

ghci> :set -XExplicitForAll
ghci> (x :: forall a. Num a => a -> a) :: Char -> Char  -- Outermost constructor matches, so 'a' can get unified with Char and the 'a' type variable disappears

<interactive>:5:2: error:
    • No instance for (Num Char)
        arising from an expression type signature
    • In the expression:
          (x :: forall a. Num a => a -> a) :: Char -> Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Char -> Char
ghci> (x :: forall a. Num a => a -> a) :: Maybe Char

<interactive>:8:2: error:
    • Couldn't match expected type ‘Maybe Char’
                  with actual type ‘Integer -> Integer’
    • In the expression: (x :: forall a. Num a => a -> a) :: Maybe Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Maybe Char
ghci> (x :: forall a. Num a => a -> a) :: Either Char Bool

<interactive>:10:2: error:
    • Couldn't match expected type ‘Either Char Bool’
                  with actual type ‘Integer -> Integer’
    • In the expression:
          (x :: forall a. Num a => a -> a) :: Either Char Bool
      In an equation for ‘it’:
          it = (x :: forall a. Num a => a -> a) :: Either Char Bool
ghci> (x :: forall a. Num a => (,) a a) :: Either Char Bool

<interactive>:11:2: error:
    • Couldn't match expected type ‘Either Char Bool’
                  with actual type ‘(Integer, Integer)’
    • In the expression:
          (x :: forall a. Num a => (,) a a) :: Either Char Bool
      In an equation for ‘it’:
          it = (x :: forall a. Num a => (,) a a) :: Either Char Bool
ghci> (x :: forall a. Num a => (,) a a) :: Char

<interactive>:12:2: error:
    • Couldn't match expected type ‘Char’
                  with actual type ‘(Integer, Integer)’
    • In the expression: (x :: forall a. Num a => (,) a a) :: Char
      In an equation for ‘it’:
          it = (x :: forall a. Num a => (,) a a) :: Char


来源: stackexchange

问:
Python - Paramiko isn't running a remote script properly
I am trying to run a script over SSH on a remote computer (the script is located on the remote computer). However, when I run Paramiko, all I'm doing is this:

```<code>ssh = paramiko.SSHClient()
ssh.connect(-----blacked out-----)
ssh.exec_command("python script.py")
</code>```

But it's not even executing the command. The script just runs a couple command line commands. The script.py file works just fine if I run it on the remote computer through the remote computer's terminal, but it won't when I try to use ssh to do it like above with paramiko.

答: You  might need to pass the full path to python and/or to the script, sometimes when not executing in terminal/interactive (tty) mode the path is not found as it does not load the profile scripts you would load during an interactive shell.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run a script over SSH on a remote computer (the script is located on the remote computer). However, when I run Paramiko, all I'm doing is this:

ssh = paramiko.SSHClient()
ssh.connect(-----blacked out-----)
ssh.exec_command("python script.py")

But it's not even executing the command. The script just runs a couple command line commands. The script.py file works just fine if I run it on the remote computer through the remote computer's terminal, but it won't when I try to use ssh to do it like above with paramiko.


问:
similarity search API of Watson Visual Recognition related to bulk volume of images
We have a customer requirement to search similar images in a collection using Watson Visual Recognition. The documentation mentions that each collection can contain 1 million images. Thus, I have the following questions:

a) What is the maximum size of the image?

b) Each image upload takes up to 1 second and the standard plan has a limit of 25000 images per day. So, can only 25k images added to the collection/day?

c) The customer has about 2 million images. How can we upload the images faster?

d) Is there a separate plan available for bulk volumes?

答:
This information comes from the Visual Recognition documentation at the following url:
https://www.ibm.com/watson/developercloud/doc/visual-recognition/customizing.html

Size limitations

There are size limitations for training calls and data:

The service accepts a maximum of 10,000 images or 100 MB per .zip
file.

The service requires a minimum of 10 images per .zip file.

The service accepts a maximum of 256 MB per training call.

Minimum recommend size of an image is 32X32 pixels.

Guidelines for good training Anchor link

The following guidelines are not enforced by the API. However, the service tends to perform better when the training data adheres to them:

A minimum of 50 images is recommended in each .zip file, as fewer than 50 images can decrease the quality of the trained classifier.

If the quality and content of training data is the same, then classifiers that are trained on more images will generally be more accurate than classifiers that are trained on fewer images. The benefits of training a classifier on more images plateaus at around 5000 images, and this can take a while to process. You can train a classifier on more than 5000 images, but it may not significantly increase that classifier's accuracy.

Uploading a total of 150-200 images per .zip file gives you the best balance between the time it takes to train and the improvement to classifier accuracy. More than 200 images increases the time, and it does increase the accuracy, but with diminishing returns for the amount of time it takes.

Include approximately the same number of images in each examples file. Including an unequal number of images can cause the quality of the trained classifier to decline.

The accuracy of your custom classifier can be affected by the kinds of images you provide to train it. Provide example images that are similar to the images you plan to analyze. For example, if you are training the classifier "tiger", your classifier might be less accurate if you provide only images of tigers in a zoo taken by a mobile phone to train the classifier, but you want to test the classifier on images of tigers in the wild taken by professional photographers.

Guidelines for high volume classifying Anchor link

If you want to classify many images, submitting one image at a time can take a long time. You can maximize efficiency and performance of the service in the following ways:

Resize images to be no larger than 320 pixels in either width or height. Images do not need to be high resolution.

Submit images in batches as compressed (.zip) files.

Specify only the classifiers you want results for in the classifier_ids parameter. If you do not specify a value for this parameter, the service classifies the images against the default classifier and takes longer to return a response.


问:
How do I create a public default constructor and an overloaded constructor?
I am extremely new to Java and coding in general. I am working on a project where I have created two interfaces and am now creating a concrete class named VehicleChassis that implements my Chassis interface. First, I created a String named chassisName instance variable. Now, I need to create a default constructor and overloaded constructor with the following value - A String with a parameter value of chassisName. I have searched the Internet on how to do both, but I am so confused. Help!

Below is the code I have so far.

```<code>public abstract class VehicleChassis implements Chassis{
public String chassisName;
}
</code>```

答:
You mean this?

```<code>public abstract class VehicleChassis implements Chassis{
    public String chassisName;
    VehicleChassis() {
        chassisName = "name";
    }
    VehicleChassis(final String chassisName) {
        this.chassisName = chassisName;
    }
}
</code>```

You won't be able to instantiate this VehicleChassis because you've declared it as abstract. You can use the constructors if you extend this class, though. Consider declaring the constructors protected if that's what you intend to do.

Body:
I am extremely new to Java and coding in general. I am working on a project where I have created two interfaces and am now creating a concrete class named VehicleChassis that implements my Chassis interface. First, I created a String named chassisName instance variable. Now, I need to create a default constructor and overloaded constructor with the following value - A String with a parameter value of chassisName. I have searched the Internet on how to do both, but I am so confused. Help!

Below is the code I have so far.

public abstract class VehicleChassis implements Chassis{
public String chassisName;
}

Body:
You mean this?

public abstract class VehicleChassis implements Chassis{
    public String chassisName;
    VehicleChassis() {
        chassisName = "name";
    }
    VehicleChassis(final String chassisName) {
        this.chassisName = chassisName;
    }
}

You won't be able to instantiate this VehicleChassis because you've declared it as abstract. You can use the constructors if you extend this class, though. Consider declaring the constructors protected if that's what you intend to do.


问:
Define default selection if no data in db - Symfony EntityType
This is code I use to show filed in page.

I need some way to predefine default selected if there is no data.
Any suggestion?

```<code>->add('period', EntityType::class, [
            'required' => false,
            'empty_value' => false,
            'expanded' => true,
            'class' => 'MainBundle\Entity\NotificationsPeriod',
            'query_builder' => function (EntityRepository $er) {
                $qb = $er->createQueryBuilder('u');
                $qb->orderBy('u.id', 'ASC');
                $qb->add('where', $qb->expr()->notIn('u.id', 1));
                return $qb;
            },
            'empty_data' => 2,
        ])
</code>```

答:
You're almost there!

You need to set your empty_data parameter as you have to match a value in your HTML.

For example:

```<code>//formClass.php
'empty_data' => 2,
</code>```

Then ..

```<code>//template.twig
<select name="whatever">
  <option value="2">Something</option>
  {# build your options from data.. #}
</select>
</code>```

The official docs are here: http://symfony.com/doc/current/reference/forms/types/choice.html#empty-data

Body:
This is code I use to show filed in page.

I need some way to predefine default selected if there is no data.
Any suggestion?

->add('period', EntityType::class, [
            'required' => false,
            'empty_value' => false,
            'expanded' => true,
            'class' => 'MainBundle\Entity\NotificationsPeriod',
            'query_builder' => function (EntityRepository $er) {
                $qb = $er->createQueryBuilder('u');
                $qb->orderBy('u.id', 'ASC');
                $qb->add('where', $qb->expr()->notIn('u.id', 1));
                return $qb;
            },
            'empty_data' => 2,
        ])

Body:
You're almost there!

You need to set your empty_data parameter as you have to match a value in your HTML.

For example:

//formClass.php
'empty_data' => 2,

Then ..

//template.twig
<select name="whatever">
  <option value="2">Something</option>
  {# build your options from data.. #}
</select>

The official docs are here: http://symfony.com/doc/current/reference/forms/types/choice.html#empty-data


问:
dev_appserver fails to launch on Ubuntu docker container (ValidationError: Value 'None' for application does not match expression)
I started seeing this issue after upgrading docker container. I couldn't find a way to use an older package for app engine. Using options =157.x.y to get older versions doesn't work in apt-get.

Failure log:

```<code>Traceback (most recent call last):
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 103, in <module>
    _run_file(__file__, globals())
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 97, in _run_file
    execfile(_PATHS.script_file(script_name), globals_)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 322, in <module>
    main()
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 310, in main
    dev_server.start(options)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 106, in start
    env_variables=parsed_env_variables)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 851, in __init__
    env_variables)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 131, in __init__
    self._config_path)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 443, in _parse_configuration
    config.application = self._forced_app_id
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 361, in __setattr__
    value = self.GetValidator(key)(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 599, in __call__
    return self.Validate(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 881, in Validate
    return self.validator(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 599, in __call__
    return self.Validate(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 955, in Validate
    '\'%s\'' % (value, key, self.re.pattern))
google.appengine.api.validation.ValidationError: Value 'None' for application does not match expression '^(?:(?:[a-z\d\-]{1,100}\~)?(?:(?!\-)[a-z\d\-\.]{1,100}:)?(?!-)[a-z\d\-]{0,99}[a-z\d])$'
</code>```

Docker file

```<code>    FROM ubuntu:16.04
    RUN apt-get upgrade
    RUN apt-get update

    RUN apt-get install -y wget
    RUN apt-get install -y curl
    RUN apt-get install -y apt-transport-https

    RUN echo "deb https://packages.cloud.google.com/apt cloud-sdk-xenial main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

    RUN wget -O - https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -

    RUN apt-get update
    RUN cat /etc/apt/sources.list.d/google-cloud-sdk.list

    RUN apt-get install -y google-cloud-sdk
    RUN apt-get install -y google-cloud-sdk-app-engine-python

    WORKDIR /mycodepath
    EXPOSE 8080
</code>```

答:
My version of dev_appserver started doing the same.

I dug onto the code and found that the argument parser sets an empty app_id command-line argument to "None" (yes, that's a String not a NoneType). Incidentally, the app_id regex does not match for uppercase characters and thus the ValidationError triggers. (I'm glad that's the case or else it would've caused trickier bugs by silently making my application's name 'None')

My workaround for now is to explicitly pass in the name of your application from the command line with the -A flag. Note that this overrides the application variable in the app.yaml configuration.

I was thinking my version of argparse was broken but now it sounds like a dev_appserver bug.

Body:
I started seeing this issue after upgrading docker container. I couldn't find a way to use an older package for app engine. Using options =157.x.y to get older versions doesn't work in apt-get.

Failure log:

Traceback (most recent call last):
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 103, in <module>
    _run_file(__file__, globals())
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 97, in _run_file
    execfile(_PATHS.script_file(script_name), globals_)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 322, in <module>
    main()
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 310, in main
    dev_server.start(options)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 106, in start
    env_variables=parsed_env_variables)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 851, in __init__
    env_variables)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 131, in __init__
    self._config_path)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 443, in _parse_configuration
    config.application = self._forced_app_id
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 361, in __setattr__
    value = self.GetValidator(key)(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 599, in __call__
    return self.Validate(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 881, in Validate
    return self.validator(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 599, in __call__
    return self.Validate(value, key)
  File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/validation.py", line 955, in Validate
    '\'%s\'' % (value, key, self.re.pattern))
google.appengine.api.validation.ValidationError: Value 'None' for application does not match expression '^(?:(?:[a-z\d\-]{1,100}\~)?(?:(?!\-)[a-z\d\-\.]{1,100}:)?(?!-)[a-z\d\-]{0,99}[a-z\d])$'

Docker file

    FROM ubuntu:16.04
    RUN apt-get upgrade
    RUN apt-get update

    RUN apt-get install -y wget
    RUN apt-get install -y curl
    RUN apt-get install -y apt-transport-https

    RUN echo "deb https://packages.cloud.google.com/apt cloud-sdk-xenial main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

    RUN wget -O - https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -

    RUN apt-get update
    RUN cat /etc/apt/sources.list.d/google-cloud-sdk.list

    RUN apt-get install -y google-cloud-sdk
    RUN apt-get install -y google-cloud-sdk-app-engine-python

    WORKDIR /mycodepath
    EXPOSE 8080


问:
A problem in Updation of the record c#
i don't know why every time i perform update of my record, the query from which i update do not increments the ID from 0 to 1 and always it takes 0.. i don't know how do i increment my id to 1 and so far.. please explain.. :/ .. my code is :</p>

```<code>private void btnUpdate_Click(object sender, EventArgs e)
            {
                int CustomerID =0;
                SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;
                Initial Catalog=Gym;Integrated Security=True");
                SqlCommand cmd  = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                BindGridView();
            }

private void BindGridView()
        {
            SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=Gym;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select * from Customer", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgView_CustomerInfo.DataSource = dt.DefaultView;
        }
</code>```

答: You need to use Command.ExecuteNonQuery() instead.

ContentLicense: CC BY-SA 2.5

Title: A problem in Updation of the record c#

Body:
i don't know why every time i perform update of my record, the query from which i update do not increments the ID from 0 to 1 and always it takes 0.. i don't know how do i increment my id to 1 and so far.. please explain.. :/ .. my code is :

private void btnUpdate_Click(object sender, EventArgs e)
            {
                int CustomerID =0;
                SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;
                Initial Catalog=Gym;Integrated Security=True");
                SqlCommand cmd  = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                BindGridView();
            }

private void BindGridView()
        {
            SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=Gym;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select * from Customer", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgView_CustomerInfo.DataSource = dt.DefaultView;
        }


问:
how to add authentication to aws api gateway call in NodeJS
I'm calling AWS APi Gateway from node, using the following options:

```<code>var post_options = {
        host: 'myurl.execute-api.us-west-2.amazonaws.com',
        port: '443'
        path: '/staging/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };
</code>```

The call is made in the following way:

```<code>http.post(post_options, post_data, function(res){
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                console.log(chunk);
            });
        });
</code>```

The response I get back is:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: Yl1rUhK7Bmaq57ckHvK1E32tqNqDs4GC078yek3_23_RMefXUGJAdA==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
name: undefined
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: nJ3dotCRum8XudR6v0PinqzDjjPCX3N5TmoM2fNQSJK9BLn8jJEWqg==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
</code>```

I think, I'm getting "Bad request" because I did not pass any authentication information to my call.
What is the proper syntax to add such auth information?

答:
API Gateway doesn't support chunked encoding, is that what you are trying to use on the backend? If the response headers back through API Gateway indicate that we should be using chunked encoding, there might be an issue.

You shouldn't receive this error regardless, but I want to determine more specifics about your API/backend.

Body:
I'm calling AWS APi Gateway from node, using the following options:

var post_options = {
        host: 'myurl.execute-api.us-west-2.amazonaws.com',
        port: '443'
        path: '/staging/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

The call is made in the following way:

http.post(post_options, post_data, function(res){
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                console.log(chunk);
            });
        });

The response I get back is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>

ERROR

The request could not be satisfied.

Bad request.

Generated by cloudfront (CloudFront)
Request ID: Yl1rUhK7Bmaq57ckHvK1E32tqNqDs4GC078yek3_23_RMefXUGJAdA==

<ADDRESS>
</ADDRESS>

name: undefined
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>

ERROR

The request could not be satisfied.

Bad request.

Generated by cloudfront (CloudFront)
Request ID: nJ3dotCRum8XudR6v0PinqzDjjPCX3N5TmoM2fNQSJK9BLn8jJEWqg==

<ADDRESS>
</ADDRESS>

I think, I'm getting "Bad request" because I did not pass any authentication information to my call.
What is the proper syntax to add such auth information?


问:
Passing Class Memeber function to different class
I'm sure this can be done, but it seems really complex so i will do my best to explain.

I have a basic class

```<code>class TestClass {
public:

    void Test1(int a) { cout << "You chose option 1. The answer is " << a << "\n"; }
    void Test2(int b) { cout << "You chose option 2. The answer is " << b << "\n"; }
    void Run(int i) {
        if (i == 0) {
            Test1(2);
        }
        else {
            Test1(5);
        }
    }
};
</code>```

And also a secondary class

```<code>class ExecuteFunctions {
public:
    template<class _Fn, class... _Args>
    void CPU(_Fn&& _Fx, _Args&&... _Ax);
};

template<class _Fn, class... _Args>
void ExecuteFunctions::CPU(_Fn&& _Fx, _Args&&... _Ax)
{
    _Fx(forward<_Args>(_Ax)...);
}
</code>```

But when i try and call TestClass::Run using the execute class from main it wont compile saying it doesnt match the argument list.

```<code>Execute.CPU(TestClass::Run,Option);
</code>```

I can call the function without the ExecuteClass and can also call it in a new thread

```<code>int Option = 1;
TestClass T;
thread TestThread(&TestClass::Run, &T, Option);
</code>```

Is what i'm trying to do actually possible?

答:
You need to have an instance of object to call your run method on, simply _Fx(forward<_Args>(_Ax)...); is not enough. The fix is as follows:

```<code>ExecuteFunctions Execute;
int Option = 1;
TestClass T;
Execute.CPU(std::bind(&TestClass::Run, &T, std::placeholders::_1),Option);
</code>```

Body:
I'm sure this can be done, but it seems really complex so i will do my best to explain.

I have a basic class

class TestClass {
public:

    void Test1(int a) { cout << "You chose option 1. The answer is " << a << "\n"; }
    void Test2(int b) { cout << "You chose option 2. The answer is " << b << "\n"; }
    void Run(int i) {
        if (i == 0) {
            Test1(2);
        }
        else {
            Test1(5);
        }
    }
};

And also a secondary class

class ExecuteFunctions {
public:
    template<class _Fn, class... _Args>
    void CPU(_Fn&& _Fx, _Args&&... _Ax);
};

template<class _Fn, class... _Args>
void ExecuteFunctions::CPU(_Fn&& _Fx, _Args&&... _Ax)
{
    _Fx(forward<_Args>(_Ax)...);
}

But when i try and call TestClass::Run using the execute class from main it wont compile saying it doesnt match the argument list.

Execute.CPU(TestClass::Run,Option);

I can call the function without the ExecuteClass and can also call it in a new thread

int Option = 1;
TestClass T;
thread TestThread(&TestClass::Run, &T, Option);

Is what i'm trying to do actually possible?

Body:
You need to have an instance of object to call your run method on, simply _Fx(forward<_Args>(_Ax)...); is not enough. The fix is as follows:

ExecuteFunctions Execute;
int Option = 1;
TestClass T;
Execute.CPU(std::bind(&TestClass::Run, &T, std::placeholders::_1),Option);


问:
Divide a rectangle into 2 triangles along diagonal using css
I want to make a div into 2 triangles (as shown in below, no problem if 1 is background of parent) upper one with one color and lower one with another. I dont mind how it is implemented but i want to do it in css (not javascript). I tried with css rotation, (code below), but its not responsive. In smaller or wider screen it is distorted . Any way to implement this in css?

body {
  background: #eee;
}

.darker {
  position: fixed;
  top: -94%;
  left: -10%;
  width: 150%;
  height: 150%;
  background: #dd4f39;
  -webkit-transform: rotate(30deg);
          transform: rotate(30deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="darker"> </div></code>```

答:
Please Use this code snippet.

div {
  width: 100%;
  height: 100px;
}

.diagonalRising {
  border: 1pt solid black;
  background: linear-gradient(to right bottom, #eeeeee 0%, #eeeeee 49.9%, #eeeeee 50%, #000000 51%, #dd4f39 51.1%, #dd4f39 100%);
}

.diagonalFalling {
  background: linear-gradient(to right top, #eeeeee 0%, #eeeeee 49.9%, #000000 50%, #000000 51%, #dd4f39 51.1%, #dd4f39 100%);
}

.diagonalCross {
  position: relative;
  background: linear-gradient(to right bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 49.9%, rgba(0, 0, 0, 1) 50%, rgba(0, 0, 0, 1) 51%, rgba(0, 0, 0, 0) 51.1%, rgba(0, 0, 0, 0) 100%);
}

.diagonalCross:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
  background: linear-gradient(to right top, #ffffff 0%, #ffffff 49.9%, #000000 50%, #000000 51%, #ffffff 51.1%, #ffffff 100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="diagonalRising"></div>
<div class="diagonalFalling"></div>
<div class="diagonalCross"></div></code>```

Body:
Please Use this code snippet.

div {
  width: 100%;
  height: 100px;
}

.diagonalRising {
  border: 1pt solid black;
  background: linear-gradient(to right bottom, #eeeeee 0%, #eeeeee 49.9%, #eeeeee 50%, #000000 51%, #dd4f39 51.1%, #dd4f39 100%);
}

.diagonalFalling {
  background: linear-gradient(to right top, #eeeeee 0%, #eeeeee 49.9%, #000000 50%, #000000 51%, #dd4f39 51.1%, #dd4f39 100%);
}

.diagonalCross {
  position: relative;
  background: linear-gradient(to right bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 49.9%, rgba(0, 0, 0, 1) 50%, rgba(0, 0, 0, 1) 51%, rgba(0, 0, 0, 0) 51.1%, rgba(0, 0, 0, 0) 100%);
}

.diagonalCross:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
  background: linear-gradient(to right top, #ffffff 0%, #ffffff 49.9%, #000000 50%, #000000 51%, #ffffff 51.1%, #ffffff 100%);
}

<div class="diagonalRising"></div>
<div class="diagonalFalling"></div>
<div class="diagonalCross"></div>


答:
Without any info I'd guess that it outputs info which you don't read so it blocks and waits until you do... It's like echoing into the pipe when there is nothing on the other side...

I'd recommend looking into http://stackoverflow.com/a/32758464

Title: Python - Paramiko isn't running a remote script properly


问:
Code execution after __halt_compiler
Next time in my life i see some bytecode after function __halt_compiler. In this case it's symfony installer. How to do that ? How to generate code which will be executable after __halt_compiler ?</p>

答:
I guess you mean https://symfony.com/installer, a PHAR archive that starts like this:

```<code>#!/usr/bin/env php
<?php
/**
 * Generated by Box.
 *
 * @link https://github.com/herrera-io/php-box/
 */
if (class_exists('Phar')) {
Phar::mapPhar('default.phar');
require 'phar://' . __FILE__ . '/symfony';
}
__HALT_COMPILER(); ?>
</code>```

Conceptually speaking, PHAR archives are not too different from self-extracting ZIP files (in fact ZIP is among the supported internal formats). The archive contains:

A stub, which is the short PHP script you can see.

A manifest with a description of the archive contentes

An archive with the contents themselves

An optional signature

The stub on top is a regular PHP script so the PHAR archive can run with the regular PHP interpreter rather than requiring a dedicated executable:

```<code>php foo.phar
</code>```

This script block ends with __HALT_COMPILER(); to::

Prevent the rest of the file from being parsed and possibly executed as PHP code (the main script does all that's needed for the initial phase).

Populate the __COMPILER_HALT_OFFSET__ constant so the PHAR library can easily detect where archived data starts.

This scripts does three things:

Detect whether the Phar library is available in the computer.

Load current file as Phar archive and register the manifest with the content description.

Execute the symfony script inside the archive, which is the actual installer code.

Title: Code execution after __halt_compiler

Body:
I guess you mean https://symfony.com/installer, a PHAR archive that starts like this:

#!/usr/bin/env php
<?php
/**
 * Generated by Box.
 *
 * @link https://github.com/herrera-io/php-box/
 */
if (class_exists('Phar')) {
Phar::mapPhar('default.phar');
require 'phar://' . __FILE__ . '/symfony';
}
__HALT_COMPILER(); ?>

Conceptually speaking, PHAR archives are not too different from self-extracting ZIP files (in fact ZIP is among the supported internal formats). The archive contains:

A stub, which is the short PHP script you can see.

A manifest with a description of the archive contentes

An archive with the contents themselves

An optional signature

The stub on top is a regular PHP script so the PHAR archive can run with the regular PHP interpreter rather than requiring a dedicated executable:

php foo.phar

This script block ends with __HALT_COMPILER(); to::

Prevent the rest of the file from being parsed and possibly executed as PHP code (the main script does all that's needed for the initial phase).

Populate the __COMPILER_HALT_OFFSET__ constant so the PHAR library can easily detect where archived data starts.

This scripts does three things:

Detect whether the Phar library is available in the computer.

Load current file as Phar archive and register the manifest with the content description.

Execute the symfony script inside the archive, which is the actual installer code.


问:
Execute method within linq
Is it possible to execute a method with in Linq ie

```<code>var lst = (from ls in testEntity.Month where ls .Month1.ToString()  == hello() select ls).ToList();

     private string  hello()

        {
            return "8";
        }
</code>```

I know that Linq will not execute itself, while executing this i am getting the following error

LINQ to Entities does not recognize the method  'System.String ToString()'  and this method cannot be translated into a store expression.

答:
Generally, you can call methods in LINQ without problems.
The problem you are encountering here is specific to LINQ to Entities. L2E needs to translate all your method calls into the appropriate database statements, and for the method you called it doesn't know how to translate it.

You could rewrite your hello() function to return an expression:

```<code>public Expression<Func<string>> hello() {
    return () => "8";
}
</code>```

that way L2E can translate the statements. If that works, depends on your real code, of course.

Title: Execute method within linq

Body:
Is it possible to execute a method with in Linq ie

var lst = (from ls in testEntity.Month where ls .Month1.ToString()  == hello() select ls).ToList();

     private string  hello()

        {
            return "8";
        }

I know that Linq will not execute itself, while executing this i am getting the following error

LINQ to Entities does not recognize the method  'System.String ToString()'  and this method cannot be translated into a store expression.

Body:
Generally, you can call methods in LINQ without problems.
The problem you are encountering here is specific to LINQ to Entities. L2E needs to translate all your method calls into the appropriate database statements, and for the method you called it doesn't know how to translate it.

You could rewrite your hello() function to return an expression:

public Expression<Func<string>> hello() {
    return () => "8";
}

that way L2E can translate the statements. If that works, depends on your real code, of course.


问:
Twitter and R ( Curl:curl_fetch_memory Error)
Here is my Code :

```<code>install.packages('twitteR',dependencies=T)
install.packages('httpRequest')
install.packages('purrr')
install.packages('httk')
install.packages('httpuv')
install.packages("base64enc")

library(twitteR)
library(plyr)
library(purrr)
library(httk)
library(httpuv)

my_key<- "*****"
my_secret<- "*****"
my_access_token<-NULL
my_access_secret<-NULL
setup_twitter_oauth(my_key,my_secret,my_access_token,my_access_secret
                    )

tweets=searchTwitter('#abortion',n=1500)
length(tweets)
tweets.text=laply(tweets,function(t)t$getText())
pos=scan('positive-words.text',What='character',comment.char=';')
</code>```

I am getting the following error : Error in curl::curl_fetch_memory(url, handle = handle) :
  Couldn't connect to server.

Please provide me how to proceed.

Thanks

答:
Here is a minimal working example. I believe you need to provide all four keys/secrets.</p>

```<code>library(twitteR)
library(ROAuth)

api_key <- "***"
api_secret <- "***"
access_token <- "***"
access_token_secret <- "***"
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)

tweets <- searchTwitter('#abortion', n = 10)
df <- twListToDF(tweets)
</code>```

Body:
Here is my Code :

install.packages('twitteR',dependencies=T)
install.packages('httpRequest')
install.packages('purrr')
install.packages('httk')
install.packages('httpuv')
install.packages("base64enc")

library(twitteR)
library(plyr)
library(purrr)
library(httk)
library(httpuv)

my_key<- "*****"
my_secret<- "*****"
my_access_token<-NULL
my_access_secret<-NULL
setup_twitter_oauth(my_key,my_secret,my_access_token,my_access_secret
                    )

tweets=searchTwitter('#abortion',n=1500)
length(tweets)
tweets.text=laply(tweets,function(t)t$getText())
pos=scan('positive-words.text',What='character',comment.char=';')

I am getting the following error : Error in curl::curl_fetch_memory(url, handle = handle) :
  Couldn't connect to server.

Please provide me how to proceed.

Thanks

Body:
Here is a minimal working example. I believe you need to provide all four keys/secrets.

library(twitteR)
library(ROAuth)

api_key <- "***"
api_secret <- "***"
access_token <- "***"
access_token_secret <- "***"
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)

tweets <- searchTwitter('#abortion', n = 10)
df <- twListToDF(tweets)


问:
Passing attributes as parameters and inserting into table
I have a database table called "User" with the following attributes:
UserId, Name, CreatedAt, CreatedBy, ModifiedAt, ModifiedBy, Address, City, Province, Country, PostCode, Phone.

What I need to do is create a class named as User Repository with a methode CreateUser. The method will take all attributes as parameter and will insert into tables respectively i.e. User

Can anyone guide me how to do this?

答:
create a class with all your attributes

```<code>public class user {

public id UserId {get;set;}
public string Name {get;set;}
public string CreatedAt {get;set;}

public string createdBy {get;set;}
public string modifiedAt {get;set;}

public string modifiedBy {get;set;}
public string address {get;set;}

public string city {get;set;}
}
</code>```

Create a repository - assuming you have UserDbContext.

```<code>// following method will insert new record into the database.

    public void CreateUser(user data){
    _ctxmain = new UserDbContext();
    var newUser = new user {
    UserId = data.UserId,
    Name = data.Name,
    CreatedAt = data.CreatedAt,
    CreatedBy = data.CreatedBy,
    modifiedBy = data.modifiedBy,
    modifiedAt = data.modifiedAt,
    address = data.address,
    city = data.city

    };

    _ctxmain.User.Add(newUser);
    _ctxmain.SaveChanges();  // saving details to the User table in database

    }
</code>```

Body:
create a class with all your attributes

public class user {

public id UserId {get;set;}
public string Name {get;set;}
public string CreatedAt {get;set;}

public string createdBy {get;set;}
public string modifiedAt {get;set;}

public string modifiedBy {get;set;}
public string address {get;set;}

public string city {get;set;}
}

Create a repository - assuming you have UserDbContext.

// following method will insert new record into the database.

    public void CreateUser(user data){
    _ctxmain = new UserDbContext();
    var newUser = new user {
    UserId = data.UserId,
    Name = data.Name,
    CreatedAt = data.CreatedAt,
    CreatedBy = data.CreatedBy,
    modifiedBy = data.modifiedBy,
    modifiedAt = data.modifiedAt,
    address = data.address,
    city = data.city

    };

    _ctxmain.User.Add(newUser);
    _ctxmain.SaveChanges();  // saving details to the User table in database

    }


问:
How to use Heroku as API proxy (Node.js)?
I try to use Heroku as a layer of for flickr api because GFW has blocked flickr, and perhaps other public api in the future. I can run the index.js on a local environment or on AWS, but failed to run on Heroku. I did a bit of research and it looks like Heroku only support HTTP server as it has a layer outside of the dyno. So I wrote my code as followed:

```<code>var http = require('http');
var qs = require('querystring');
var curl = require('request');
var Port = 80;
var httpServer = http.createServer(app).listen(Port);

function app(request, response) {
  if(request.method === "GET") {
    response.writeHead(401, {'Content-Type': 'text/html'});
    response.write('<!doctype html><html><head><title>401</title></head><body>401: Unauthorized</body></html>');
    response.end();
  } else if(request.method === "POST") {
    if (request.url === "/") {
      var requestBody = '';
      request.on('data', function(data) {
        requestBody += data;
        if(requestBody.length > 1e7) {
          response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
          response.end('413: Request Entity Too Large');
        }
      });
      request.on('end', function() {
        var formData = qs.parse(requestBody);
        if (formData.request === 'list') {
          var url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_api_key}}&user_id={{insert_user_id}}&format=json';
        } else if (formData.request === 'photoset') {
          var url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=' + formData.id + '&api_key={{insert_api_key}}&user_id={{insert_user_id}}&extras=url_o&format=json';
        } else {
          response.writeHead(400, 'Bad Request', {'Content-Type': 'text/html'});
          response.end('400: Bad Request');
          return;
        }
        getrequest(url, (err, body)=>{
          if (err) {
            response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
            response.end('502: Bad Gateway');
          } else {
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(body);
            response.end();
          }
        });
      });
    } else {
      response.writeHead(404, 'Resource Not Found', {'Content-Type': 'text/html'});
      response.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
    }
  } else {
    response.writeHead(405, 'Method Not Supported', {'Content-Type': 'text/html'});
    return response.end('<!doctype html><html><head><title>405</title></head><body>405: Method Not Supported</body></html>');
  }
};
function getrequest(url, callback){
  curl(url, (error, response, body) => {
    if (error) {
      callback(error);
      return;
    }
    callback(null, body);
  });
}
</code>```

The autobuild completed but I get 506 error when I sent POST request to my dyno's url. When I run heroku run node index.js it throws the following err message:

```<code>events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES 0.0.0.0:80
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at Server._listen2 (net.js:1245:19)
    at listen (net.js:1294:10)
    at Server.listen (net.js:1390:5)
    at Object.<anonymous> (/app/index.js:5:41)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
</code>```

答:
.listen(process.env.PORT || Port)

Heroku require a dynamic PORT of which you didn't set.

Body:
I try to use Heroku as a layer of for flickr api because GFW has blocked flickr, and perhaps other public api in the future. I can run the index.js on a local environment or on AWS, but failed to run on Heroku. I did a bit of research and it looks like Heroku only support HTTP server as it has a layer outside of the dyno. So I wrote my code as followed:

var http = require('http');
var qs = require('querystring');
var curl = require('request');
var Port = 80;
var httpServer = http.createServer(app).listen(Port);

function app(request, response) {
  if(request.method === "GET") {
    response.writeHead(401, {'Content-Type': 'text/html'});
    response.write('<!doctype html><title>401</title>401: Unauthorized');
    response.end();
  } else if(request.method === "POST") {
    if (request.url === "/") {
      var requestBody = '';
      request.on('data', function(data) {
        requestBody += data;
        if(requestBody.length > 1e7) {
          response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
          response.end('413: Request Entity Too Large');
        }
      });
      request.on('end', function() {
        var formData = qs.parse(requestBody);
        if (formData.request === 'list') {
          var url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_api_key}}&user_id={{insert_user_id}}&format=json';
        } else if (formData.request === 'photoset') {
          var url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=' + formData.id + '&api_key={{insert_api_key}}&user_id={{insert_user_id}}&extras=url_o&format=json';
        } else {
          response.writeHead(400, 'Bad Request', {'Content-Type': 'text/html'});
          response.end('400: Bad Request');
          return;
        }
        getrequest(url, (err, body)=>{
          if (err) {
            response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
            response.end('502: Bad Gateway');
          } else {
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(body);
            response.end();
          }
        });
      });
    } else {
      response.writeHead(404, 'Resource Not Found', {'Content-Type': 'text/html'});
      response.end('<!doctype html><title>404</title>404: Resource Not Found');
    }
  } else {
    response.writeHead(405, 'Method Not Supported', {'Content-Type': 'text/html'});
    return response.end('<!doctype html><title>405</title>405: Method Not Supported');
  }
};
function getrequest(url, callback){
  curl(url, (error, response, body) => {
    if (error) {
      callback(error);
      return;
    }
    callback(null, body);
  });
}

The autobuild completed but I get 506 error when I sent POST request to my dyno's url. When I run heroku run node index.js it throws the following err message:

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES 0.0.0.0:80
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at Server._listen2 (net.js:1245:19)
    at listen (net.js:1294:10)
    at Server.listen (net.js:1390:5)
    at Object.<anonymous> (/app/index.js:5:41)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)


问:
Testing rails API for sign-up with devise. Error: "Missing 'confirm_success_url' parameter."
I am trying to use devise and devise_token_auth for authentication in my app.

I am overriding the registration controller as follow:

```<code>module Overrides
  class RegistrationsController < DeviseTokenAuth::RegistrationsController

    ## I am doing these to go around the `Can't verify CSRF token authenticity` Error.
    # skip_before_action :valid_authenticity_token, only: :create
    protect_from_forgery :except => :create

    def sign_up_params
      params.require(:user).permit(:email, :password, :password_confirmation, :name, :nickname)
    end

  end
end
</code>```

I am also sending in my parameters using swagger docs api as follow:

```<code>swagger_api :create do
  summary "Sign up a new user"
  param :form, "user[email]", :string, :required, "Email of the new user"
  param :form, "user[password]", :string, :required, "Password of the new user"
  param :form, "user[password_confirmation]", :string, :required, "Retype Password of the new user"
  param :form, "user[name]", :string, :optional, "Name of the new user"
  param :form, "user[nickname]", :string, :optional, "Nick-Name of the new user"
  response :not_acceptable
  response :success
end
</code>```

This produces parameters on my terminal as follow:

```<code>Processing by Overrides::RegistrationsController#create as JSON
  Parameters: {"user"=>{"email"=>"sadf@fsd.fgs", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "name"=>"rgefsrfgrfdfsd", "nickname"=>"rgefsrfgrfdfsd"}}
</code>```

However, this request never hits my model, ( talkless of creating the new user ). On the page, however, I am having the following error:

And a Completed 403 Forbidden in 93ms (Views: 0.3ms | ActiveRecord: 0.0ms) on the terminal.

How can I go about solving this? Thanks

Update:

```<code>#route.rb:
namespace :api do
    namespace :v1 do

      mount_devise_token_auth_for 'User', at: 'auth', controllers: {
                                          confirmations:      'overrides/confirmations',
                                          passwords:          'overrides/passwords',
                                          registrations:      'overrides/registrations',
                                          sessions:           'overrides/sessions',
                                        }
      ...

    end
  end

#Countroller:
class ApiController < ApplicationController
  include DeviseTokenAuth::Concerns::SetUserByToken
  protect_from_forgery with: :null_session
end

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

#user.rb:
class User < ActiveRecord::Base
  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :confirmable, :omniauthable
  include DeviseTokenAuth::Concerns::User
</code>```

答:
The solution is just to set the default URL in config/initializer/devise_token_auth.rb:

```<code>DeviseTokenAuth.setup do |config|
    config.default_confirm_success_url = "confirmed"
end
</code>```

Body:
I am trying to use devise and devise_token_auth for authentication in my app.

I am overriding the registration controller as follow:

module Overrides
  class RegistrationsController < DeviseTokenAuth::RegistrationsController

    ## I am doing these to go around the `Can't verify CSRF token authenticity` Error.
    # skip_before_action :valid_authenticity_token, only: :create
    protect_from_forgery :except => :create

    def sign_up_params
      params.require(:user).permit(:email, :password, :password_confirmation, :name, :nickname)
    end

  end
end

I am also sending in my parameters using swagger docs api as follow:

swagger_api :create do
  summary "Sign up a new user"
  param :form, "user[email]", :string, :required, "Email of the new user"
  param :form, "user[password]", :string, :required, "Password of the new user"
  param :form, "user[password_confirmation]", :string, :required, "Retype Password of the new user"
  param :form, "user[name]", :string, :optional, "Name of the new user"
  param :form, "user[nickname]", :string, :optional, "Nick-Name of the new user"
  response :not_acceptable
  response :success
end

This produces parameters on my terminal as follow:

Processing by Overrides::RegistrationsController#create as JSON
  Parameters: {"user"=>{"email"=>"sadf@fsd.fgs", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "name"=>"rgefsrfgrfdfsd", "nickname"=>"rgefsrfgrfdfsd"}}

However, this request never hits my model, ( talkless of creating the new user ). On the page, however, I am having the following error:

And a Completed 403 Forbidden in 93ms (Views: 0.3ms | ActiveRecord: 0.0ms) on the terminal.

How can I go about solving this? Thanks

Update:

#route.rb:
namespace :api do
    namespace :v1 do

      mount_devise_token_auth_for 'User', at: 'auth', controllers: {
                                          confirmations:      'overrides/confirmations',
                                          passwords:          'overrides/passwords',
                                          registrations:      'overrides/registrations',
                                          sessions:           'overrides/sessions',
                                        }
      ...

    end
  end

#Countroller:
class ApiController < ApplicationController
  include DeviseTokenAuth::Concerns::SetUserByToken
  protect_from_forgery with: :null_session
end

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

#user.rb:
class User < ActiveRecord::Base
  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :confirmable, :omniauthable
  include DeviseTokenAuth::Concerns::User

Body:
The solution is just to set the default URL in config/initializer/devise_token_auth.rb:

DeviseTokenAuth.setup do |config|
    config.default_confirm_success_url = "confirmed"
end


问:
Do you know any free Bug Tracking System?

Possible Duplicates:

  Can anyone suggest a small, simple and free bugtracker?

  What is your bug/task tracking tool?

Hi,

Do you know any free Bug Tracking System that achieves the goals described in The Joel Test: 12 Steps to Better Code which says:

A minimal useful bug database must include the following data for every bug:

•complete steps to reproduce the bug

• expected behavior

• observed (buggy) behavior

• who it's assigned to

• whether it has been fixed or not

Thanks!

答: Hi you can compare systems here http://en.wikipedia.org/wiki/Comparison_of_issue-tracking_systems</p>


问:
How to show formatted text using javascript?
I have some values that I have written in php. The var here is derived from nl2br $ther. The code is written so that it removes certain words from the here array, but I do not want to remove some values such as

```<code>  "<br/>"
</code>```

and \n to preserve the formatting.
I tried the following code (and a combination of others but it is not working)

```<code><script = "javascript">
var r = <?php echo json_encode($t, JSON_HEX_TAG); ?>; // getting random nu.
 var here = <?php echo json_encode($ther, JSON_HEX_TAG); ?>;
 var jtotal = <?php echo json_encode($total, JSON_HEX_TAG); ?>;

var count =0;
for(var b=0; b < jtotal; b++)  {

if ((b==r) && (here[b] = "<br")) {
   document.write("<br");
}
else if ((b==r) && (here[b] = "/>")) {
 document.write("/>");
}
else if ((b==r) && (here[b] = "\n")) {
 document.write("\n");
}

 else if (b==r){
count = count+1;
document.write("____(" + count+ ")____");
r=r+2;
}

else {

    document.write(here[b] + " ");
}

</script>
</code>```

答:
```<code>    <script = "javascript">
var r = <?php echo json_encode($t, JSON_HEX_TAG); ?>; // getting random nu.
 var here = <?php echo json_encode($ther, JSON_HEX_TAG); ?>;
 var jtotal = <?php echo json_encode($total, JSON_HEX_TAG); ?>;

var count =0;
for(var b=0; b < jtotal; b++)  {

if ((b==r) && (here[b] == "<br")) {
   document.write("<br");
}
else if ((b==r) && (here[b] == "/>")) {
 document.write("/>");
}
else if ((b==r) && (here[b] == "\n")) {
 document.write("\n");
}

 else if (b==r){
count = count+1;
document.write("____(" + count+ ")____");
r=r+2;
}

else {

    document.write(here[b] + " ");
}
</code>```

I think your Comparison Operators is missing "=".
Hope helpful.

Body:
I have some values that I have written in php. The var here is derived from nl2br $ther. The code is written so that it removes certain words from the here array, but I do not want to remove some values such as

  "
"

and \n to preserve the formatting.
I tried the following code (and a combination of others but it is not working)

Body:
    <script = "javascript">
var r = <?php echo json_encode($t, JSON_HEX_TAG); ?>; // getting random nu.
 var here = <?php echo json_encode($ther, JSON_HEX_TAG); ?>;
 var jtotal = <?php echo json_encode($total, JSON_HEX_TAG); ?>;

var count =0;
for(var b=0; b < jtotal; b++)  {

if ((b==r) && (here[b] == "<br")) {
   document.write("<br");
}
else if ((b==r) && (here[b] == "/>")) {
 document.write("/>");
}
else if ((b==r) && (here[b] == "\n")) {
 document.write("\n");
}

 else if (b==r){
count = count+1;
document.write("____(" + count+ ")____");
r=r+2;
}

else {

    document.write(here[b] + " ");
}

I think your Comparison Operators is missing "=".
Hope helpful.


问:
Subsetting on a tibble using "[]" gives "object not found" error
The article on dplyr here says "[]" (square brackets) can be used to subset filtered Tibbles like this:

```<code>filter(mammals, adult_body_mass_g > 1e7)[ , 3]
</code>```

But I am getting an "object not found" error.
Here is the replication of the error on a more known dataset "iris"

```<code>library(dplyr)
iris %>% filter(Sepal.Length>6) [,c(1:3)]
</code>```

Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
    object 'Sepal.Length' not found

I also want to mention that I am deliberately not preferring to use the native subsetting in dplyr using select() as I need a vector output and not a data frame on a single column. Unfortunately, dplyr always forces a data frame output (for good reasons).

答:
You need an extra pipe:

```<code>iris %>% filter(Sepal.Length>6) %>% .[,1:3]
</code>```

Sorry, forgot the . before the brackets.

Note: Your code will probably be more readable if you stick to the tidyverse syntax and use select as the last operation.

```<code>iris %>%
     filter(Sepal.Length > 6) %>%
     select(1:3)
</code>```

Body:
The article on dplyr here says "[]" (square brackets) can be used to subset filtered Tibbles like this:

filter(mammals, adult_body_mass_g > 1e7)[ , 3]

But I am getting an "object not found" error.
Here is the replication of the error on a more known dataset "iris"

library(dplyr)
iris %>% filter(Sepal.Length>6) [,c(1:3)]

Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
    object 'Sepal.Length' not found

I also want to mention that I am deliberately not preferring to use the native subsetting in dplyr using select() as I need a vector output and not a data frame on a single column. Unfortunately, dplyr always forces a data frame output (for good reasons).

Body:
You need an extra pipe:

iris %>% filter(Sepal.Length>6) %>% .[,1:3]

Sorry, forgot the . before the brackets.

Note: Your code will probably be more readable if you stick to the tidyverse syntax and use select as the last operation.

iris %>%
     filter(Sepal.Length > 6) %>%
     select(1:3)


问:
How to run a custom mongodb query in spring-boot
I have a spring-boot application and I am trying to run this below query using it.

```<code>db.userActivity.findAndModify(
{
   query: { 'appId' : 1234, 'status' : 0},
   update: { $inc: { 'status': 1 } }
});
</code>```

I did try something like this but it didn't work

```<code>public interface UserActivityRepository extends MongoRepository<UserActivity, String> {

    /**
     * Find all documents in the database
     * @param appId
     * @param status
     * @return
     */
    @Query("{ 'appId' : ?0, 'status' : ?1}")
    public List<UserActivity> findAllDocuments(long appId, int status);

    /**
     * Find all documents by appId whose state is unread
     * and marked them read after reading
     * @param appId
     * @return
     */
    @Query("db.userActivity.findAndModify({ query: { 'appId' : ?0, 'status' : ?1}, update: { $inc: { 'status': 1 } } })")
    public List<UserActivity> findAndUpdateAllUnreadDocuments(long appId, int status);
}
</code>```

Could you please tell what I am doing wrong?

答:
Well, I should admit I couldn't find a way to update the document using custom mongo query. But, found a way of doing it using java8 streams.

```<code> userActivityRepository.save(userActivityRepository.findAllDocuments(1234, 0)
.stream()
.peek((user) -> user.setStatus(user.getStatus() + 1))
.collect(Collectors.toList()));
</code>```

The above statement uses userActivityRepository.findAllDocuments for fetching the records with a criteria then uses OOTB MongoRepository save(Iterable<S> entites) method to update the documents.

In place of $inc have incremented the status field.

This may not be what you are expecting, but just a possible solution if you  wish to implement.

Hope this helps!

Body:
I have a spring-boot application and I am trying to run this below query using it.

db.userActivity.findAndModify(
{
   query: { 'appId' : 1234, 'status' : 0},
   update: { $inc: { 'status': 1 } }
});

I did try something like this but it didn't work

public interface UserActivityRepository extends MongoRepository<UserActivity, String> {

    /**
     * Find all documents in the database
     * @param appId
     * @param status
     * @return
     */
    @Query("{ 'appId' : ?0, 'status' : ?1}")
    public List<UserActivity> findAllDocuments(long appId, int status);

    /**
     * Find all documents by appId whose state is unread
     * and marked them read after reading
     * @param appId
     * @return
     */
    @Query("db.userActivity.findAndModify({ query: { 'appId' : ?0, 'status' : ?1}, update: { $inc: { 'status': 1 } } })")
    public List<UserActivity> findAndUpdateAllUnreadDocuments(long appId, int status);
}

Could you please tell what I am doing wrong?

Body:
Well, I should admit I couldn't find a way to update the document using custom mongo query. But, found a way of doing it using java8 streams.

 userActivityRepository.save(userActivityRepository.findAllDocuments(1234, 0)
.stream()
.peek((user) -> user.setStatus(user.getStatus() + 1))
.collect(Collectors.toList()));

The above statement uses userActivityRepository.findAllDocuments for fetching the records with a criteria then uses OOTB MongoRepository save(Iterable<S> entites) method to update the documents.

In place of $inc have incremented the status field.

This may not be what you are expecting, but just a possible solution if you  wish to implement.

Hope this helps!


问:
Java: Long result = -1: cannot convert from int to long
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

```<code>Long result = -1;
</code>```

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

答:
There is no conversion between the object Long and int so you need to make it from long. Adding a L makes the integer -1 into a long (-1L):

```<code>Long result = -1L;
</code>```

However there is a conversion from int a long so this works:

```<code>long result = -1;
</code>```

Therefore you can write like this aswell:

```<code>Long result = (long) -1;
</code>```

Converting from a primitive (int, long etc) to a Wrapper object (Integer, Long etc) is called autoboxing, read more here.

Body:
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

Body:
There is no conversion between the object Long and int so you need to make it from long. Adding a L makes the integer -1 into a long (-1L):

Long result = -1L;

However there is a conversion from int a long so this works:

long result = -1;

Therefore you can write like this aswell:

Long result = (long) -1;

Converting from a primitive (int, long etc) to a Wrapper object (Integer, Long etc) is called autoboxing, read more here.


问:
Windows Store App - Update hooks and trigger
(somehwat related to this and this)

tl;dr: Are there some kind of update hooks for desktop-bridge converted apps distributed via the Windows Store? How can I trigger an app update from a converted app?

I use the Windows Store to distribute my electron-powered application. I wonder if there's any way to tell whether the app was updated recently or not?

There's two and a half issues I have:

1) I store settings in AppData\Roaming which seems to be virtualized for store apps. Sadly, it seems like the whole directory was cleared when I pulled the app update from the store and thus all the user settings were lost. Is there any way to keep the AppData on app updates?

2) How can I trigger an app update from within the converted app? For what I understood the store won't auto-update apps (not even if it's marked as mandatory). Having to fire up VS and writing an exe that uses some store API to update the app seems like overkill. Is there any easier solution?

2½) How do I know if my app was updated? I thought about storing the app version in the settings and comapring that with the running version on app start. But due to my issue 1) that's not working.

Thanks in advance.

Feel free to post more answers. The accepted answer, albeit being correct and pointing the right direction, still feels cumbersome. In an ideal world there would be a drop-in solution that you'd just npm i. So be encouraged to find/build simpler solutions. (Many thanks to the John Stephan Wick whatsoever!)

答:
To get notified when an update has been deployed for your UWP or DesktopBridge app, you can implement an UpdateTask:
docs / sample code

You can also check at runtime what is the version of your package:
https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.packageversion

Your app will get updates automatically, but we won't update it while the user is running your app. If the app process keeps running, we will eventually force update it, but only when the screen is locked. You can also check from your code if an update is available and take action accordingly:
https://blogs.msdn.microsoft.com/appinstaller/2016/11/11/developer-controlled-app-updates/

Your appdata should persist across app updates. If that's not what you are seeing, please post a separate dedicated question about this with repro details and we will follow up.

Thanks!


问:
Create Subsections in UITableView (Swift 2.3)
I am currenlty working on an app, and I have to display soccer fixtures in a TableView.

The table view should look like this (see picture above)
As a tree view it should look like :

```<code>Date
    League
        Fixture1
        Fixture2
    League2
        Fixture1
        Fixture2
Date
    League
        Fixture1
        Fixture2
    League2
        Fixture1
        Fixture2
</code>```

So I created a DataManager in order to manage my dummy data :

```<code>import Foundation
import RxSwift
import RxCocoa

class DataManager {
    var games = [Int:[League:[Game]]]()

    static let shared = DataManager()

    private init() {
        self.buildDummyData()
    }

    func buildDummyData() {

        let today = NSDate()
        let tomorrow = NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: 1,
                toDate: today,
                options: []
        )
        let day_after = NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: 2,
                toDate: today,
                options: []
        )

        let premierLeague = League(title: "Premier League", iName: "england")
        let ligueUn = League(title: "Ligue 1", iName: "France Contest")
        let europaLeague = League(title: "Europa League", iName: "Europa Contest")

        let game1 = Game(ftName: "Monaco", ftLogo: "sampleLogo", stName: "Paris SG", stLogo: "sampleLogo", time: "16:30", date: today, league: ligueUn)

        let game2 = Game(ftName: "Man U.", ftLogo: "sampleLogo", stName: "Liverpool", stLogo: "sampleLogo", time: "20:30", date: tomorrow!, league: premierLeague)

        let game3 = Game(ftName: "Celta Vigo", ftLogo: "sampleLogo", stName: "Man U.", stLogo: "sampleLogo", time: "19:45", date: day_after!, league: europaLeague)

        let game4 = Game(ftName: "ASSE", ftLogo: "sampleLogo", stName: "Man U.", stLogo: "sampleLogo", time: "19:45", date: day_after!, league: europaLeague)

        games = [0: [ligueUn: [game1]], 1: [premierLeague: [game2]], 2: [europaLeague: [game3, game4]]]

    }

}
</code>```

And my ViewController.swift :

```<code>import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    let dataManager = DataManager.shared

    let currentDate = NSDate()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.tableView.delegate = self
        self.tableView.dataSource = self

        tableView.registerNib(UINib(nibName: "GameTableViewCell", bundle: nil), forCellReuseIdentifier: "gameCell")

    }

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

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

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let view = UIView(frame: CGRectMake(0, 0, 350, 60))

        let label = UILabel(frame: CGRectMake(0, 13, 350, 33))

        view.addSubview(label)

        label.text = "Today"

        return view
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60.0
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return dataManager.games.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("gameCell", forIndexPath: indexPath) as! GameTableViewCell

//        var arrayOfLeagueAndGame = dataManager.games[indexPath.section]
//        var arrayOfGame = arrayOfLeagueAndGame?.popFirst()
//
//        cell.setupCell(arrayOfGame(indexPath.row))

        return cell
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50.0
    }

}
</code>```

So I'd like to see this :

```<code>TODAY
   Ligue 1
        Monaco - PSG
TUESDAY 06 JUNE
    Premier League
        Man U. - Liverpool
WEDNESDAY 07 JUNE
    Europa League
        Celta Vigo - Man U.
        ASSE - Man U.
</code>```

I don't know where to start, and how to deal with such nested data.

Thanks for your help !

答:
UITableView does not intrinsically support multiple tree levels as you describe, just entries and headers.

I would flatten the data model for display from three levels to two (Date + League on top). Each section header will display both the day and the league.

You could also just display the day in the header, then sort the games by league on that day, and distinguish the grouped leagues in the entry cells with icons indentations or cell background colors.

Hope this helps.

Body:
I am currenlty working on an app, and I have to display soccer fixtures in a TableView.

The table view should look like this (see picture above)
As a tree view it should look like :

Date
    League
        Fixture1
        Fixture2
    League2
        Fixture1
        Fixture2
Date
    League
        Fixture1
        Fixture2
    League2
        Fixture1
        Fixture2

So I created a DataManager in order to manage my dummy data :

import Foundation
import RxSwift
import RxCocoa

class DataManager {
    var games = [Int:[League:[Game]]]()

    static let shared = DataManager()

    private init() {
        self.buildDummyData()
    }

    func buildDummyData() {

        let today = NSDate()
        let tomorrow = NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: 1,
                toDate: today,
                options: []
        )
        let day_after = NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: 2,
                toDate: today,
                options: []
        )

        let premierLeague = League(title: "Premier League", iName: "england")
        let ligueUn = League(title: "Ligue 1", iName: "France Contest")
        let europaLeague = League(title: "Europa League", iName: "Europa Contest")

        let game1 = Game(ftName: "Monaco", ftLogo: "sampleLogo", stName: "Paris SG", stLogo: "sampleLogo", time: "16:30", date: today, league: ligueUn)

        let game2 = Game(ftName: "Man U.", ftLogo: "sampleLogo", stName: "Liverpool", stLogo: "sampleLogo", time: "20:30", date: tomorrow!, league: premierLeague)

        let game3 = Game(ftName: "Celta Vigo", ftLogo: "sampleLogo", stName: "Man U.", stLogo: "sampleLogo", time: "19:45", date: day_after!, league: europaLeague)

        let game4 = Game(ftName: "ASSE", ftLogo: "sampleLogo", stName: "Man U.", stLogo: "sampleLogo", time: "19:45", date: day_after!, league: europaLeague)

        games = [0: [ligueUn: [game1]], 1: [premierLeague: [game2]], 2: [europaLeague: [game3, game4]]]

    }

}

And my ViewController.swift :

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    let dataManager = DataManager.shared

    let currentDate = NSDate()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.tableView.delegate = self
        self.tableView.dataSource = self

        tableView.registerNib(UINib(nibName: "GameTableViewCell", bundle: nil), forCellReuseIdentifier: "gameCell")

    }

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

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

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let view = UIView(frame: CGRectMake(0, 0, 350, 60))

        let label = UILabel(frame: CGRectMake(0, 13, 350, 33))

        view.addSubview(label)

        label.text = "Today"

        return view
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60.0
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return dataManager.games.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("gameCell", forIndexPath: indexPath) as! GameTableViewCell

//        var arrayOfLeagueAndGame = dataManager.games[indexPath.section]
//        var arrayOfGame = arrayOfLeagueAndGame?.popFirst()
//
//        cell.setupCell(arrayOfGame(indexPath.row))

        return cell
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50.0
    }

}

So I'd like to see this :

TODAY
   Ligue 1
        Monaco - PSG
TUESDAY 06 JUNE
    Premier League
        Man U. - Liverpool
WEDNESDAY 07 JUNE
    Europa League
        Celta Vigo - Man U.
        ASSE - Man U.

I don't know where to start, and how to deal with such nested data.

Thanks for your help !


问:
How to change/update Dynamics crm entity record data and state from Active to Inactive with Javascript
I have issues with changing the state, status and additional data for  Entity Record (Dynamics CRM 2015).
. I am trying to update the data in just created Entity record.
But all the time I get Bad Request. Please help me!?

this is my code.

Entity name: "Send Email Campaign"

Entity Schema Name: "concep_emailcampaign"

Record test name: 19/05/17-2

function CreateInactiveEmailCampaign(data) {

    var emailcampaignId, EmailCampaignName;
    var context = Xrm.Page.context;
    var serverUrl = Xrm.Page.context.getClientUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var CRMObject = new Object();
    /////////////////////////////////////////////////////////////
    // Specify the ODATA entity collection
    var ODATA_EntityCollection = "/concep_emailcampaignSet";
    /////////////////////////////////////////////////////////////

    CRMObject.concep_name               = data.Name;
    EmailCampaignName                   = data.Name;
    CRMObject.concep_Subject            = data.Subject;
    CRMObject.concep_SentDateTime   = data.sentdatetime;
    CRMObject.concep_Recipients   = data.recipientsCount;
    CRMObject.concep_CampaignID   = data.CampaignID;
    CRMObject.concep_CampaignCode   = data.CampaignCode;

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(CRMObject);
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //alert("success");
            debugger;
            var NewCRMRecordCreated = data["d"];
            ChangeRecordStatus(NewCRMRecordCreated, 1, 2, serverUrl);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("failure");
        }
    });
}
function ChangeRecordStatus(data, stateCode, statusCode, serverUrl) {
 // I need to update the record with
    //CRMObject.statecode    = {}
    //CRMObject.statecode.Value   = 1;    //Inactive
    //CRMObject.statuscode    = {Value:2}
    //CRMObject.statuscode.Value  = 2;    //Inactive
    //CRMObject.concep_Campaign   = {}
    //CRMObject.concep_Campaign.Id   = data.Campaign;
    //CRMObject.concep_SendAccount  = {}
    //CRMObject.concep_SendAccount.Id  = data.SendAccount;
    //CRMObject.concep_SendAccount.LogicalName  = data.SendAccount;
    //CRMObject.concep_SendAccount.Name  = data.SendAccount;
    //CRMObject.concep_ResponsesTotal = ''
    //CRMObject.concep_ResponsesToRecipientsRate = ''
    //CRMObject.concep_concep_emailcampaign_list = ''
    //CRMObject.concep_emailcampaign_campaign. = ''
    //CRMObject.concep_emailcampaign_sendaccount. = ''
    //CRMObject.concep_surveyresponse_emailcampaign. = ''
    //CRMObject.user_concep_emailcampaign. = ''
 var serverUrl = serverUrl;
 var RECORD_ID = data.concep_emailcampaignId
 var EntityLogicalName = data.concep_name;
   var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    request += "";
    request += "";
    request += "<c:key>EntityMoniker</c:key>";
    request += "<c:value i:type=\"a:EntityReference\">";
    request += "" + RECORD_ID + "";
    //request += "" + EntityLogicalName + "";
    request += "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "<c:key>State</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "" + stateCode + "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "<c:key>Status</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "" + statusCode + "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "";
    request += "SetState";
    request += "</request>";
    request += "</Execute>";
    request += "</s:Body>";
    request += "</s:Envelope>";
    //send set state request
    $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",
        url:  serverUrl + "/XRMServices/2011/Organization.svc/web",
        data: request,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Success");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest);
             alert(errorThrown);
        }
    });
}```

This may help: Active/Deactive Record using JS in CRM

答:
May I know why you are using this approach - any specific reason? Bcoz, this can be achieved easily in UI workflow with no code.

Another approach you are doing now using JS. But from where you are calling this method - CreateInactiveEmailCampaign? On form load? or ribbon click?

You have to check the form type for update mode (refer: https://msdynamicscrmblog.wordpress.com/2013/12/11/get-form-types-and-modes-in-dynamics-crm-2013/). Otherwise create mode wont have RecordId.

Debug & see which line you are getting error.

Body:
I have issues with changing the state, status and additional data for  Entity Record (Dynamics CRM 2015).
. I am trying to update the data in just created Entity record.
But all the time I get Bad Request. Please help me!?

this is my code.

Entity name: "Send Email Campaign"

Entity Schema Name: "concep_emailcampaign"

Record test name: 19/05/17-2

function CreateInactiveEmailCampaign(data) {

    var emailcampaignId, EmailCampaignName;
    var context = Xrm.Page.context;
    var serverUrl = Xrm.Page.context.getClientUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var CRMObject = new Object();
    /////////////////////////////////////////////////////////////
    // Specify the ODATA entity collection
    var ODATA_EntityCollection = "/concep_emailcampaignSet";
    /////////////////////////////////////////////////////////////

    CRMObject.concep_name               = data.Name;
    EmailCampaignName                   = data.Name;
    CRMObject.concep_Subject            = data.Subject;
    CRMObject.concep_SentDateTime   = data.sentdatetime;
    CRMObject.concep_Recipients   = data.recipientsCount;
    CRMObject.concep_CampaignID   = data.CampaignID;
    CRMObject.concep_CampaignCode   = data.CampaignCode;

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(CRMObject);
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //alert("success");
            debugger;
            var NewCRMRecordCreated = data["d"];
            ChangeRecordStatus(NewCRMRecordCreated, 1, 2, serverUrl);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("failure");
        }
    });
}
function ChangeRecordStatus(data, stateCode, statusCode, serverUrl) {
 // I need to update the record with
    //CRMObject.statecode    = {}
    //CRMObject.statecode.Value   = 1;    //Inactive
    //CRMObject.statuscode    = {Value:2}
    //CRMObject.statuscode.Value  = 2;    //Inactive
    //CRMObject.concep_Campaign   = {}
    //CRMObject.concep_Campaign.Id   = data.Campaign;
    //CRMObject.concep_SendAccount  = {}
    //CRMObject.concep_SendAccount.Id  = data.SendAccount;
    //CRMObject.concep_SendAccount.LogicalName  = data.SendAccount;
    //CRMObject.concep_SendAccount.Name  = data.SendAccount;
    //CRMObject.concep_ResponsesTotal = ''
    //CRMObject.concep_ResponsesToRecipientsRate = ''
    //CRMObject.concep_concep_emailcampaign_list = ''
    //CRMObject.concep_emailcampaign_campaign. = ''
    //CRMObject.concep_emailcampaign_sendaccount. = ''
    //CRMObject.concep_surveyresponse_emailcampaign. = ''
    //CRMObject.user_concep_emailcampaign. = ''
 var serverUrl = serverUrl;
 var RECORD_ID = data.concep_emailcampaignId
 var EntityLogicalName = data.concep_name;
   var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    request += "";
    request += "";
    request += "<c:key>EntityMoniker</c:key>";
    request += "<c:value i:type=\"a:EntityReference\">";
    request += "" + RECORD_ID + "";
    //request += "" + EntityLogicalName + "";
    request += "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "<c:key>State</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "" + stateCode + "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "<c:key>Status</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "" + statusCode + "";
    request += "</c:value>";
    request += "";
    request += "";
    request += "";
    request += "SetState";
    request += "</request>";
    request += "</Execute>";
    request += "</s:Body>";
    request += "</s:Envelope>";
    //send set state request
    $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",
        url:  serverUrl + "/XRMServices/2011/Organization.svc/web",
        data: request,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Success");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest);
             alert(errorThrown);
        }
    });
}

This may help: Active/Deactive Record using JS in CRM