问:
Getting ModelValidation Exception when using MultipartFormData
```<code>The service Code looks like below. I have defined @PATH in main class.

@POST
    @Timed
    @Produces(MediaType.MULTIPART_FORM_DATA)
    @ResponseStatusOverride(httpStatus = 202)
    public MetaLinks CreateEdmUpload(@ApiParam(hidden = true) @Auth User user,
                                     @FormDataParam("importInput") FormDataBodyPart jsonPart,
                                     @FormDataParam("file") InputStream mdfStream,
                                     @FormDataParam("file") FormDataContentDisposition cdh)

            throws ApiException {

        jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
        ImportInput importInput = jsonPart.getValueAs(ImportInput.class);
</code>```

I have the following dependency in POM

```<code><dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.23.1</version>
        </dependency>
</code>```

AND I am registering the class as well in my client request but when i start the JAVA application to try to POST i get the following error

alidation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public com.rm

What could be wrong.. Can someone please suggest

答: Yes registering multipartFeature solved the problem.</p>

Body:
The service Code looks like below. I have defined @PATH in main class.

@POST
    @Timed
    @Produces(MediaType.MULTIPART_FORM_DATA)
    @ResponseStatusOverride(httpStatus = 202)
    public MetaLinks CreateEdmUpload(@ApiParam(hidden = true) @Auth User user,
                                     @FormDataParam("importInput") FormDataBodyPart jsonPart,
                                     @FormDataParam("file") InputStream mdfStream,
                                     @FormDataParam("file") FormDataContentDisposition cdh)

            throws ApiException {

        jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
        ImportInput importInput = jsonPart.getValueAs(ImportInput.class);

I have the following dependency in POM

<dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.23.1</version>
        </dependency>

AND I am registering the class as well in my client request but when i start the JAVA application to try to POST i get the following error

alidation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public com.rm

What could be wrong.. Can someone please suggest


来源: stackexchange

问:
Slow drawing of images in pictureBoxes
The form size is stretched to the screen resolution. The following elements are on the form:

```<code>private System.Windows.Forms.PictureBox pictureBox6;
private System.Windows.Forms.PictureBox pictureBox7;
private System.Windows.Forms.PictureBox pictureBox8;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox9;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel1;
</code>```

When you open a form, it immediately loads the images to the panel from the folder. Example:

```<code>pictureBox2.Load("bgr/1.png");
</code>```

Images are loaded and displayed, but they are drawn for a long time, that is, you can see the rendering of the image itself in parts.

Image 1

Image 2

Question: how can I solve the problem of slow drawing images or make it invisible to the user?

答:
There is also a property on the form to enable double buffering that can sometimes fix display issues (particularly if you notice flickering while drawing or going in and out of a form.  This doesn't always extend down to the controls on the form (like the Panel).  If you want to use the panel, you can still make double buffering work but you'll need to extend the panel and then use the extended panel (I'll share the code, it's straightforward).  I suspect if I had to guess that if by moving the pictures out of the panel yours started working faster that this will also work.

Form:

```<code>this.DoubleBuffered = true;
</code>```

Extended Panel:

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

namespace MyApp
{
    public class PanelEx : System.Windows.Forms.Panel
    {
        public PanelEx()
        {
            this.SetStyle(
                System.Windows.Forms.ControlStyles.UserPaint |
                System.Windows.Forms.ControlStyles.AllPaintingInWmPaint |
                System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer,
                true);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Slow drawing of images in pictureBoxes

Body:
The form size is stretched to the screen resolution. The following elements are on the form:

private System.Windows.Forms.PictureBox pictureBox6;
private System.Windows.Forms.PictureBox pictureBox7;
private System.Windows.Forms.PictureBox pictureBox8;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox9;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel1;

When you open a form, it immediately loads the images to the panel from the folder. Example:

pictureBox2.Load("bgr/1.png");

Images are loaded and displayed, but they are drawn for a long time, that is, you can see the rendering of the image itself in parts.

Image 1

Image 2

Question: how can I solve the problem of slow drawing images or make it invisible to the user?

Body:
There is also a property on the form to enable double buffering that can sometimes fix display issues (particularly if you notice flickering while drawing or going in and out of a form.  This doesn't always extend down to the controls on the form (like the Panel).  If you want to use the panel, you can still make double buffering work but you'll need to extend the panel and then use the extended panel (I'll share the code, it's straightforward).  I suspect if I had to guess that if by moving the pictures out of the panel yours started working faster that this will also work.

Form:

this.DoubleBuffered = true;

Extended Panel:

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

namespace MyApp
{
    public class PanelEx : System.Windows.Forms.Panel
    {
        public PanelEx()
        {
            this.SetStyle(
                System.Windows.Forms.ControlStyles.UserPaint |
                System.Windows.Forms.ControlStyles.AllPaintingInWmPaint |
                System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer,
                true);
        }
    }
}


问:
Weird error: [ArgumentOutOfRangeException: 'count' must be non-negative
I have a site which runs in ASP.NET 3.5, NHibernate 2.2 and Sprint .NET for Dependency Injection. On our test server a rather strange error occurrs, and also almost everytime there are multiple users online. After the problem has occurred, this error is displayed for every user and every request they make - until you do an IISRESET. Then it is all ok again.

Here's the exception:

```<code>'count' must be non-negative.
Parameter name: count
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count

Source Error:
[No relevant source lines]

Source File: c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET      Files\root\4bf9aa39\6dcf5fc6\App_Web_z9ifuy6t.6.cs    Line: 0

Stack Trace:
[ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count]
System.String.CtorCharCount(Char c, Int32 count) +10082288
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +3612
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) +75
Spring.Objects.Factory.Support.DefaultListableObjectFactory.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +365
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +136
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type) +66

[ActivationException: Activation error occured while trying to get instance of type InfoTextService, key ""]
   Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in      c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:57
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance() in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:90
OurProjectsNamespace.Infrastructure.ObjectLocator.LocateService() +86
</code>```

答:
In my case, this error occurred after some time during performance testing. It starts fine and after some time this error pops up.

Turns out it was caused by a totally unrelated [ThreadLocal] variable I used in my code. I replaced it with a method parameter and now it works fine.

ContentLicense: CC BY-SA 2.5

Body:
I have a site which runs in ASP.NET 3.5, NHibernate 2.2 and Sprint .NET for Dependency Injection. On our test server a rather strange error occurrs, and also almost everytime there are multiple users online. After the problem has occurred, this error is displayed for every user and every request they make - until you do an IISRESET. Then it is all ok again.

Here's the exception:

'count' must be non-negative.
Parameter name: count
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count

Source Error:
[No relevant source lines]

Source File: c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET      Files\root\4bf9aa39\6dcf5fc6\App_Web_z9ifuy6t.6.cs    Line: 0

Stack Trace:
[ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count]
System.String.CtorCharCount(Char c, Int32 count) +10082288
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +3612
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) +75
Spring.Objects.Factory.Support.DefaultListableObjectFactory.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +365
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +136
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type) +66

[ActivationException: Activation error occured while trying to get instance of type InfoTextService, key ""]
   Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in      c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:57
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance() in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:90
OurProjectsNamespace.Infrastructure.ObjectLocator.LocateService() +86


问:
Can't convert from Microsoft.Extensions.Configuration.IConfigurationBuilder' to 'Microsoft.Extensions.Configuration.IConfiguration'
When working with ASP.NET Core, in Program.cs when we add Configuration I faced an unusual issue (for those who are expert in ASP.NET CORE may find this basic). When I was trying to add .UseConfiguration(config) it gave me a error saying -

Can't convert from Microsoft.Extensions.Configuration.IConfigurationBuilder' to 'Microsoft.Extensions.Configuration.IConfiguration'

The following is my code:

```<code>var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("hosting.json", optional: true);;

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
</code>```

答:
Well, I tried different approaches, until I figured out the simple solution was instead of just writing config in the parameters of .UseConfiguration, I had to do .UseConfiguration(config.Build())

```<code>var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("hosting.json", optional: true);;

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config.Build())
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When working with ASP.NET Core, in Program.cs when we add Configuration I faced an unusual issue (for those who are expert in ASP.NET CORE may find this basic). When I was trying to add .UseConfiguration(config) it gave me a error saying -

Can't convert from Microsoft.Extensions.Configuration.IConfigurationBuilder' to 'Microsoft.Extensions.Configuration.IConfiguration'

The following is my code:

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("hosting.json", optional: true);;

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

Body:
Well, I tried different approaches, until I figured out the simple solution was instead of just writing config in the parameters of .UseConfiguration, I had to do .UseConfiguration(config.Build())

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("hosting.json", optional: true);;

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config.Build())
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();


问:
How to predict input image with cnn trained model
I have trained cnn model for MNIST digit recognition...now I want to provide my own input to my model and expecting for the correct output with label name...
I dont know how to provide input to my trained model could anyone please help me....here is my full code......</p>

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

import numpy as np
import tensorflow as tf

from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)
sess = tf.Session()

def cnn_model_fn(features, labels, mode):

  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  conv1 = tf.layers.conv2d(inputs= input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)

  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5],padding="same", activation=tf.nn.relu)

  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)

  dropout = tf.layers.dropout(inputs=dense, rate=0.4, training= mode == learn.ModeKeys.TRAIN)

  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn= cnn_model_fn, model_dir="/home/kumar/Downloads/")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

# Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)

  saver = tf.train.Saver()
  saver.restore(sess, "/home/kumar/Downloads/model_simple.ckpt")
  print("model restored.")

if __name__ == "__main__":
  tf.app.run()
</code>```

答:
Edit

Use predict to feed in your data and get the predicted label.

```<code>mnist_classifier.fit(your_data)    # your_data should have shape = (number_of_sample, number_of_features)
</code>```

Refer to the document.

Body:
I have trained cnn model for MNIST digit recognition...now I want to provide my own input to my model and expecting for the correct output with label name...
I dont know how to provide input to my trained model could anyone please help me....here is my full code......

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

import numpy as np
import tensorflow as tf

from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)
sess = tf.Session()

def cnn_model_fn(features, labels, mode):

  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  conv1 = tf.layers.conv2d(inputs= input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)

  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5],padding="same", activation=tf.nn.relu)

  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)

  dropout = tf.layers.dropout(inputs=dense, rate=0.4, training= mode == learn.ModeKeys.TRAIN)

  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn= cnn_model_fn, model_dir="/home/kumar/Downloads/")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

# Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)

  saver = tf.train.Saver()
  saver.restore(sess, "/home/kumar/Downloads/model_simple.ckpt")
  print("model restored.")

if __name__ == "__main__":
  tf.app.run()

Body:
Edit

Use predict to feed in your data and get the predicted label.

mnist_classifier.fit(your_data)    # your_data should have shape = (number_of_sample, number_of_features)

Refer to the document.


问:
Can I use MarshalJSON to add arbitrary fields to a json encoding in golang?
Suppose I've written the following code snippet. Full code on the playground here for those inclined.

```<code>type Book struct {
  Title        string
  Author       string
}

func main() {
  ms := Book{"Catch-22", "Joseph Heller"}
  out, err := json.MarshalIndent(ms, "", "  ")
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(string(out))
}
</code>```

This code outputs the following, exactly as I'd expect:

```<code>{
  "Title": "Catch-22",
  "Author": "Joseph Heller"
}
</code>```

Suppose for a moment I wanted to add a field to the JSON output without including it in the Book struct. Perhaps a genre:

```<code>{
  "Title": "Catch-22",
  "Author": "Joseph Heller",
  "Genre": "Satire"
}
</code>```

Can I use MarshalJSON() to add an arbitrary field to the JSON payload on Marshal()? Something like:

```<code>func (b *Book) MarshalJSON() ([]byte, error) {
    // some code
}
</code>```

Other answers make me think this should be possible, but I'm struggling to figure out the implementation.

答:
Marshalling a map is another way around the problem.

tmap := make(map[string]interface{})

tmap["struct"] = struct {
    StructValue string `json:"struct_value"`
}{
    "Value 02",
}

tmap["string"] = "Value 01"

out, err := json.MarshalIndent(tmap, "", "  ")
if err != nil {
    log.Fatalln(err)
}
fmt.Println(string(out))
```

<p>This will output:</p>

<pre class="lang-json prettyprint-override"><code>{
  "string": "Value 01",
  "struct": {
    "struct_value": "Value 02"
  }
}
</code>```

Where you have many arbitrary key names this could be a good solution.

Playground: https://play.golang.org/p/Umy9rtx2Ms

Body:
Suppose I've written the following code snippet. Full code on the playground here for those inclined.

type Book struct {
  Title        string
  Author       string
}

func main() {
  ms := Book{"Catch-22", "Joseph Heller"}
  out, err := json.MarshalIndent(ms, "", "  ")
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(string(out))
}

This code outputs the following, exactly as I'd expect:

{
  "Title": "Catch-22",
  "Author": "Joseph Heller"
}

Suppose for a moment I wanted to add a field to the JSON output without including it in the Book struct. Perhaps a genre:

{
  "Title": "Catch-22",
  "Author": "Joseph Heller",
  "Genre": "Satire"
}

Can I use MarshalJSON() to add an arbitrary field to the JSON payload on Marshal()? Something like:

func (b *Book) MarshalJSON() ([]byte, error) {
    // some code
}

Other answers make me think this should be possible, but I'm struggling to figure out the implementation.

Body:
Marshalling a map is another way around the problem.

tmap := make(map[string]interface{})

tmap["struct"] = struct {
    StructValue string `json:"struct_value"`
}{
    "Value 02",
}

tmap["string"] = "Value 01"

out, err := json.MarshalIndent(tmap, "", "  ")
if err != nil {
    log.Fatalln(err)
}
fmt.Println(string(out))

This will output:

{
  "string": "Value 01",
  "struct": {
    "struct_value": "Value 02"
  }
}

Where you have many arbitrary key names this could be a good solution.

Playground: https://play.golang.org/p/Umy9rtx2Ms


问:
Run Time error 6 Overrun in vba for excel
I'm running the following program, and get an overflow error at the first iteration once the program gets to a. From my understanding this shouldn't happen because I'm using Doubles which have a ridiculous amount of capacity, and a Long, but because it's only going up to 100 currently it shouldn't matter, and the code fails long before then. Here is my original inputs:

```<code>h0 = 1000, v0 = 0, a0 = g = -9.80665, dt = .01, m = 752.2528, b = .287875
</code>```

and here's the code:

```<code>Sub drag()
    Dim h0 As Double
    Dim v0 As Double
    Dim a0 As Double
    Dim dt As Double
    Dim m As Double
    Dim b As Double
    Dim g As Double
    Dim i As Long
    Dim h As Double
    Dim v As Double
    Dim a As Double

    h0 = Worksheets("Drag").Cells(2, 8).Value
    v0 = Worksheets("Drag").Cells(2, 9).Value
    a0 = Worksheets("Drag").Cells(2, 10).Value
    g = Worksheets("Drag").Cells(2, 10).Value
    dt = Worksheets("Drag").Cells(2, 7).Value
    m = Worksheets("Drag").Cells(2, 4).Value
    b = Worksheets("Drag").Cells(2, 5).Value
    Debug.Print h0 & v0 & a0 & dt & m & b

    For i = 1 To 100
        v = v0 + a0 * dt
        h = 0.5 * a0 * (dt ^ 2) + v0 * dt + h0
        a = m * g - b * (v ^ 2)   'Line where overflow occurs
        v0 = v
        h0 = h
        a0 = a
        Cells(i + 2, 8) = h0
        Cells(i + 2, 9) = v0
        Cells(i + 2, 10) = a0
        Next i
    Debug.Print h0 & v0 & a0 & dt & m & b
End Sub
</code>```

Hope this is an easy fix.

答:
Your overflow happens when i=14 (14th pass through the loop) and when v = -1.689 x 10^209. I don't know what you are trying to do, but v is blowing up. It would help if you describe what you are trying to do. – John Coleman 17 mins ago

@John Coleman I see the problem now, I'm doing the drag equation and I forgot to divide the a term by m, thanks. – Anthrochange 9 mins ago

You have already identified what needs to be done.

Now for the explanation on why the overflow on m * g - b * (v ^ 2). I added a watch as shown below

Consider the before and after screenshot

Before v = v0 + a0 * dt is calculated

After v = v0 + a0 * dt is calculated

What you see here is a very peculiar behaviour. A Type Double changing to an Integer

This is not normal and has been experienced before. Unfortunately this problem exists in Excel for a long time and unfortunately is also present in Excel 2016. It occurs only when you are using very large numbers. These kind of bugs are very rare, but yes, they do exist.

One can have a similar kind of experience when using MOD as mentioned in the below link

The MOD Function

Body:
I'm running the following program, and get an overflow error at the first iteration once the program gets to a. From my understanding this shouldn't happen because I'm using Doubles which have a ridiculous amount of capacity, and a Long, but because it's only going up to 100 currently it shouldn't matter, and the code fails long before then. Here is my original inputs:

h0 = 1000, v0 = 0, a0 = g = -9.80665, dt = .01, m = 752.2528, b = .287875

and here's the code:

Sub drag()
    Dim h0 As Double
    Dim v0 As Double
    Dim a0 As Double
    Dim dt As Double
    Dim m As Double
    Dim b As Double
    Dim g As Double
    Dim i As Long
    Dim h As Double
    Dim v As Double
    Dim a As Double

    h0 = Worksheets("Drag").Cells(2, 8).Value
    v0 = Worksheets("Drag").Cells(2, 9).Value
    a0 = Worksheets("Drag").Cells(2, 10).Value
    g = Worksheets("Drag").Cells(2, 10).Value
    dt = Worksheets("Drag").Cells(2, 7).Value
    m = Worksheets("Drag").Cells(2, 4).Value
    b = Worksheets("Drag").Cells(2, 5).Value
    Debug.Print h0 & v0 & a0 & dt & m & b

    For i = 1 To 100
        v = v0 + a0 * dt
        h = 0.5 * a0 * (dt ^ 2) + v0 * dt + h0
        a = m * g - b * (v ^ 2)   'Line where overflow occurs
        v0 = v
        h0 = h
        a0 = a
        Cells(i + 2, 8) = h0
        Cells(i + 2, 9) = v0
        Cells(i + 2, 10) = a0
        Next i
    Debug.Print h0 & v0 & a0 & dt & m & b
End Sub

Hope this is an easy fix.


问:
Cassandra Primary Key with no Clustering Key
I have a table that contains words with their frequencies in Cassandra table(word, frequenc0y, frequency1).

Can I make the primary key consisting of only word as Partition key? if not, can I use word also as Clustering key?

答:
You have no constraints, except that you cannot reuse your columns, so you can put only a single column in your PRIMARY KEY definition, that will specifically be your PARTITION KEY.

BTW, if that's all you need, and depending on your UPDATE capabilities on the frequency0 and frequency1 columns, that could be a job for counter columns. Have a look at the official documentation about counters:

Creating a counter table

Using a counter

HTH.


问:
How would I tell a browser to render a string, not display it
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

```<code>@Html.MyMenu()
</code>```

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

```<code><div id="menucontainer">

                <a href="/Anuncio/Electronics">Electronics</a><a href="/Anuncio/Clothes">Clothes</a><a href="/Anuncio/Domestic">Domestic</a><a href="/Anuncio/Garden">Garden</a>

            </div>
</code>```

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

```<code><%: this is rendered, right? %>
</code>```

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.

答:
In RC2 a new method called @HTml.Raw should to this.

Or you can change MyMenu to return HtmlString or MvcString rather than just string.

OwnerDisplayName: delete

Body:
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

@Html.MyMenu()

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

                ElectronicsClothesDomesticGarden

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

<%: this is rendered, right? %>

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.


问:
Javascript, complete calculation into number
I'm trying to convert a calculation String into a Number object in JavaScript, however I can't find a function that do the wanted job.

The parseInt(String) function only parse the first number of calculation but doesn't apply the mathematical functions on it.

I minimal version of what I'm meaning would be something like this: https://jsfiddle.net/qd7u6h60/3/

I'll be glad if someone has an anwser

答:
You need to use eval() instead or parseInt.
Updated fiddle: https://jsfiddle.net/qd7u6h60/5/</p>

```<code>$('button[name=calculate]').click(function() {
   var calculation = $('input[name=calculation]').val();
   var result = eval(calculation); /* Only parse the first number of the  complete calculation */
   $('input[name=result]').val(result);
});
</code>```

Body:
You need to use eval() instead or parseInt.
Updated fiddle: https://jsfiddle.net/qd7u6h60/5/

$('button[name=calculate]').click(function() {
   var calculation = $('input[name=calculation]').val();
   var result = eval(calculation); /* Only parse the first number of the  complete calculation */
   $('input[name=result]').val(result);
});


问:
Dotnet Core 1.1 Azure Deployment: No executable found matching command "dotnet-publish-iis"
I'm getting an issue with deploying via git to Azure. My app called Blogg keeps getting hung up when the PostCompile command runs after the app gets published to the server. That command is:

<Exec Command="dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" />

I was under the impression that the package reference for this command came from Microsoft.AspNetCore.Server.IISIntegration but even after adding versions 1.1.0-preview4-final and 1.1.2 (the latest), I'm still having troubles.

In case it's helpful, below are what's in my .csproj file:

```<code>`<Project ToolsVersion="15.0" Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.0-preview4-final" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.sqlserver.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0-msbuild2-final" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild2-final" />
  </ItemGroup>
  <ItemGroup>
    <None Include="wwwroot/*" CopyToPublishDirectory="Always" />
    <None Include="Views/*" CopyToPublishDirectory="Always" />
    <None Include="web.config" CopyToPublishDirectory="Always" />
  </ItemGroup>
  <Target Name="MyPostCompileTarget" AfterTargets="Publish">
    <Exec Command="dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" />
  </Target>
</Project>`
</code>```

And the error I'm getting from the Azure log:

```<code>`Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
D:\Program Files (x86)\dotnet\sdk\1.0.0-rc4-004771\NuGet.targets(97,5): warning : Dependency specified was Microsoft.AspNetCore.Server.IISIntegration (>= 1.1.0-preview4-final) but ended up with Microsoft.AspNetCore.Server.IISIntegration 1.1.0. [D:\home\site\repository\Blogg.csproj]
  Installing Microsoft.AspNetCore.Http.Features 1.1.0.
  Installing Microsoft.AspNetCore.Hosting.Server.Abstractions 1.1.0.
  Installing Microsoft.Extensions.Configuration.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.Http.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.WebUtilities 1.1.0.
  Installing Microsoft.Extensions.ObjectPool 1.1.0.
  Installing Microsoft.Net.Http.Headers 1.1.0.
  Installing Microsoft.AspNetCore.Http.Extensions 1.1.0.
  Installing Microsoft.AspNetCore.Hosting.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.Http 1.1.0.
  Installing Microsoft.Extensions.Logging.Abstractions 1.1.0.
  Installing Microsoft.Extensions.Options 1.1.0.
  Installing Microsoft.AspNetCore.HttpOverrides 1.1.0.
  Installing Microsoft.AspNetCore.Server.IISIntegration 1.1.0.
  Writing lock file to disk. Path: D:\home\site\repository\obj\project.assets.json
  Restore completed in 18.69 sec for D:\home\site\repository\Blogg.csproj.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
  Restore completed in 14.38 sec for D:\home\site\repository\Blogg.csproj.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
  Restore completed in 17.49 sec for D:\home\site\repository\Blogg.csproj.

  NuGet Config files used:
      D:\local\AppData\NuGet\NuGet.Config

  Feeds used:
      https://api.nuget.org/v3/index.json

  Installed:
      14 package(s) to D:\home\site\repository\Blogg.csproj
Microsoft (R) Build Engine version 15.1.545.13942
Copyright (C) Microsoft Corporation. All rights reserved.

  Blogg -> D:\home\site\repository\bin\Release\netcoreapp1.0\Blogg.dll
  No executable found matching command "dotnet-publish-iis"
D:\home\site\repository\Blogg.csproj(30,5): error MSB3073: The command "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\Blogg.csproj" --output "D:\local\Temp\8d4ac97ca692979" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\62.60524.2862\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"`
</code>```

答:
When using csproj files for ASP.NET Core web applications, you can safely remove this line:

```<code><Exec Command="dotnet publish-iis …" />
</code>```

For project.json based projects, this command performed actions that are now performed by default if your project uses the web sdk:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
</code>```

It looks like the migration correctly removed the tools reference to the dotnet-publish-iis tool but did not remove the corresponding invocation. You could file an issue at the dotnet migrate tool's GitHub repository with your original project.json file.

Body:
I'm getting an issue with deploying via git to Azure. My app called Blogg keeps getting hung up when the PostCompile command runs after the app gets published to the server. That command is:

<Exec Command="dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" />

I was under the impression that the package reference for this command came from Microsoft.AspNetCore.Server.IISIntegration but even after adding versions 1.1.0-preview4-final and 1.1.2 (the latest), I'm still having troubles.

In case it's helpful, below are what's in my .csproj file:

`<Project ToolsVersion="15.0" Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.0-preview4-final" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.sqlserver.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0-msbuild2-final" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild2-final" />
  </ItemGroup>
  <ItemGroup>
    <None Include="wwwroot/*" CopyToPublishDirectory="Always" />
    <None Include="Views/*" CopyToPublishDirectory="Always" />
    <None Include="web.config" CopyToPublishDirectory="Always" />
  </ItemGroup>
  <Target Name="MyPostCompileTarget" AfterTargets="Publish">
    <Exec Command="dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" />
  </Target>
</Project>`

And the error I'm getting from the Azure log:

`Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
D:\Program Files (x86)\dotnet\sdk\1.0.0-rc4-004771\NuGet.targets(97,5): warning : Dependency specified was Microsoft.AspNetCore.Server.IISIntegration (>= 1.1.0-preview4-final) but ended up with Microsoft.AspNetCore.Server.IISIntegration 1.1.0. [D:\home\site\repository\Blogg.csproj]
  Installing Microsoft.AspNetCore.Http.Features 1.1.0.
  Installing Microsoft.AspNetCore.Hosting.Server.Abstractions 1.1.0.
  Installing Microsoft.Extensions.Configuration.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.Http.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.WebUtilities 1.1.0.
  Installing Microsoft.Extensions.ObjectPool 1.1.0.
  Installing Microsoft.Net.Http.Headers 1.1.0.
  Installing Microsoft.AspNetCore.Http.Extensions 1.1.0.
  Installing Microsoft.AspNetCore.Hosting.Abstractions 1.1.0.
  Installing Microsoft.AspNetCore.Http 1.1.0.
  Installing Microsoft.Extensions.Logging.Abstractions 1.1.0.
  Installing Microsoft.Extensions.Options 1.1.0.
  Installing Microsoft.AspNetCore.HttpOverrides 1.1.0.
  Installing Microsoft.AspNetCore.Server.IISIntegration 1.1.0.
  Writing lock file to disk. Path: D:\home\site\repository\obj\project.assets.json
  Restore completed in 18.69 sec for D:\home\site\repository\Blogg.csproj.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
  Restore completed in 14.38 sec for D:\home\site\repository\Blogg.csproj.
  Restoring packages for D:\home\site\repository\Blogg.csproj...
  Restore completed in 17.49 sec for D:\home\site\repository\Blogg.csproj.

  NuGet Config files used:
      D:\local\AppData\NuGet\NuGet.Config

  Feeds used:
      https://api.nuget.org/v3/index.json

  Installed:
      14 package(s) to D:\home\site\repository\Blogg.csproj
Microsoft (R) Build Engine version 15.1.545.13942
Copyright (C) Microsoft Corporation. All rights reserved.

  Blogg -> D:\home\site\repository\bin\Release\netcoreapp1.0\Blogg.dll
  No executable found matching command "dotnet-publish-iis"
D:\home\site\repository\Blogg.csproj(30,5): error MSB3073: The command "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\Blogg.csproj" --output "D:\local\Temp\8d4ac97ca692979" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\62.60524.2862\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"`

Body:
When using csproj files for ASP.NET Core web applications, you can safely remove this line:

<Exec Command="dotnet publish-iis …" />

For project.json based projects, this command performed actions that are now performed by default if your project uses the web sdk:

<Project Sdk="Microsoft.NET.Sdk.Web">

It looks like the migration correctly removed the tools reference to the dotnet-publish-iis tool but did not remove the corresponding invocation. You could file an issue at the dotnet migrate tool's GitHub repository with your original project.json file.


问:
Debug a self signed android app? (Need it for facebook integration)
When hitting the "debug"-button in eclipse my App gets signed by a debug key form android which is stored in the file "debug.keystore".

Now I am implementing the Facebook SDK which forces me to use a signed app for the Single SignOn feature. That way I need to generate the hash of my companies keystore and store the one in our facebook developer account.

I know how to sign an app through the wizard in Eclipse (over the AndroidManifest.xml). How to debug such a signed app?

Can I change the debug key somehow and set up our companies key as debug key? Or how should I go? Right now I can get FB working only by signing and installing my app on a device. I already tried to generate a hash of the debug key with no luck...

答:
I do not recommend setting your companies key as your debug key, but you can do that by replacing the Eclipse debug keystore file, named debug.keystore. You can find its location on your OS by reading through this.

A better solution would be to generate the hash of the debug key - follow the instructions given on the official SDK for Android page, and make sure you mention the correct keystore file, and the alias "androiddebugkey". The password is always "android".


问:
Unable to display single custom post type in wordpress
i am showing the projects added customly on to my home page by simple queering them. using these lines of code

```<code>$args = array( 'post_type' => 'recent-projects', 'posts_per_page' => 10 ,'order' => 'ASC');
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo get_post_permalink( $post->ID, $leavename, $sample );
    endwhile;
</code>```

when i click on the permalink of the custom posts then it is showing me the index page. while i have archive.php too.
here is the code from functions.php.

```<code>register_post_type( 'recent-projects',
// CPT Options
    array(
        'labels' => array(
            'name' => __( 'Recent Projects' ),
            'singular_name' => __( 'Recent Project' )
        ),
        'taxonomies' => array('recordings', 'category', 'whatever'),  //add this....
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'recent-projects'),
        'supports' => array(
        'title',
        'editor',
        'excerpt',
        'trackbacks',
        'custom-fields',
        'comments',
        'revisions',
        'thumbnail',
        'author',
        'page-attributes',)

    )
);
</code>```

and this is the code in file named archive-recent-projects.php

```<code><?php get_header(); ?>
<div class="content-area">
    <div class="container main_content_wrap">
      <div class="page_wrapper">

        <section id="site-main" class="site-main content-part" >
            <div class="blog-post">
                <h1 class="classic-title"><span>Recent Projects</span></h1>
                <br>
                <br>
                <ul>
                <?php
                    $args = array( 'post_type' => 'recent-projects','order' => 'ASC');
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();?>
                       <li>
                        <small><?php the_time('F jS, Y'); ?></small><br>
                        <strong>-</strong>  <?php the_title(); ?><br> <a href="<?php the_permalink(); ?>">Read</a><br><br>
                    </li>

                <?php endwhile; // end of the loop. ?>
            </ul>
            </div>
        </section>
        </div><!--end .page_wrapper-->
    </div>
</div>
<?php get_footer(); ?>
</code>```

答:
```<code>$recent_posts = new WP_Query( array(
'post_type' => 'recent-projects',
'posts_per_page' => 10 ,
'order' => 'ASC'
));
if($recent_posts->have_posts()) :
    while($recent_posts->have_posts()) : $recent_posts->the_post();
        echo '<a href="' . get_the_permalink() . '">' . get_the_title() . '</a>';
        the_content();
    endwhile;
endif;
wp_reset_postdata();
</code>```

Body:
i am showing the projects added customly on to my home page by simple queering them. using these lines of code

$args = array( 'post_type' => 'recent-projects', 'posts_per_page' => 10 ,'order' => 'ASC');
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo get_post_permalink( $post->ID, $leavename, $sample );
    endwhile;

when i click on the permalink of the custom posts then it is showing me the index page. while i have archive.php too.
here is the code from functions.php.

register_post_type( 'recent-projects',
// CPT Options
    array(
        'labels' => array(
            'name' => __( 'Recent Projects' ),
            'singular_name' => __( 'Recent Project' )
        ),
        'taxonomies' => array('recordings', 'category', 'whatever'),  //add this....
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'recent-projects'),
        'supports' => array(
        'title',
        'editor',
        'excerpt',
        'trackbacks',
        'custom-fields',
        'comments',
        'revisions',
        'thumbnail',
        'author',
        'page-attributes',)

    )
);

and this is the code in file named archive-recent-projects.php

<?php get_header(); ?>

Recent Projects

                <?php
                    $args = array( 'post_type' => 'recent-projects','order' => 'ASC');
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();?>

                        <?php the_time('F jS, Y'); ?>

                        -  <?php the_title(); ?>
 <a href="<?php the_permalink(); ?>">Read

                <?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>


问:
How Haskell handles parallel computing on a multicore machine/cluster
I'm considering a new language to learn those days to be used in high performance computing on a cluster of computers we have, among those languages, I'm considering Haskell.

I have read some about Haskell, but still have questions about using Haskell in high performance and distributed computing, which the language is known for, but I read some debates about Haskell is not good for those type of systems due to laziness, I can summarize my questions in the following lines:

Haskell uses green threads, which is great for handling big number of concurrent connections, but what happens when one of tasks takes longer than average and blocks the rest, does the whole thread block (Node.js style), forward the next task to another processor/thread (Golang), use reductions technique (Erlang), which kicks the task out of processing context after a pre-determined number of ticks, or else?

In a distributed computing environment, what happens to lazily-evaluated functions, do they have to be forced strict?

If one function/module requires strict evaluation, but it depends on other lazy functions/modules, shall I modify the code of other functions/modules to make them strict as well, or the compiler will handle this to me and force everything in that chain to strict or lazy.

When processing a very large sequence of data, how does Haskell handle parallel processing, is it by following some kind of implicit map-reduce technique, or I have do it by myself.

Is there a clustering abstract in the language, that handles the computing power for me, that automatically forwards the next task to the free processor wherever it is, be it on the same computer or another computer in the same cluster.

How does Haskell ensure fair-share of work is evenly distributed to all the available cores on the same computer or on the available cluster.

答:
GHC uses a pool of available work (called sparks) and a work-stealing system: when a thread runs out of work, it will look for work in the pool or on the work queues of other threads that it can steal.

There is no built-in support for distributed computing as there is in (say) Erlang. The semantics are whatever your implementation defines. There are existing implementations like Cloud Haskell that you can look at for examples.

Neither. Haskell will automatically do whatever work is necessary to provide a value that is demanded and no more.

Haskell (and GHC in particular) does not do anything to automatically parallelize evaluation because there is no known universal strategy for parallelizing that is strictly better than not parallelizing. See Why is there no implicit parallelism in Haskell? for more info.

No. See (2).

For the same machine, it uses the pool of sparks and the work-stealing system described above. There is no notion of "clustering".

For an overview of parallel and concurrent programming in Haskell, see the free book of the same name by Simon Marlow, a primary author of GHC's runtime system.


问:
Record video in Simulator Xcode 9 Beta
Apple's Whats new in Xcode 9 states that we can record videos of Simulators. How to do that?</p>

答: On iOS devices you can open control center settings and enable 'recorder' then open control center and tap the circle in circle in control center, to begin recording, when you are done it saves to your photo library. Hope this helps (hope this feature stays on the release version:])</p>

Title: Record video in Simulator Xcode 9 Beta


问:
How to fetch all the data from Smartsheet using API?
I am trying to fetch all the rows that are existing in an Smartsheet using API.
I have generated the bearer authorization token and have the report details. My Python is fetching me results of the first 100 rows (source has 1200 rows). I don't use any filters within the Python. Is this due to any default (page-size value)?

I am unable to retrieve all existing data from this API.

答:
It's unclear from your question if you are reading a sheet or a report. Sample code would be very helpful.

The report API get_report(report_id, page_size=100, page=1, include=None) also allows you to specify the number of results to return. However, note that you can read a maximum of 500 rows at a time from a report. So you would need to use a loop.


答:
You can use eval() to compute the value.
The eval() function evaluates JavaScript code represented as a string.
The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression

Please find the code snippet below. I have modified your example

$('button[name=calculate]').click(function() {
var calculation = $('input[name=calculation]').val();
  var result = eval(calculation); /* Only parse the first number of the complete calculation */
  $('input[name=result]').val(result);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">

<br/>

<div class="input-group">
  <input type="text" name="calculation" class="form-control" placeholder="Calculation, eg: (5 - 2)/(7 + 4)">
</div>

<br/>

<div class="input-group">
  <span class="input-group-addon">=</span>
  <input type="number" name="result" class="form-control" placeholder="Result" readonly>
</div>

<br/><br/>

<button type="button" name="calculate" class="btn btn-info">Calculate !</button>

</div></code>```

Title: Javascript, complete calculation into number

Body:
I'm trying to convert a calculation String into a Number object in JavaScript, however I can't find a function that do the wanted job.

The parseInt(String) function only parse the first number of calculation but doesn't apply the mathematical functions on it.

I minimal version of what I'm meaning would be something like this: https://jsfiddle.net/qd7u6h60/3/

I'll be glad if someone has an anwser

Body:
You can use eval() to compute the value.
The eval() function evaluates JavaScript code represented as a string.
The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression

Please find the code snippet below. I have modified your example

$('button[name=calculate]').click(function() {
var calculation = $('input[name=calculation]').val();
  var result = eval(calculation); /* Only parse the first number of the complete calculation */
  $('input[name=result]').val(result);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">

<br/>

<div class="input-group">
  <input type="text" name="calculation" class="form-control" placeholder="Calculation, eg: (5 - 2)/(7 + 4)">
</div>

<br/>

<div class="input-group">
  <span class="input-group-addon">=</span>
  <input type="number" name="result" class="form-control" placeholder="Result" readonly>
</div>

<br/><br/>

<button type="button" name="calculate" class="btn btn-info">Calculate !</button>

</div>


问:
UIButton won't go to Aspect Fit in iPhone
I have a couple UIButtons, and in IB they're set to Aspect Fit, but for some reason they're always stretching.  Is there something else you have to set?  I tried all the different view modes and none of them work, they all stretch.</p>

答:
If you put the image in an UIImageView behind the button, you'll loose the built-in functionality of the UIButton class, such as adjustsImageWhenHighlighted and adjustsImageWhenDisabled, and of course the ability to set different images for different states (without the hazzle of doing this yourself).

If we want to have an image unstreched for all control states, one approuch is to get the image using imageWithCGImage:scale:orientation, as in the following method:

```<code>- (UIImage *) getScaledImage:(UIImage *)img insideButton:(UIButton *)btn {

    // Check which dimension (width or height) to pay respect to and
    // calculate the scale factor
    CGFloat imgRatio = img.size.width / img.size.height,
            btnRatio = btn.frame.size.width / btn.frame.size.height,
            scaleFactor = (imgRatio > btnRatio
                           ? img.size.width / btn.frame.size.width
                           : img.size.height / btn.frame.size.height;

    // Create image using scale factor
    UIImage *scaledImg = [UIImage imageWithCGImage:[img CGImage]
                                             scale:scaleFactor
                                       orientation:UIImageOrientationUp];
    return scaledImg;
}
</code>```

To implement this we would write:

```<code>UIImage *scaledImg = [self getScaledImage:myBtnImg insideButton:myBtn];
[myBtn setImage:scaledImg forState:UIControlStateNormal];
</code>```

This should prevent the image from stretching in all control states. It worked for me, but let me know if it doesn't!

NOTE: Here we are addressing a problem relating to UIButton, but the insideButton: might as well be insideView:, or whatever one would like to fit the image into.

Body:
If you put the image in an UIImageView behind the button, you'll loose the built-in functionality of the UIButton class, such as adjustsImageWhenHighlighted and adjustsImageWhenDisabled, and of course the ability to set different images for different states (without the hazzle of doing this yourself).

If we want to have an image unstreched for all control states, one approuch is to get the image using imageWithCGImage:scale:orientation, as in the following method:

- (UIImage *) getScaledImage:(UIImage *)img insideButton:(UIButton *)btn {

    // Check which dimension (width or height) to pay respect to and
    // calculate the scale factor
    CGFloat imgRatio = img.size.width / img.size.height,
            btnRatio = btn.frame.size.width / btn.frame.size.height,
            scaleFactor = (imgRatio > btnRatio
                           ? img.size.width / btn.frame.size.width
                           : img.size.height / btn.frame.size.height;

    // Create image using scale factor
    UIImage *scaledImg = [UIImage imageWithCGImage:[img CGImage]
                                             scale:scaleFactor
                                       orientation:UIImageOrientationUp];
    return scaledImg;
}

To implement this we would write:

UIImage *scaledImg = [self getScaledImage:myBtnImg insideButton:myBtn];
[myBtn setImage:scaledImg forState:UIControlStateNormal];

This should prevent the image from stretching in all control states. It worked for me, but let me know if it doesn't!

NOTE: Here we are addressing a problem relating to UIButton, but the insideButton: might as well be insideView:, or whatever one would like to fit the image into.


问:
multidimensional array difference php
I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

```<code>$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)
</code>```

Now I want the key difference of these two arrays. I have tried array_diff_key() but it doesnot work for multidimensional.

```<code>array_diff_key($array1, $array2)
</code>```

I want the output as following

```<code>//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)
</code>```

If you think my question is genuine please accept it and answer. Thank you.

EDIT

Now if the second array is

```<code>$array2 = Array( [b1] => zzzzz)
</code>```

The result should be

```<code>$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)
</code>```

答:
There are a lot of cases, where original answers will not work properly, so I wrote a better solution. One of the problems was, that if you deleted a property in array 2, the other functions didn't recognized it.

```<code>function check_diff_multi($array1, $array2){
    $result = array();

    foreach($array1 as $key => $val) {
        if(is_array($val) && isset($array2[$key])) {
            $tmp = check_diff_multi($val, $array2[$key]);
            if($tmp) {
                $result[$key] = $tmp;
            }
        }
        elseif(!isset($array2[$key])) {
            $result[$key] = null;
        }
        elseif($val !== $array2[$key]) {
            $result[$key] = $array2[$key];
        }

        if(isset($array2[$key])) {
            unset($array2[$key]);
        }
    }

    $result = array_merge($result, $array2);

    return $result;
}
</code>```

I have also added test cases to check result:

Here you can find result for my function: http://sandbox.onlinephpfunctions.com/code/3bf7b032f772f8a4d184ca4151de9c3e9e9a58bc

Here you can find result for the accepted answer: http://sandbox.onlinephpfunctions.com/code/88efa3feb5f28bf256b5a220bd881d4a4a04130f

As you can see, my fuctions delivers better results.

Title: multidimensional array difference php

Body:
I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)

Now I want the key difference of these two arrays. I have tried array_diff_key() but it doesnot work for multidimensional.

array_diff_key($array1, $array2)

I want the output as following

//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)

If you think my question is genuine please accept it and answer. Thank you.

EDIT

Now if the second array is

$array2 = Array( [b1] => zzzzz)

The result should be

$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)

Body:
There are a lot of cases, where original answers will not work properly, so I wrote a better solution. One of the problems was, that if you deleted a property in array 2, the other functions didn't recognized it.

function check_diff_multi($array1, $array2){
    $result = array();

    foreach($array1 as $key => $val) {
        if(is_array($val) && isset($array2[$key])) {
            $tmp = check_diff_multi($val, $array2[$key]);
            if($tmp) {
                $result[$key] = $tmp;
            }
        }
        elseif(!isset($array2[$key])) {
            $result[$key] = null;
        }
        elseif($val !== $array2[$key]) {
            $result[$key] = $array2[$key];
        }

        if(isset($array2[$key])) {
            unset($array2[$key]);
        }
    }

    $result = array_merge($result, $array2);

    return $result;
}

I have also added test cases to check result:

Here you can find result for my function: http://sandbox.onlinephpfunctions.com/code/3bf7b032f772f8a4d184ca4151de9c3e9e9a58bc

Here you can find result for the accepted answer: http://sandbox.onlinephpfunctions.com/code/88efa3feb5f28bf256b5a220bd881d4a4a04130f

As you can see, my fuctions delivers better results.


问:
Place HTML and CSS in my iframe using javascript
I'm building an html preview tool inside a small project and I'm trying to find the best way to place html and the css that will style that html inside an iframe.

I'm able to create the iframe and place the html contents of my div inside. So far that seems to be working correctly in this fiddle

```<code>$(function() {

    var $html = $("#html").html();
    var $frame = $('<iframe>');
        $('body').html( $frame );

    var doc = $frame[0].contentWindow.document;
    var $framehtml = $('html',doc);
        $framehtml.html($html);

});
</code>```

But how do I add css to the head of that iframe? For example, adding the class .mobile you see in the fiddle to the head of the iframe so the image is hidden when the iframe reaches a width of 500px?

EDIT: I don't want to inject a css style sheet. I'd rather create a  tag in the head and place the css you see in the fiddle.

答:
@FRAN and @APAD1 were right, this is a duplicate. I was able to use those answers to create my own with this updated fiddle</p>

```<code>    var $head = $("#myframe").contents().find("head");
    $head.append($("<style/>",
                   {type: "text/css" }));

    var $style = $("#myframe").contents().find("style");
    $style.append($css);
</code>```

Body:
I'm building an html preview tool inside a small project and I'm trying to find the best way to place html and the css that will style that html inside an iframe.

I'm able to create the iframe and place the html contents of my div inside. So far that seems to be working correctly in this fiddle

$(function() {

    var $html = $("#html").html();
    var $frame = $('');
        $('body').html( $frame );

    var doc = $frame[0].contentWindow.document;
    var $framehtml = $('html',doc);
        $framehtml.html($html);

});

But how do I add css to the head of that iframe? For example, adding the class .mobile you see in the fiddle to the head of the iframe so the image is hidden when the iframe reaches a width of 500px?

EDIT: I don't want to inject a css style sheet. I'd rather create a  tag in the head and place the css you see in the fiddle.

Body:
@FRAN and @APAD1 were right, this is a duplicate. I was able to use those answers to create my own with this updated fiddle

    var $head = $("#myframe").contents().find("head");
    $head.append($("<style/>",
                   {type: "text/css" }));

    var $style = $("#myframe").contents().find("style");
    $style.append($css);


问:
Android - Timed game with countdown which updates UI with remaining time, while user can still interact with UI
I'm designing a simple word game for Android.

The user will have to submit words associated with a topic/person, and will have around 20 seconds to do so.

The user inputs into a textbox and when they press 'enter', the inputted text will appear as a 'blob' on the screen. I want the UI to show a countdown message to inform the user how much time is remaining.  At the end of the countdown, the user will no longer be able to submit any more words and possibly taken to another screen/shown a popup that says 'Times up'.

I'm quite new to Android/Java development so not sure its multi-threading works and if I'd need to use it. I've seen Handlers/Runners suggested in other questions but I'm not sure they apply to my particular situation.

答:
Everything which is not the UI, you write:

```<code>new Thread(new Runnable{
    //your code
}).start();
</code>```

Your UI is still responsible, and your Background Tasks run in a different thresd

Body:
Everything which is not the UI, you write:

new Thread(new Runnable{
    //your code
}).start();

Your UI is still responsible, and your Background Tasks run in a different thresd


问:
I am having problems with "error ';' expected"
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

```<code>int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}
</code>```

If anyone could help me with this, I would really appreciate.
Thank you.

答:
You are declaring the method maxValue inside your adjacentElementsProduct method, to change this you will need to extract it and make it accept an array and return the int with the max value.

```<code>int maxValue (int[] products) {
    int x = products [0];
    for (int i = 1; i < products.length; i++) {
        if (products [i] > x){
            x = products [i];
        }
    }
    return x;
}
</code>```

The method does not verify the length of the input array so you will need to take this into account

finally use it as return maxValue(products);

Body:
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}

If anyone could help me with this, I would really appreciate.
Thank you.

Body:
You are declaring the method maxValue inside your adjacentElementsProduct method, to change this you will need to extract it and make it accept an array and return the int with the max value.

int maxValue (int[] products) {
    int x = products [0];
    for (int i = 1; i < products.length; i++) {
        if (products [i] > x){
            x = products [i];
        }
    }
    return x;
}

The method does not verify the length of the input array so you will need to take this into account

finally use it as return maxValue(products);


问:
Selenium: Open Firefox with default profile using java code
I'm using Selenium in java code to open a web application in Firefox.  But I faced a problem with Firefox profile because when I run the code,  Firefox window openned using new profile,  so the web application couldn't be opened since the proxy settings are different (I should add the IP address into Firefox no proxy IPs).  I tried get the default profile from my code,  but nothing changed.  I also tried to create new profile but I don't know how to add the IP to it.
I changed the code so I can open the Firefox manually and then Selenium opens the application in nee tab,  so the IP will be there. But this also failed and the code still opens new window.
I'll be very thankful if anyone can help. </p>

答:
We can create a firefox profile with proxy value and open the firefox instance with that profile. Below code might give some idea.

```<code>public static void main(String[] args)
{

      // Create proxy class object
      Proxy p=new Proxy();

      // Set HTTP Port to 7777
      p.setHttpProxy("localhost:7777");

      // Create desired Capability object
      DesiredCapabilities cap=new DesiredCapabilities();

      // Pass proxy object p
      cap.setCapability(CapabilityType.PROXY, p);
      System.setProperty("webdriver.gecko.driver", "//PATH");
      WebDriver driver=new FirefoxDriver(cap);

 }
</code>```

Hope this helps. Thanks.

Body:
We can create a firefox profile with proxy value and open the firefox instance with that profile. Below code might give some idea.

public static void main(String[] args)
{

      // Create proxy class object
      Proxy p=new Proxy();

      // Set HTTP Port to 7777
      p.setHttpProxy("localhost:7777");

      // Create desired Capability object
      DesiredCapabilities cap=new DesiredCapabilities();

      // Pass proxy object p
      cap.setCapability(CapabilityType.PROXY, p);
      System.setProperty("webdriver.gecko.driver", "//PATH");
      WebDriver driver=new FirefoxDriver(cap);

 }

Hope this helps. Thanks.


问:
Downloading pygame games without pygame?
This is a simple question. I have been making a game, and I wanted some of my friends to be able to download it online. Do they have to have pygame and python installed on there computer to download it. The reason I ask is because Im also thinking about releasing it to the general audience and if they can't download because they don't have pygame, well I probably won't get much feedback or success. Thank you.</p>

答:
I'm not sure how to deal with installing python, but I added this bit of code to the beginning of my most recent program which is designed to automatically install pygame on launch through cmd using pip.</p>

```<code>import os
try:
    import pygame
except:
    try:
        print("Attempting to install pygame...")
        os.system('py -m pip install pygame')
        import pygame
    except:
        try:
            os.system('python -m pip install pygame')
            import pygame
        except:
            print("Error, failed to install pygame libraries")
            input("Press enter to exit...")
            quit()
</code>```

Body:
I'm not sure how to deal with installing python, but I added this bit of code to the beginning of my most recent program which is designed to automatically install pygame on launch through cmd using pip.

import os
try:
    import pygame
except:
    try:
        print("Attempting to install pygame...")
        os.system('py -m pip install pygame')
        import pygame
    except:
        try:
            os.system('python -m pip install pygame')
            import pygame
        except:
            print("Error, failed to install pygame libraries")
            input("Press enter to exit...")
            quit()


问:
How to remove duplicate values from dict?
I'm trying to remove duplicate values in my dict but its not working:

```<code>samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics
</code>```

This prints:

```<code>{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
</code>```

答:
The below dict comprehension will create a new dict from the original one without any duplicate values:

```<code>samples_antibiotics = {k: list(set(v)) for k, v in samples_antibiotics_with_duplicates.items()}
</code>```

The set version of a list (or any container) does not contain any duplicates since sets do not allow any (that is why they require hashable items as do dicts).

As @CoryKramer says in the comments, the solution given here will not (generally speaking) preserve the order of the items in the values-list. If that is important to you, you would have to go with something else.

Body:
I'm trying to remove duplicate values in my dict but its not working:

samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics

This prints:

{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}

Body:
The below dict comprehension will create a new dict from the original one without any duplicate values:

samples_antibiotics = {k: list(set(v)) for k, v in samples_antibiotics_with_duplicates.items()}

The set version of a list (or any container) does not contain any duplicates since sets do not allow any (that is why they require hashable items as do dicts).

As @CoryKramer says in the comments, the solution given here will not (generally speaking) preserve the order of the items in the values-list. If that is important to you, you would have to go with something else.


问:
Q3DScatter --> How to add a point with a different color to a point cloud
I wrote a program in Qt, which visualizes a processed pointcloud (3D-points) by using Q3DScatter.
Now I want to add calculated keypoints with a different color.
Is that possible?
Does anyboy have some experiences with that?
Below you can see the part of code, where the point cloud is added to the data array.</p>

```<code>QScatterDataArray * dataArray = new QScatterDataArray;
dataArray->resize(vector_seg_x->size());
QScatterDataItem * ptrToDataArray = &dataArray->first();

for(int i = 0; i < vector_seg_x->size();i++){

    ptrToDataArray->setPosition(QVector3D(
                                    (double)(iter_seg_x[i]),
                                    (double)(iter_seg_y[i]),
                                    (double)(iter_seg_z[i])));
    ptrToDataArray++;

}

m_graph_seg->seriesList().at(0)->dataProxy()->resetArray(dataArray);
</code>```

答:
You can only set a color/gradient for a whole point list:</p>

```<code>Q3DScatter scatter;
scatter.setFlags(scatter.flags() ^ Qt::FramelessWindowHint);

scatter.addSeries(new QScatter3DSeries);
scatter.addSeries(new QScatter3DSeries);

{
    QScatterDataArray *data = new QScatterDataArray;
    *data << QVector3D(0.5f, 0.5f, 0.5f) << QVector3D(-0.3f, -0.5f, -0.4f) << QVector3D(0.0f, -0.3f, 0.2f);

    scatter.seriesList().at(0)->dataProxy()->resetArray(data);

    QLinearGradient linearGrad(QPointF(100, 100), QPointF(200, 200));
    linearGrad.setColorAt(0, Qt::blue);
    linearGrad.setColorAt(1, Qt::red);

    scatter.seriesList().at(0)->setBaseGradient(linearGrad);
    scatter.seriesList().at(0)->setColorStyle(Q3DTheme::ColorStyle::ColorStyleObjectGradient);
}

{
    QScatterDataArray *data = new QScatterDataArray;
    *data << QVector3D(0.f, 0.f, 0.f);

    scatter.seriesList().at(1)->dataProxy()->resetArray(data);
    scatter.seriesList().at(1)->setBaseColor(Qt::green);
}

scatter.show();
</code>```

Body:
I wrote a program in Qt, which visualizes a processed pointcloud (3D-points) by using Q3DScatter.
Now I want to add calculated keypoints with a different color.
Is that possible?
Does anyboy have some experiences with that?
Below you can see the part of code, where the point cloud is added to the data array.

QScatterDataArray * dataArray = new QScatterDataArray;
dataArray->resize(vector_seg_x->size());
QScatterDataItem * ptrToDataArray = &dataArray->first();

for(int i = 0; i < vector_seg_x->size();i++){

    ptrToDataArray->setPosition(QVector3D(
                                    (double)(iter_seg_x[i]),
                                    (double)(iter_seg_y[i]),
                                    (double)(iter_seg_z[i])));
    ptrToDataArray++;

}

m_graph_seg->seriesList().at(0)->dataProxy()->resetArray(dataArray);

Body:
You can only set a color/gradient for a whole point list:

Q3DScatter scatter;
scatter.setFlags(scatter.flags() ^ Qt::FramelessWindowHint);

scatter.addSeries(new QScatter3DSeries);
scatter.addSeries(new QScatter3DSeries);

{
    QScatterDataArray *data = new QScatterDataArray;
    *data << QVector3D(0.5f, 0.5f, 0.5f) << QVector3D(-0.3f, -0.5f, -0.4f) << QVector3D(0.0f, -0.3f, 0.2f);

    scatter.seriesList().at(0)->dataProxy()->resetArray(data);

    QLinearGradient linearGrad(QPointF(100, 100), QPointF(200, 200));
    linearGrad.setColorAt(0, Qt::blue);
    linearGrad.setColorAt(1, Qt::red);

    scatter.seriesList().at(0)->setBaseGradient(linearGrad);
    scatter.seriesList().at(0)->setColorStyle(Q3DTheme::ColorStyle::ColorStyleObjectGradient);
}

{
    QScatterDataArray *data = new QScatterDataArray;
    *data << QVector3D(0.f, 0.f, 0.f);

    scatter.seriesList().at(1)->dataProxy()->resetArray(data);
    scatter.seriesList().at(1)->setBaseColor(Qt::green);
}

scatter.show();


问:
Why we create new thread and use join() to make parent thread waiting?
After reading about join method I've some doubt: I think multithreading is a way to introduce parallelism in our program and believe some time we need some thread finished before another. But I don't understand why a programmer write something like this:

```<code> public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.start();

    t1.join();

    t2.start();

    t2.join();
}
</code>```

whats the advantage of using thread in this example vs below code:

```<code>public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.run();//just run the task of thread without start new thread
    t2.run();
}
</code>```

in first example main thread should pause until t1 finished and then start t2 and wait until finished and in second example it happen too.

Why we create new thread and use join() to make parent thread waiting? why can't use parent thread instead of new thread?

答:
In both ways, you are not getting benefits.

In your first example, you have two threads and join() is not useful.

But assume a scenario where

You have multiple threads ( Main thread, T1, T2, T3 and T4)

Main, T1,T2 can run in parallel but T3 should wait for completion of T4

In above case, all threads can start in parallel but you join only T3 and T4 threads.

Refer to below post for use cases of join():

Why we should use Join in threads?

If you want to explore advanced version of multi-threading, use CountDownLatch in place of join()

Body:
After reading about join method I've some doubt: I think multithreading is a way to introduce parallelism in our program and believe some time we need some thread finished before another. But I don't understand why a programmer write something like this:

 public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.start();

    t1.join();

    t2.start();

    t2.join();
}

whats the advantage of using thread in this example vs below code:

public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.run();//just run the task of thread without start new thread
    t2.run();
}

in first example main thread should pause until t1 finished and then start t2 and wait until finished and in second example it happen too.

Why we create new thread and use join() to make parent thread waiting? why can't use parent thread instead of new thread?


问:
randomly fetch "The network connection was lost." in swift using "Alamofire.request"
Trying to call the web service as follows , and experiencing random "The network connection was lost" error causing app crash on device as well as simulator.

```<code> Alamofire.request(url, method: .post, parameters: ["limit" : "3" , "offset" : self.storeArray?.count ?? 0], encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

                switch(response.result) {
                case .success(_):
</code>```

my error bellow

```<code>Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x608000a5f950 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60800029fea0 [0x1136c0df0]>{length = 16, capacity = 16, bytes = 0x10020050a63e1c720000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://lokomart.com/services/getSearchResultData, NSErrorFailingURLKey=http://lokomart.com/services/getSearchResultData, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.})
</code>```

// I have using php backend with godaddy deluxe hosting.

and also working with swift 3

答:
Today, i had the same error. And i remember the property added for apple into iOS 9 NSAppTransportSecurity. You can try disable only for test, adding this:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</code>```

You can to do this configuration better following this answer https://stackoverflow.com/a/31623388/2711766

Body:
Trying to call the web service as follows , and experiencing random "The network connection was lost" error causing app crash on device as well as simulator.

 Alamofire.request(url, method: .post, parameters: ["limit" : "3" , "offset" : self.storeArray?.count ?? 0], encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

                switch(response.result) {
                case .success(_):

my error bellow

Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x608000a5f950 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60800029fea0 [0x1136c0df0]>{length = 16, capacity = 16, bytes = 0x10020050a63e1c720000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://lokomart.com/services/getSearchResultData, NSErrorFailingURLKey=http://lokomart.com/services/getSearchResultData, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.})

// I have using php backend with godaddy deluxe hosting.

and also working with swift 3

Body:
Today, i had the same error. And i remember the property added for apple into iOS 9 NSAppTransportSecurity. You can try disable only for test, adding this:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

You can to do this configuration better following this answer https://stackoverflow.com/a/31623388/2711766


问:
match column value, which is comma seperated column value
I have 3 columns in a table name is users. In zip_codes, there are more than one zip codes with comma separation.

```<code> id        ZIP_codes            user_email

 1          123,785,333         a@gmail.com
 2          785,241,123          v@gmail.com
</code>```

Now I have a other table name is student.

```<code>id        ZIP_code          std_email

 1          123              std1@gmail.com
 2          241              std2@gmail.com
</code>```

student.zip_code is coming from first.php and on second.php, it is matching with users.zip_codes. Now if 123 matches with other table then only a@gmail.com and v@gmail.com should be come and by 241 v@gmail.com should be come.

My code for second.php is:

```<code> <?php
 extract($_POST);
"SET @search = '$zip_code'";
$SQLSELECT = "SELECT * FROM users where REGEXP CONCAT('(^|,)(', REPLACE(@search, ',', '|'), ')(,|$)')";

$result_set =  mysql_query($SQLSELECT) or die(mysql_error());
while($row = mysql_fetch_array($result_set))
{
extract($row);
echo $user_email;
}
            ?>
</code>```

But it not working.

答:
I solved my query by FIND_IN_SET ().

SELECT * FROM users WHERE FIND_IN_SET ($zip1, zip_codes);

Body:
I have 3 columns in a table name is users. In zip_codes, there are more than one zip codes with comma separation.

 id        ZIP_codes            user_email

 1          123,785,333         a@gmail.com
 2          785,241,123          v@gmail.com

Now I have a other table name is student.

id        ZIP_code          std_email

 1          123              std1@gmail.com
 2          241              std2@gmail.com

student.zip_code is coming from first.php and on second.php, it is matching with users.zip_codes. Now if 123 matches with other table then only a@gmail.com and v@gmail.com should be come and by 241 v@gmail.com should be come.

My code for second.php is:

 <?php
 extract($_POST);
"SET @search = '$zip_code'";
$SQLSELECT = "SELECT * FROM users where REGEXP CONCAT('(^|,)(', REPLACE(@search, ',', '|'), ')(,|$)')";

$result_set =  mysql_query($SQLSELECT) or die(mysql_error());
while($row = mysql_fetch_array($result_set))
{
extract($row);
echo $user_email;
}
            ?>

But it not working.