问:
Jackson with ParameterNamesModule failing to deserialize class
I have the following classes (which I've simplified from what I'm actually trying to do, but the Exception is the same):

ParameterNameTest.java

```<code>package foo;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

public class ParameterNameTest {

  @Test
  public void test() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));

    Settings settings = objectMapper.readValue("{\"ignoreDate\": true}", DateSettings.class);
  }

  @Test
  public void testConstructorParameters() {
    Constructor[] constructors = DateSettings.class.getConstructors();
    for (Constructor constructor : constructors) {
      System.out.print(constructor.getName() + "( ");
      Parameter[] parameters = constructor.getParameters();
      for (Parameter parameter : parameters) {
        System.out.print(parameter.getType().getName() + " " + parameter.getName() + " ");
      }
      System.out.println(")");
    }
  }
}
</code>```

DateSettings.java

```<code>package foo;

public class DateSettings implements Settings {
  private final boolean ignoreDate;

  public DateSettings(boolean ignoreDate) {
    this.ignoreDate = ignoreDate;
  }

  public boolean isIgnoreDate() {
    return ignoreDate;
  }
}
</code>```

Settings.java

```<code>package foo;

public interface Settings {}
</code>```

My understanding from reading the Jackson documentation and other posts on StackOverflow, is that this should allow me to deserialize my JSON object into a DateSettings class without annotating that class (which I can't do, as in my real case it is a third party library). However, I get the following Exception:

```<code>com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `foo.DateSettings` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"ignoreDates": true}"; line: 1, column: 2]

    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at foo.ParameterNameTest.test(ParameterNameTest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

I'm aware that I need -parameters enabled when compiling, and using the testConstructorParameters test above I've convinced myself that this isn't the problem.

Where else could I be going wrong?

Update: Looks like this is being caused by this issue, https://github.com/FasterXML/jackson-databind/issues/1498, which has been open for quite a while now. If anyone has a workaround, I'd be interested to see it.

答:
so  I had a slow day and this was an interesting problem. I found the same issues on the github jackson page and it does seem like this is a regression. There is a way around it that I found that is a bit hacky but preserves backwards compatibility (I hope) and solves your direct issue. I needed to copy a few classes over due to package-privacy. If you were to put all your classes into the same jackson package, you might be able to get around it. Here is my solution in full (with the right dependencies, you should be able to paste and run this):

```<code>package com.paandadb.test;

import java.io.IOException;
import java.lang.reflect.Executable;
import java.lang.reflect.MalformedParametersException;
import java.lang.reflect.Parameter;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedConstructor;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

public class Test {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new HackedParameterModule(JsonCreator.Mode.PROPERTIES));

        DateSettings settings = objectMapper.readValue("{\"ignoreDate\": false}", DateSettings.class);
        System.out.println(settings.ignoreDate);
    }

    public static class DateSettings {
        private final boolean ignoreDate;

        public DateSettings(boolean ignoreDate) {
          this.ignoreDate = ignoreDate;
        }

        public boolean isIgnoreDate() {
          return ignoreDate;
        }
      }

    // we need to hack this because `ParameterExtractor` is package private, so we can't extend this class
    public static class HackedAnnotationIntrospector extends ParameterNamesAnnotationIntrospector {
        private static final long serialVersionUID = 1L;

        HackedAnnotationIntrospector(Mode creatorBinding, ParameterExtractor parameterExtractor) {
            super(creatorBinding, parameterExtractor);
        }
    }

    // we need to register a different introspector for the annotations
    public static class HackedParameterModule extends ParameterNamesModule {
        private static final long serialVersionUID = 1L;
        public HackedParameterModule(Mode properties) {
            super(properties);
        }

        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.insertAnnotationIntrospector(new ParameterNamesAnnotationIntrospector(JsonCreator.Mode.DEFAULT, new ParameterExtractor()));
        }
    }

    // This is the hacked introspector that simply returns default instead of null
    // you may want to make more checks here to make sure it works the way you want to and has no
    // side effects. Same thing here - need to extend because of package private `ParameterExtractor`
    public static class ParameterNamesAnnotationIntrospector extends NopAnnotationIntrospector {
        private static final long serialVersionUID = 1L;

        private final JsonCreator.Mode creatorBinding;
        private final ParameterExtractor parameterExtractor;

        ParameterNamesAnnotationIntrospector(JsonCreator.Mode creatorBinding, ParameterExtractor parameterExtractor)
        {
            this.creatorBinding = creatorBinding;
            this.parameterExtractor = parameterExtractor;
        }

        @Override
        public String findImplicitPropertyName(AnnotatedMember m) {
            if (m instanceof AnnotatedParameter) {
                return findParameterName((AnnotatedParameter) m);
            }
            return null;
        }

        private String findParameterName(AnnotatedParameter annotatedParameter) {
            Parameter[] params;
            try {
                params = getParameters(annotatedParameter.getOwner());
            } catch (MalformedParametersException e) {
                return null;
            }

            Parameter p = params[annotatedParameter.getIndex()];
            return p.isNamePresent() ? p.getName() : null;
        }

        private Parameter[] getParameters(AnnotatedWithParams owner) {
            if (owner instanceof AnnotatedConstructor) {
                return parameterExtractor.getParameters(((AnnotatedConstructor) owner).getAnnotated());
            }
            if (owner instanceof AnnotatedMethod) {
                return parameterExtractor.getParameters(((AnnotatedMethod) owner).getAnnotated());
            }

            return null;
        }

        /*
        /**********************************************************
        /* Creator information handling
        /**********************************************************
         */

        @Override
        public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            // THIS IS THE FIXING BIT
            // Note: I only enable this for your specific class, all other cases are handled in default manner
            Class<?> rawType = a.getRawType();
            if(ann == null && rawType.isAssignableFrom(DateSettings.class)) {
                return JsonCreator.Mode.DEFAULT;
            }
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                // but keep in mind that there may be explicit default for this module
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return null;
        }

        // I left the other functions from the original code in to prevent breakage
        @Override
        @Deprecated // remove AFTER 2.9
        public JsonCreator.Mode findCreatorBinding(Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return creatorBinding;
        }

        @Override
        @Deprecated // since 2.9
        public boolean hasCreatorAnnotation(Annotated a)
        {
            // 02-Mar-2017, tatu: Copied from base AnnotationIntrospector
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            if (ann != null) {
                return (ann.mode() != JsonCreator.Mode.DISABLED);
            }
            return false;
        }
    }

    // This is the package private class that does not allow for proper extending
    // which is why we had to copy a bunch of code
    public static class ParameterExtractor {

        public Parameter[] getParameters(Executable executable) {
            return executable.getParameters();
        }
    }
}
</code>```

I left a number of comments in the code but will go into a bit of detail here:

Firstly, your problem is located in ParameterNamesAnnotationIntrospector#findCreatorAnnotation. This class is not enabled to simply find a non annotated constructor. Debugging the code with an annotation reveals that annotating the constructor simply results in a default JsonCreator.Mode function. This means that if we want our code to work, we need it to recognise a default where there isn't. Firstly though, we need to get our own module in. So we do this:

```<code>public static class HackedParameterModule extends ParameterNamesModule {
        private static final long serialVersionUID = 1L;
        public HackedParameterModule(Mode properties) {
            super(properties);
        }

        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.insertAnnotationIntrospector(new ParameterNamesAnnotationIntrospector(JsonCreator.Mode.DEFAULT, new ParameterExtractor()));
        }
    }
</code>```

This registers a custom module that extends the ParameterNamesModule. It is only needed because we need to register a custom ParameterNamesAnnotationIntrospector as well. And that one uses a class ParameterExtractor which is package private, therefore we need to step through the hierarchy.

Clicking through and registering we get to the introspector. Here I added this code:

```<code>@Override
public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            // THIS IS THE FIXING BIT
            // Note: I only enable this for your specific class, all other cases are handled in default manner
            Class<?> rawType = a.getRawType();
            if(ann == null && rawType.isAssignableFrom(DateSettings.class)) {
                return JsonCreator.Mode.DEFAULT;
            }
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                // but keep in mind that there may be explicit default for this module
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return null;
        }
</code>```

This code simply adds a new default behaviour. Iff the annotation isn't found, and we would end up in an exception, and the class raw type we try to create is DateSettings, then we simply return a default mode, which is the mode we need to enable jackson to use the 1 constructor that is available. Note: this will very likely break if you had a class with multiple constructors, I have not tried this

With all of this registered, I can run my main function and get no errors and print out the right values:

```<code>DateSettings settings = objectMapper.readValue("{\"ignoreDate\": false}", DateSettings.class);
System.out.println(settings.ignoreDate);
settings = objectMapper.readValue("{\"ignoreDate\": true}", DateSettings.class);
System.out.println(settings.ignoreDate);
</code>```

Prints:

```<code>false
true
</code>```

I am not sure whether this is a decent solution. But if you are really stuck and there are no other changes that you can make, this is a way to customise jackson to your advantage.

I hope that helps!

Note: I left the names the same which may cause import problems for you. It might be worth renaming all the classes into something more distinguishable :)

Artur

Body:
I have the following classes (which I've simplified from what I'm actually trying to do, but the Exception is the same):

ParameterNameTest.java

package foo;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

public class ParameterNameTest {

  @Test
  public void test() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));

    Settings settings = objectMapper.readValue("{\"ignoreDate\": true}", DateSettings.class);
  }

  @Test
  public void testConstructorParameters() {
    Constructor[] constructors = DateSettings.class.getConstructors();
    for (Constructor constructor : constructors) {
      System.out.print(constructor.getName() + "( ");
      Parameter[] parameters = constructor.getParameters();
      for (Parameter parameter : parameters) {
        System.out.print(parameter.getType().getName() + " " + parameter.getName() + " ");
      }
      System.out.println(")");
    }
  }
}

DateSettings.java

package foo;

public class DateSettings implements Settings {
  private final boolean ignoreDate;

  public DateSettings(boolean ignoreDate) {
    this.ignoreDate = ignoreDate;
  }

  public boolean isIgnoreDate() {
    return ignoreDate;
  }
}

Settings.java

package foo;

public interface Settings {}

My understanding from reading the Jackson documentation and other posts on StackOverflow, is that this should allow me to deserialize my JSON object into a DateSettings class without annotating that class (which I can't do, as in my real case it is a third party library). However, I get the following Exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `foo.DateSettings` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"ignoreDates": true}"; line: 1, column: 2]

    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at foo.ParameterNameTest.test(ParameterNameTest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I'm aware that I need -parameters enabled when compiling, and using the testConstructorParameters test above I've convinced myself that this isn't the problem.

Where else could I be going wrong?

Update: Looks like this is being caused by this issue, https://github.com/FasterXML/jackson-databind/issues/1498, which has been open for quite a while now. If anyone has a workaround, I'd be interested to see it.

Body:
so  I had a slow day and this was an interesting problem. I found the same issues on the github jackson page and it does seem like this is a regression. There is a way around it that I found that is a bit hacky but preserves backwards compatibility (I hope) and solves your direct issue. I needed to copy a few classes over due to package-privacy. If you were to put all your classes into the same jackson package, you might be able to get around it. Here is my solution in full (with the right dependencies, you should be able to paste and run this):

package com.paandadb.test;

import java.io.IOException;
import java.lang.reflect.Executable;
import java.lang.reflect.MalformedParametersException;
import java.lang.reflect.Parameter;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedConstructor;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

public class Test {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new HackedParameterModule(JsonCreator.Mode.PROPERTIES));

        DateSettings settings = objectMapper.readValue("{\"ignoreDate\": false}", DateSettings.class);
        System.out.println(settings.ignoreDate);
    }

    public static class DateSettings {
        private final boolean ignoreDate;

        public DateSettings(boolean ignoreDate) {
          this.ignoreDate = ignoreDate;
        }

        public boolean isIgnoreDate() {
          return ignoreDate;
        }
      }

    // we need to hack this because `ParameterExtractor` is package private, so we can't extend this class
    public static class HackedAnnotationIntrospector extends ParameterNamesAnnotationIntrospector {
        private static final long serialVersionUID = 1L;

        HackedAnnotationIntrospector(Mode creatorBinding, ParameterExtractor parameterExtractor) {
            super(creatorBinding, parameterExtractor);
        }
    }

    // we need to register a different introspector for the annotations
    public static class HackedParameterModule extends ParameterNamesModule {
        private static final long serialVersionUID = 1L;
        public HackedParameterModule(Mode properties) {
            super(properties);
        }

        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.insertAnnotationIntrospector(new ParameterNamesAnnotationIntrospector(JsonCreator.Mode.DEFAULT, new ParameterExtractor()));
        }
    }

    // This is the hacked introspector that simply returns default instead of null
    // you may want to make more checks here to make sure it works the way you want to and has no
    // side effects. Same thing here - need to extend because of package private `ParameterExtractor`
    public static class ParameterNamesAnnotationIntrospector extends NopAnnotationIntrospector {
        private static final long serialVersionUID = 1L;

        private final JsonCreator.Mode creatorBinding;
        private final ParameterExtractor parameterExtractor;

        ParameterNamesAnnotationIntrospector(JsonCreator.Mode creatorBinding, ParameterExtractor parameterExtractor)
        {
            this.creatorBinding = creatorBinding;
            this.parameterExtractor = parameterExtractor;
        }

        @Override
        public String findImplicitPropertyName(AnnotatedMember m) {
            if (m instanceof AnnotatedParameter) {
                return findParameterName((AnnotatedParameter) m);
            }
            return null;
        }

        private String findParameterName(AnnotatedParameter annotatedParameter) {
            Parameter[] params;
            try {
                params = getParameters(annotatedParameter.getOwner());
            } catch (MalformedParametersException e) {
                return null;
            }

            Parameter p = params[annotatedParameter.getIndex()];
            return p.isNamePresent() ? p.getName() : null;
        }

        private Parameter[] getParameters(AnnotatedWithParams owner) {
            if (owner instanceof AnnotatedConstructor) {
                return parameterExtractor.getParameters(((AnnotatedConstructor) owner).getAnnotated());
            }
            if (owner instanceof AnnotatedMethod) {
                return parameterExtractor.getParameters(((AnnotatedMethod) owner).getAnnotated());
            }

            return null;
        }

        /*
        /**********************************************************
        /* Creator information handling
        /**********************************************************
         */

        @Override
        public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            // THIS IS THE FIXING BIT
            // Note: I only enable this for your specific class, all other cases are handled in default manner
            Class<?> rawType = a.getRawType();
            if(ann == null && rawType.isAssignableFrom(DateSettings.class)) {
                return JsonCreator.Mode.DEFAULT;
            }
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                // but keep in mind that there may be explicit default for this module
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return null;
        }

        // I left the other functions from the original code in to prevent breakage
        @Override
        @Deprecated // remove AFTER 2.9
        public JsonCreator.Mode findCreatorBinding(Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return creatorBinding;
        }

        @Override
        @Deprecated // since 2.9
        public boolean hasCreatorAnnotation(Annotated a)
        {
            // 02-Mar-2017, tatu: Copied from base AnnotationIntrospector
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            if (ann != null) {
                return (ann.mode() != JsonCreator.Mode.DISABLED);
            }
            return false;
        }
    }

    // This is the package private class that does not allow for proper extending
    // which is why we had to copy a bunch of code
    public static class ParameterExtractor {

        public Parameter[] getParameters(Executable executable) {
            return executable.getParameters();
        }
    }
}

I left a number of comments in the code but will go into a bit of detail here:

Firstly, your problem is located in ParameterNamesAnnotationIntrospector#findCreatorAnnotation. This class is not enabled to simply find a non annotated constructor. Debugging the code with an annotation reveals that annotating the constructor simply results in a default JsonCreator.Mode function. This means that if we want our code to work, we need it to recognise a default where there isn't. Firstly though, we need to get our own module in. So we do this:

public static class HackedParameterModule extends ParameterNamesModule {
        private static final long serialVersionUID = 1L;
        public HackedParameterModule(Mode properties) {
            super(properties);
        }

        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.insertAnnotationIntrospector(new ParameterNamesAnnotationIntrospector(JsonCreator.Mode.DEFAULT, new ParameterExtractor()));
        }
    }

This registers a custom module that extends the ParameterNamesModule. It is only needed because we need to register a custom ParameterNamesAnnotationIntrospector as well. And that one uses a class ParameterExtractor which is package private, therefore we need to step through the hierarchy.

Clicking through and registering we get to the introspector. Here I added this code:

@Override
public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) {
            JsonCreator ann = _findAnnotation(a, JsonCreator.class);
            // THIS IS THE FIXING BIT
            // Note: I only enable this for your specific class, all other cases are handled in default manner
            Class<?> rawType = a.getRawType();
            if(ann == null && rawType.isAssignableFrom(DateSettings.class)) {
                return JsonCreator.Mode.DEFAULT;
            }
            if (ann != null) {
                JsonCreator.Mode mode = ann.mode();
                // but keep in mind that there may be explicit default for this module
                if ((creatorBinding != null)
                        && (mode == JsonCreator.Mode.DEFAULT)) {
                    mode = creatorBinding;
                }
                return mode;
            }
            return null;
        }

This code simply adds a new default behaviour. Iff the annotation isn't found, and we would end up in an exception, and the class raw type we try to create is DateSettings, then we simply return a default mode, which is the mode we need to enable jackson to use the 1 constructor that is available. Note: this will very likely break if you had a class with multiple constructors, I have not tried this

With all of this registered, I can run my main function and get no errors and print out the right values:

DateSettings settings = objectMapper.readValue("{\"ignoreDate\": false}", DateSettings.class);
System.out.println(settings.ignoreDate);
settings = objectMapper.readValue("{\"ignoreDate\": true}", DateSettings.class);
System.out.println(settings.ignoreDate);

Prints:

false
true

I am not sure whether this is a decent solution. But if you are really stuck and there are no other changes that you can make, this is a way to customise jackson to your advantage.

I hope that helps!

Note: I left the names the same which may cause import problems for you. It might be worth renaming all the classes into something more distinguishable :)

Artur


来源: stackexchange

问:
MySQL error: #1045 - Access denied for user 'root'@'localhost' (using password: YES)
I have tried every fix that I have found, and I cannot change my root MySQL password.  At the shell, if I type in mysql -u root, I get

Access denied for user 'root'@'localhost' (using password: NO)

When I go to PHP MyAdmin, I get this:

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

This all started when I was forced to enter a new password for MySQL.  I have NO idea how to fix this and I am desperate.

Thank you.

答:
For Windows users: Before starting to recover your password, try in command line:

```<code>mysql -uroot -pyourpassword
</code>```

as is, without space like shown below:

Print of my MySQL login

I have no time to explain why, but if you want to know more, please check how the 'MySQL X.X command line client' shortcut in your computer works.

In time, make sure that the mysql paths are in the PATH variable.

My computer is using these paths shown below. Your computer might be using other paths.
C:\ProgramData\MySQL\MySQL Server 8.0
C:\Program Files\MySQL\MySQL Server 8.0\bin

ContentLicense: CC BY-SA 3.0

Body:
For Windows users: Before starting to recover your password, try in command line:

mysql -uroot -pyourpassword

as is, without space like shown below:

Print of my MySQL login

I have no time to explain why, but if you want to know more, please check how the 'MySQL X.X command line client' shortcut in your computer works.

In time, make sure that the mysql paths are in the PATH variable.

My computer is using these paths shown below. Your computer might be using other paths.
C:\ProgramData\MySQL\MySQL Server 8.0
C:\Program Files\MySQL\MySQL Server 8.0\bin

ContentLicense: CC BY-SA 4.0


问:
Is an empty href valid?
One of our web developers uses the following html as a placeholder for styling a drop down list.

```<code><a href="" class="arrow"></a>
</code>```

Is this considered anchor tag valid?

Since there is no href value, it shows up as broken on some of our link checker reports.

答:
The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

Title: Is an empty href valid?

Body:
One of our web developers uses the following html as a placeholder for styling a drop down list.

Is this considered anchor tag valid?

Since there is no href value, it shows up as broken on some of our link checker reports.


问:
In javavscript, what is the difference between: (function(){"use strict"}) (); and "use strict"?
What is the difference between:

```<code>(function () {'use strict';})();
</code>```

and  "use strict".

I don't understand when or why I would use one over the other?

I think that one declares the complete external JS document strict and the other makes a function strict.

My confusion comes when I see people enclose their complete external JavaScript in:

```<code>(function () {'use strict';})();
</code>```

Why not just start the document with use "use strict"?

Lastly, I have tested an external JS doc using the same code.
One, I used "use strict" and it worked.

The other I enclosed the complete JS document with (function () {'use strict';})(); and it did not work.

Why?

JavaScript is my first programming language and I am a little overwhelmed by its depth. I really appreciate your patience and professional guidance thank you for any help or direction you can offer me.

Thank you so much.

答:
Well

```<code>(function() { "use strict"; })()
</code>```

is completely useless; it has no effect on anything.

At the beginning of a scope, like a function or a

Body:
What is the difference between:

(function () {'use strict';})();

and  "use strict".

I don't understand when or why I would use one over the other?

I think that one declares the complete external JS document strict and the other makes a function strict.

My confusion comes when I see people enclose their complete external JavaScript in:

(function () {'use strict';})();

Why not just start the document with use "use strict"?

Lastly, I have tested an external JS doc using the same code.
One, I used "use strict" and it worked.

The other I enclosed the complete JS document with (function () {'use strict';})(); and it did not work.

Why?

JavaScript is my first programming language and I am a little overwhelmed by its depth. I really appreciate your patience and professional guidance thank you for any help or direction you can offer me.

Thank you so much.

Body:
Well

(function() { "use strict"; })()

is completely useless; it has no effect on anything.

At the beginning of a scope, like a function or a <script> block,

"use strict";

signals the interpreter that you want code interpreted in "strict" mode. If it's in a function that does nothing, it has no meaningful effect on anything. Of course, if the actual function you're talking about has more code than just the "use strict"; statement, then it means that that function will be interpreted in "strict" mode.


问:
In Shopify Private app, Proxy URL Redirect to App's Server URL
I am working on Shopify private app in the Laravel Framework. In my app, I have added a proxy URL. But when I am trying to open my proxy URL then It will redirect to me on my app server URL.

Here's the screenshot my partner account:-

For Example:-
Whenever I tried to open proxy URL:- https://test.myshopify.com/a/test

It will redirect to my app server URL:-
https://test.devserver.co.in/shopify/test?shop=test.myshopify.com&path_prefix=%2Fa%test&timestamp=1559210902&signature=bed7eb24d4a9278021a12535df9e38749a333a9dd33e7164fb66c113a2a00a0e

Please help me with this.
Thanks

答:
You don't actually callback to your proxy URL like https://test.myshopify.com/a/fizzbuzz

Instead you do a POST or a GET to /a/fizzbuzz with some parameters (or not). In other words, it is as if you are doing a POST or GET to something local to the Shopify store itself. There is nothing to identify your actual proxy App.

Perhaps this is your simple problem. Shopify will take your POST or GET, and proxy it for you to the right endpoint in your App, with security.


问:
Can I get every month of the year even if there is not data for that month in DB
I want to get a statistic for every month of the years i have in DB

```<code>SELECT      monthname(created_at) AS month, YEAR(created_at) AS year, count(*) AS number
FROM        tableName
WHERE       type_of_user = "someType"
GROUP BY    year, month(created_at)
ORDER BY    created_at DESC
</code>```

Now it gives me only month that I have, but I need to get statistics  for every month, even if I don't have any stored data for that month

答:
Create a calendar table. This will need one entry per month, for every year that you intend to use.

Then select from the calendar table, and join in the values that you get from your current query. Use COALESCE() to put a zero-value where the entry is NULL (e.g. when there are no records in the tableName for that month and year).

SELECT MONTHNAME(date) as month,
       YEAR(date) as year,
       COALESCE(number, 0) as number
FROM calendar AS C
LEFT JOIN (
  SELECT created_at, COUNT(*) as number
  FROM tableName AS T
  WHERE T.type_of_user = 'someType'
  GROUP BY YEAR(created_at), MONTH(created_at)
) AS T
ON MONTH(T.created_at) = MONTH(C.date) AND YEAR(T.created_at) = YEAR(C.date)
GROUP BY month, YEAR(created_at)
ORDER BY MONTH(date), YEAR(date)
```

SQL fiddle at http://sqlfiddle.com/#!9/e0a4dc/

Body:
I want to get a statistic for every month of the years i have in DB

SELECT      monthname(created_at) AS month, YEAR(created_at) AS year, count(*) AS number
FROM        tableName
WHERE       type_of_user = "someType"
GROUP BY    year, month(created_at)
ORDER BY    created_at DESC

Now it gives me only month that I have, but I need to get statistics  for every month, even if I don't have any stored data for that month

Body:
Create a calendar table. This will need one entry per month, for every year that you intend to use.

Then select from the calendar table, and join in the values that you get from your current query. Use COALESCE() to put a zero-value where the entry is NULL (e.g. when there are no records in the tableName for that month and year).

SELECT MONTHNAME(date) as month,
       YEAR(date) as year,
       COALESCE(number, 0) as number
FROM calendar AS C
LEFT JOIN (
  SELECT created_at, COUNT(*) as number
  FROM tableName AS T
  WHERE T.type_of_user = 'someType'
  GROUP BY YEAR(created_at), MONTH(created_at)
) AS T
ON MONTH(T.created_at) = MONTH(C.date) AND YEAR(T.created_at) = YEAR(C.date)
GROUP BY month, YEAR(created_at)
ORDER BY MONTH(date), YEAR(date)

SQL fiddle at http://sqlfiddle.com/#!9/e0a4dc/


问:
BorderColor not picking the linearGradient color on android
Im trying to create a circle with an image inside it that its border is colourful that's why I used LinearGradient.

I was using this guide:

https://codeburst.io/linear-gradient-for-border-color-in-react-native-5bcab3eea1c9

the problem that in iOS its working fine as you can see in this image:

https://imgur.com/a/Tz0uEcC

but on android the when I use borderWidth and choosing borderColor of transparent the borderColor looks like shadow and not picking the LinearGradient color from some reason...

here is the android:
https://imgur.com/a/qG1LJBt

what am I doing wrong?

```<code>
        <LinearGradient
          colors={['#ac8af8', '#cca5e7']}
          start={{ x: 0.0, y: 1.0 }} end={{ x: 1.0, y: 1.0 }}
          style={styles.profilePhotoContainer}
        >
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
            <Image
          style={[styles.profileImage]}
          source={this.state.profilePhoto}
        />
          </TouchableOpacity>
        </LinearGradient>

const styles = StyleSheet.create({
profilePhotoContainer: {
    zIndex: 5,
    position: 'absolute',
    top: Dimensions.get('window').height * .13,
    left: Dimensions.get('window').width / 2 - Dimensions.get('window').width * .13,
    elevation: 4,
    borderRadius: 75,
    borderWidth: 4,
    overflow: "hidden" ,
    borderColor: 'transparent',
  },
profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderWidth: 1,
    borderColor: 'transparent',
    backgroundColor: '#FFF',
    flex:1,
    resizeMode:'contain',
  },

})

</code>```

答:
You should add style to the TouchableOpacity:

```<code>style={{
  width: 100,
  height: 100, backgroundColor: 'transparent', overflow: "hidden", borderRadius: 50, flex: 1}}
</code>```

in addition change the style of profilePhotoContainer to:

```<code>profilePhotoContainer: {
    zIndex: 5,
    position: 'absolute',
    top: Dimensions.get('window').height * .13,
    left: Dimensions.get('window').width / 2 - Dimensions.get('window').width * .13,
    elevation: 4,
    borderRadius: 75,
    padding: 5,
    overflow: "hidden",
    borderColor: 'transparent',
  }

</code>```

Body:
Im trying to create a circle with an image inside it that its border is colourful that's why I used LinearGradient.

I was using this guide:

https://codeburst.io/linear-gradient-for-border-color-in-react-native-5bcab3eea1c9

the problem that in iOS its working fine as you can see in this image:

https://imgur.com/a/Tz0uEcC

but on android the when I use borderWidth and choosing borderColor of transparent the borderColor looks like shadow and not picking the LinearGradient color from some reason...

here is the android:
https://imgur.com/a/qG1LJBt

what am I doing wrong?

        <LinearGradient
          colors={['#ac8af8', '#cca5e7']}
          start={{ x: 0.0, y: 1.0 }} end={{ x: 1.0, y: 1.0 }}
          style={styles.profilePhotoContainer}
        >
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
            <Image
          style={[styles.profileImage]}
          source={this.state.profilePhoto}
        />
          </TouchableOpacity>
        </LinearGradient>

const styles = StyleSheet.create({
profilePhotoContainer: {
    zIndex: 5,
    position: 'absolute',
    top: Dimensions.get('window').height * .13,
    left: Dimensions.get('window').width / 2 - Dimensions.get('window').width * .13,
    elevation: 4,
    borderRadius: 75,
    borderWidth: 4,
    overflow: "hidden" ,
    borderColor: 'transparent',
  },
profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderWidth: 1,
    borderColor: 'transparent',
    backgroundColor: '#FFF',
    flex:1,
    resizeMode:'contain',
  },

})

Body:
You should add style to the TouchableOpacity:

style={{
  width: 100,
  height: 100, backgroundColor: 'transparent', overflow: "hidden", borderRadius: 50, flex: 1}}

in addition change the style of profilePhotoContainer to:

profilePhotoContainer: {
    zIndex: 5,
    position: 'absolute',
    top: Dimensions.get('window').height * .13,
    left: Dimensions.get('window').width / 2 - Dimensions.get('window').width * .13,
    elevation: 4,
    borderRadius: 75,
    padding: 5,
    overflow: "hidden",
    borderColor: 'transparent',
  }


问:
Restart the codeblock with a while-loop
Problem: I would like to restart my codeblock after the error message.

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");

if (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");
```

答:
You can just change your if into a while:

```<code>Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");
</code>```

Title: Restart the codeblock with a while-loop

Body:
You can just change your if into a while:

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");


问:
How to decode php json array?
I want to show name and type but not working. How can I do taht?

$json:

```<code>{"222":{"id":"222","name":"Shirt1","type":"Men","product":"1","count":"2","price":7000},"223":{"id":"223","name":"Shirt2","type":"Men","product":"2","count":"1","price":4000},"224":{"id":"224","name":"Shirt3","product":"3","count":"2","price":14000}}
</code>```

Decode:

```<code>$products = json_decode($json, true);
foreach ($products['id'] as $k => $v)
{
    var_dump(array_key_exists('name', $v));
}
</code>```

答:
```<code>$products = json_decode($json, true);

$result = '';

foreach( $products as $product ) {
   $result .= 'Name : ' . $product['name'] . ', type : ' . $product['type'] . ';';
}

echo $result;
</code>```

Title: How to decode php json array?

Body:
I want to show name and type but not working. How can I do taht?

$json:

{"222":{"id":"222","name":"Shirt1","type":"Men","product":"1","count":"2","price":7000},"223":{"id":"223","name":"Shirt2","type":"Men","product":"2","count":"1","price":4000},"224":{"id":"224","name":"Shirt3","product":"3","count":"2","price":14000}}

Decode:

$products = json_decode($json, true);
foreach ($products['id'] as $k => $v)
{
    var_dump(array_key_exists('name', $v));
}


问:
Jasmine SpyOn same method more than once
I have an angular controller with a method that calls $location.search() twice.

First time is just $location.search() to return the value.

Second time is $location.search("foo", null) to clear it.

I have the following spy in my unit test:

spyOn($location, "search").and.returnValue({ foo: "bar" });

It appears the spy returns {foo:"bar"} even when my implementation does $location.search("foo", null).

I need a way to have two different spies for the same method depending on the arguments.

I need this expect:

expect($location.search().foo).toEqual(null);

to pass at the end of the unit test.

答:
Also it's possible to call spy properties on the mocked object directly. The code may look like:

```<code>spyOn($location,'search');

$location.search.and.returnValue(null);
// do stuff
$location.search.and.returnValue({ foo: "bar" })
// do other stuff
</code>```

In case of typescript it may look like:

```<code>spyOn($location,'search');

(<jasmine.Spy>$location.search).and.returnValue(null);
// do stuff
(<jasmine.Spy>$location.search).and.returnValue({ foo: "bar" })
// do other stuff
</code>```

Posting this answer because it may look a bit cleaner and doesn't require additional variables.

Body:
Also it's possible to call spy properties on the mocked object directly. The code may look like:

spyOn($location,'search');

$location.search.and.returnValue(null);
// do stuff
$location.search.and.returnValue({ foo: "bar" })
// do other stuff

In case of typescript it may look like:

spyOn($location,'search');

(<jasmine.Spy>$location.search).and.returnValue(null);
// do stuff
(<jasmine.Spy>$location.search).and.returnValue({ foo: "bar" })
// do other stuff

Posting this answer because it may look a bit cleaner and doesn't require additional variables.


答:
If you

```<code>"use strict";
</code>```

At the top of the file, the entire file (that is, all code in the file/script tag, including third-party libraries [thanks VLAZ for clarification]) is strict.

Placing it inside an IIFE:

```<code>(function() { "use strict"; })();
</code>```

Means that only code inside the IIFE will be strict.

Title: In javavscript, what is the difference between: (function(){"use strict"}) (); and "use strict"?

Body:
If you

"use strict";

At the top of the file, the entire file (that is, all code in the file/script tag, including third-party libraries [thanks VLAZ for clarification]) is strict.

Placing it inside an IIFE:

(function() { "use strict"; })();

Means that only code inside the IIFE will be strict.


问:
Facebook share text
I have these links on my site

```<code><a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/4')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/5')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/8')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/9')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/10')" target="_blank" style="text-decoration:none;"></a>
</code>```

with this javascript

```<code><script>
function fbs_click(location_place) {
        u=location_place;
        t=document.title;
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    }
</script>
</code>```

and i want to know if there is a way to add text or some sort to each one uniquely so that each link as a different body ..here is my code working but where and how do i add a description of some sort

答:
If my memory is good, you can add a parameter in the facebook.com/sharer.php? url like so :

facebook.com/sharer.php?u=yourlinke&t=The text you want it to be in the textarea

Title: Facebook share text

Body:
I have these links on my site

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/4')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/5')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/8')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/9')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/10')" target="_blank" style="text-decoration:none;">

with this javascript

and i want to know if there is a way to add text or some sort to each one uniquely so that each link as a different body ..here is my code working but where and how do i add a description of some sort


问:
How to insert data into bridging/mapping table using Sequelize.js
I am trying to insert data into the bridging/mapping table using sequelize.js

I defined the Articles as-

```<code>const Articles = db.define('article', {
    "slug": {
      type: Sequelize.STRING,
      primaryKey: true,
      allowNull:false
    },
    "title": {
      type: Sequelize.STRING(50),
      allowNull: false
    },
    "description": {
      type: Sequelize.STRING(100),
    },
    "body": Sequelize.STRING,
  })
</code>```

and Tags as-

```<code>const Tags = db.define('tag', {
    name: {
      type: Sequelize.STRING,
      primaryKey: true
    }
})
</code>```

I created a many-to-many association between them as

```<code>Articles.belongsToMany(Tags, {through:'article_tags'})
Tags.belongsToMany(Articles, {through:'article_tags'})
</code>```

This created a table article_tags in my Database along with articles and tags. But now how can I insert data into this article_tags bridging table using sequelize?

答:
You have to model that mapping table as well.... then when you are in the resolver for say something like "tagArticle" you would just call the create function on the mapping table with the id of the article and the id of the tag... here is an example of a resolver for a join table i have where i am joining Dealers to Accounts

```<code>createUserAccountDealer: async (_, args, { models }) => {

      let returnValue = null;
      const { username, input } = args;
      try {
        returnValue = await models.ProfileDealerInfo.create(input);

        if (returnValue && returnValue.dataValues.id) {
          const tempJoin = { username, dealer_id: returnValue.dataValues.id };
          await models.ProfileAccountDealer.create(tempJoin);
        }
      } catch (err) {
        logger.error(err);
      }
      return returnValue;
    }
</code>```

The difference for me is that dealer is a child of account, so i do the join record right after creating the child dealer record... Your example is a little diff where tags and articles may already exist and you may just only be associating them meaning the id's would just be passed in the args from the client and you would not have the extra step of waiting to get the id back from the child record create

Body:
I am trying to insert data into the bridging/mapping table using sequelize.js

I defined the Articles as-

const Articles = db.define('article', {
    "slug": {
      type: Sequelize.STRING,
      primaryKey: true,
      allowNull:false
    },
    "title": {
      type: Sequelize.STRING(50),
      allowNull: false
    },
    "description": {
      type: Sequelize.STRING(100),
    },
    "body": Sequelize.STRING,
  })

and Tags as-

const Tags = db.define('tag', {
    name: {
      type: Sequelize.STRING,
      primaryKey: true
    }
})

I created a many-to-many association between them as

Articles.belongsToMany(Tags, {through:'article_tags'})
Tags.belongsToMany(Articles, {through:'article_tags'})

This created a table article_tags in my Database along with articles and tags. But now how can I insert data into this article_tags bridging table using sequelize?

Body:
You have to model that mapping table as well.... then when you are in the resolver for say something like "tagArticle" you would just call the create function on the mapping table with the id of the article and the id of the tag... here is an example of a resolver for a join table i have where i am joining Dealers to Accounts

createUserAccountDealer: async (_, args, { models }) => {

      let returnValue = null;
      const { username, input } = args;
      try {
        returnValue = await models.ProfileDealerInfo.create(input);

        if (returnValue && returnValue.dataValues.id) {
          const tempJoin = { username, dealer_id: returnValue.dataValues.id };
          await models.ProfileAccountDealer.create(tempJoin);
        }
      } catch (err) {
        logger.error(err);
      }
      return returnValue;
    }

The difference for me is that dealer is a child of account, so i do the join record right after creating the child dealer record... Your example is a little diff where tags and articles may already exist and you may just only be associating them meaning the id's would just be passed in the args from the client and you would not have the extra step of waiting to get the id back from the child record create


答:
It would be very simple:

```<code>Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

    Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
}
</code>```

You need to make sure to prompt the user again, otherwise they will not know that they need to enter another number.

Title: Restart the codeblock with a while-loop

Body:
Problem: I would like to restart my codeblock after the error message.

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");

if (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

Body:
It would be very simple:

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

    Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
}

You need to make sure to prompt the user again, otherwise they will not know that they need to enter another number.


问:
Apple pay: is there a difference in payment tokens created on the web vs in-app?
I'm trying to implement apple pay on the web, with a payment provider (worldpay) which does not say they support apple pay on the web, only in-app.

To get around this, I'm trying to be cheeky and do the integration by "pretending to be an app". I use an apple pay token I obtained from the browser, and send it to the payment provider using the same endpoints used by an app. Everything looks like it's working fine, but in the end all payments are declined, as though the bank has declined a payment. They show up in my wallet as declined as well.

In order to figure this out, I want to know: is a difference in the structure and/or contents of the apple payment token in apps and on the web? And if so, what are the differences?

I've read this Payment Token Format Reference from apple but it did not make me any wiser.

Here is an example of how a token looks on the web:

```<code>{
    "version": "EC_v1",
    "data": "DP...A=",
    "header": {
        "ephemeralPublicKey": "MF...5g==",
        "publicKeyHash": "kd...l4=",
        "transactionId": "a5...3e"
    }
}
</code>```

Appriciate any help!

答:
From what I know, no there is no difference between tokens. Even though I only used it with swift in-app, I would assume the tokens are the same just like with stripe and paypal.

Some research on this suggests that since they don't mention a difference in their official documentation, I would suppose they are the same.

https://developer.apple.com/apple-pay/planning/

Hope this helps.

Body:
I'm trying to implement apple pay on the web, with a payment provider (worldpay) which does not say they support apple pay on the web, only in-app.

To get around this, I'm trying to be cheeky and do the integration by "pretending to be an app". I use an apple pay token I obtained from the browser, and send it to the payment provider using the same endpoints used by an app. Everything looks like it's working fine, but in the end all payments are declined, as though the bank has declined a payment. They show up in my wallet as declined as well.

In order to figure this out, I want to know: is a difference in the structure and/or contents of the apple payment token in apps and on the web? And if so, what are the differences?

I've read this Payment Token Format Reference from apple but it did not make me any wiser.

Here is an example of how a token looks on the web:

{
    "version": "EC_v1",
    "data": "DP...A=",
    "header": {
        "ephemeralPublicKey": "MF...5g==",
        "publicKeyHash": "kd...l4=",
        "transactionId": "a5...3e"
    }
}

Appriciate any help!


问:
I want to click a button on 3rd window,which is an active element
First window is Parent window. then it populates two child window, some times while i inspect it shows 2 windows some times it shows 3 windows. I have to find a solution to switch on active window and to click the active element using Java.

Thread.sleep(1000);
                System.out.println(driver.getWindowHandles().size());

```<code>        for(String WinID : driver.getWindowHandles() ) {
            System.out.println(WinID);
            driver.switchTo().window(WinID);
          driver.findElement(Group.btnmodexit).click();
        }
</code>```

答:
not sure why its not working for u, it works fine for me. U getting all opened tabs in array list then jumping to required tab by index, which is u passing to method by property.

```<code>    public void switchBetweenTabs(int tabIndex)
{
    ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());

    driver.switchTo().window(tabs.get(tabIndex));
}
</code>```

Then click on your button.

Body:
First window is Parent window. then it populates two child window, some times while i inspect it shows 2 windows some times it shows 3 windows. I have to find a solution to switch on active window and to click the active element using Java.

Thread.sleep(1000);
                System.out.println(driver.getWindowHandles().size());

        for(String WinID : driver.getWindowHandles() ) {
            System.out.println(WinID);
            driver.switchTo().window(WinID);
          driver.findElement(Group.btnmodexit).click();
        }

Body:
not sure why its not working for u, it works fine for me. U getting all opened tabs in array list then jumping to required tab by index, which is u passing to method by property.

    public void switchBetweenTabs(int tabIndex)
{
    ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());

    driver.switchTo().window(tabs.get(tabIndex));
}

Then click on your button.


问:
When is it "acceptable" to use ViewBag/ViewData in ASP.NET MVC?
I realize that the best practice is to use strongly typed Views and pass in all needed data in a ViewModel, but I am curious if there are situations where it is actually considered "best practice" to pass data in the ViewBag/ViewData.

In what scenarios is the ViewBag/ViewData preferred for passing data to a view?

update

It's great to hear the various uses everyone has come up with for ViewBag/ViewData. We may never arrive at a "best practice" but it will be great to see the different solutions people have come up with that rely on the ViewBag/ViewData.

答:
I prefer to use some DTO instead of using viewbag. Using DTO make you strong type your viewdata.

Hope this helps.


问:
How to execute gitlab-ci jobs on specific events
I'm learning gitlab-ci and I'm having a difficult time setting up the .yml file to run a specific job only when a certain trigger token is used or when a branch is merged into master.

I've read through gitlab-ci docs and reviewed several examples. Still, I'm not seeing what I'm looking for.

*Edit: Answering part of my own question, using only: - master should only run the job for merges and pushes to master branch.

```<code>.build_template: &base_defs
  stage: build_base
  <<: *tags_defs
  variables:
    FILE_VER: "3.4"
  script:
    - docker build -t "${DEV_BASE}:latest" "${VERSION}/devel/base"
      --build-arg FILE_VERSION=${FILE_VER}
  only:
    - master
    - ~ WHEN TRIGGER TOKEN MATCHES = K3K3K3K3 ~
</code>```

答:
Maybe you can use

```<code>only:
  variables:
    - token == "..."
</code>```

and make it work with one of the predefined gitlab variables?
Reference: GitLab Docs

Body:
I'm learning gitlab-ci and I'm having a difficult time setting up the .yml file to run a specific job only when a certain trigger token is used or when a branch is merged into master.

I've read through gitlab-ci docs and reviewed several examples. Still, I'm not seeing what I'm looking for.

*Edit: Answering part of my own question, using only: - master should only run the job for merges and pushes to master branch.

.build_template: &base_defs
  stage: build_base
  <<: *tags_defs
  variables:
    FILE_VER: "3.4"
  script:
    - docker build -t "${DEV_BASE}:latest" "${VERSION}/devel/base"
      --build-arg FILE_VERSION=${FILE_VER}
  only:
    - master
    - ~ WHEN TRIGGER TOKEN MATCHES = K3K3K3K3 ~

Body:
Maybe you can use

only:
  variables:
    - token == "..."

and make it work with one of the predefined gitlab variables?
Reference: GitLab Docs


问:
What's the fastest way to check if a username is available with a huge dataset?
I'm looking for the fastest/most efficient way to search if a given username is available from a set of tens of millions of usernames. At the moment I'm using a normal MySQL SELECT query that runs every key press, but I'm not happy with the performance. I'm using indexing, partitioning, etc and I know that MySQL can be optimized to be very fast, but I also know that there are better solutions.

So what's the fastest username search:

Redis EXISTS command

Elasticsearch

Something else

Ex: how does Gmail search across billions of email addresses when registering. How does Facebook do it? I assume they don't just run an SQL query.

I'm looking for a practical solution for a PHP app.

Right now I'm just using a very basic select:

```<code>SELECT username FROM users WHERE username = $username LIMIT 1
</code>```

The username column has a unique index on it

答:
Your example mention companies that use high-end systems. Obviously not any system can do that, and here is why:

Let's assume how a gigantic company address any username among billions:

There is a service, probably written in C, not even C++

It is deployed at a Unix or Linux cluster

There is also another service acts as health checker of the first one that checks every e.g. second a standard username and password

The service loads all data (usually username and password) in memory

When that data changes at its source, it is called to adopt changes, this is triggered from the data source

When a call is needed for data (our case), there are 2(minimum) asynchronous calls to two copies of the health checker (to avoid service-dead delays)that the primary service is alive

When any health checker replies ok, the call to the main service (of the checker) takes place, and verifies or not username and/or password requested.

The caller then continuous according to reply.

Concluding, whatever solution as close as possible to this works fast. A memory 'db' like redis as mentioned above is somewhat close - somewhat means close enough considering the differences. If a colossal company gets a performance of 10 and a simple website gets a performance of 8-9 using similar practices following same principles with costs adjusted to each company size, than i believe is a successful choice to do.

Body:
I'm looking for the fastest/most efficient way to search if a given username is available from a set of tens of millions of usernames. At the moment I'm using a normal MySQL SELECT query that runs every key press, but I'm not happy with the performance. I'm using indexing, partitioning, etc and I know that MySQL can be optimized to be very fast, but I also know that there are better solutions.

So what's the fastest username search:

Redis EXISTS command

Elasticsearch

Something else

Ex: how does Gmail search across billions of email addresses when registering. How does Facebook do it? I assume they don't just run an SQL query.

I'm looking for a practical solution for a PHP app.

Right now I'm just using a very basic select:

SELECT username FROM users WHERE username = $username LIMIT 1

The username column has a unique index on it


问:
VBA, For Each Loop, incrementing offset by 1 column
I have a for each loop, how can I incrementally increase my cells output by one column? Currently this just writes to one cell in output.</p>

```<code>Sub quarterly()

Dim result As String

rev = Sheets("fin").Range("B105:F105")

For Each x In rev:

    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2) = result

Next

End Sub
</code>```

答:
You can use a counter:</p>

```<code>Sub quarterly()

dim j as long
j = 0

dim rev as range
rev = workSheets("fin").Range("B105:F105")

dim x as variant
For Each x In rev
    Dim result As String
    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2+j) = result
    j=j+1
Next

End Sub
</code>```

Body:
I have a for each loop, how can I incrementally increase my cells output by one column? Currently this just writes to one cell in output.

Sub quarterly()

Dim result As String

rev = Sheets("fin").Range("B105:F105")

For Each x In rev:

    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2) = result

Next

End Sub

Body:
You can use a counter:

Sub quarterly()

dim j as long
j = 0

dim rev as range
rev = workSheets("fin").Range("B105:F105")

dim x as variant
For Each x In rev
    Dim result As String
    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2+j) = result
    j=j+1
Next

End Sub


问:
Combine edges when node degree is n in networkx
I have an undirected graph as follows:

```<code>import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)
nx.draw_networkx(G,with_labels=True)
plt.show()
</code>```

I want to combine edges when node satisfies degree=n(like 2). I need remove node 1,2 and 8,and connect 3-6 and 6-9 in my example. So I expect the results to be as follows.

How can I do it? Thanks in advaence

答:
```<code>import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)

# Select all nodes with only 2 neighbors
nodes_to_remove = [n for n in G.nodes if len(list(G.neighbors(n))) == 2]

# For each of those nodes
for node in nodes_to_remove:
    # We add an edge between neighbors (len == 2 so it is correct)
    G.add_edge(*G.neighbors(node))
    # And delete the node
    G.remove_node(node)

nx.draw(G,with_labels=True)
</code>```

Body:
I have an undirected graph as follows:

import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)
nx.draw_networkx(G,with_labels=True)
plt.show()

I want to combine edges when node satisfies degree=n(like 2). I need remove node 1,2 and 8,and connect 3-6 and 6-9 in my example. So I expect the results to be as follows.

How can I do it? Thanks in advaence


问:
How to program loop with two different variables
Imagine you want to add the sum of 2 dice so the output looks like this in 6 lines:

```<code>2 3 4 5 6 7 3 4 5 6 7 8 9 4 5 6 7 8 9 10 11 5 6 ... 7 8... 8 9...
</code>```

By only programming a single loop ?

I tried to do it with nested loops but could figure out the logic for it.

答:
You can do with one while loop and two variables for two dices.

```<code><?php
$x = 1;
$y = 1;

while ( $x <= 6 ) {
    echo $x + $y;

    $y++;

    if ( $y > 6 ) {
        $y = 1;
        $x++;
    }
}
</code>```

It's essentially a mechanical counter. When the first wheel completes a rotation, it resets, and advances the second wheel. Except in this case they are dice. When $y is greater than six, it resets and advances $x.

You would use similar code when dealing with dates, advancing months when the days tick over etc.

The code would be simpler using two loops.

```<code>for ( $x = 1; $x <= 6; $x++ ) {
    for ( $y = 1; $y <= 6; $y++ ) {
        echo $x + $y;
    }
}
</code>```

As this was not allowed, the while loop is the 'first wheel' and the if statement determines when to reset and advance the second.

https://www.hackerrank.com/ is good if you want to practice solving coding problems

Body:
Imagine you want to add the sum of 2 dice so the output looks like this in 6 lines:

2 3 4 5 6 7 3 4 5 6 7 8 9 4 5 6 7 8 9 10 11 5 6 ... 7 8... 8 9...

By only programming a single loop ?

I tried to do it with nested loops but could figure out the logic for it.

Body:
You can do with one while loop and two variables for two dices.

<?php
$x = 1;
$y = 1;

while ( $x <= 6 ) {
    echo $x + $y;

    $y++;

    if ( $y > 6 ) {
        $y = 1;
        $x++;
    }
}

It's essentially a mechanical counter. When the first wheel completes a rotation, it resets, and advances the second wheel. Except in this case they are dice. When $y is greater than six, it resets and advances $x.

You would use similar code when dealing with dates, advancing months when the days tick over etc.

The code would be simpler using two loops.

for ( $x = 1; $x <= 6; $x++ ) {
    for ( $y = 1; $y <= 6; $y++ ) {
        echo $x + $y;
    }
}

As this was not allowed, the while loop is the 'first wheel' and the if statement determines when to reset and advance the second.

https://www.hackerrank.com/ is good if you want to practice solving coding problems


问:
Insert multiple records in Sqflite
How to insert quickly multiple records in sqflite? The standard quickly method is:

```<code>await database.insert(table, object.toMap())
</code>```

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

答:
If you have a list of objects you want to insert, you can do it like this (it's not a very clean code, but it works):

  insertClients(List<Client> clients) async {
    final db = await database;
    var buffer = new StringBuffer();
    clients.forEach((c) {
      if (buffer.isNotEmpty) {
        buffer.write(",\n");
      }
      buffer.write("('");
      buffer.write(c.firstName);
      buffer.write("', '");
      buffer.write(c.lastName);
      buffer.write("', '");
      buffer.write(c.address);
      buffer.write("')");
    });
    var raw =
        await db.rawInsert("INSERT Into Clients (firstName,lastName,address)"
            " VALUES ${buffer.toString()}");
    return raw;
  }
```

<p>I'm using this statement from SQLite:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO 'tablename' ('column1', 'column2') VALUES
                ('data1', 'data2'),
                ('data1', 'data2'),
                ('data1', 'data2');
</code>```

Title: Insert multiple records in Sqflite

Body:
How to insert quickly multiple records in sqflite? The standard quickly method is:

await database.insert(table, object.toMap())

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

Body:
If you have a list of objects you want to insert, you can do it like this (it's not a very clean code, but it works):

  insertClients(List<Client> clients) async {
    final db = await database;
    var buffer = new StringBuffer();
    clients.forEach((c) {
      if (buffer.isNotEmpty) {
        buffer.write(",\n");
      }
      buffer.write("('");
      buffer.write(c.firstName);
      buffer.write("', '");
      buffer.write(c.lastName);
      buffer.write("', '");
      buffer.write(c.address);
      buffer.write("')");
    });
    var raw =
        await db.rawInsert("INSERT Into Clients (firstName,lastName,address)"
            " VALUES ${buffer.toString()}");
    return raw;
  }

I'm using this statement from SQLite:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
                ('data1', 'data2'),
                ('data1', 'data2'),
                ('data1', 'data2');


问:
How to append multiple Paths to PYTHONPATH programmatically
I have 4 directories:

```<code>/home/user/test1
/home/user/test2
/home/user/test3
/home/user/test4
</code>```

I have another directory with tests

```<code>/home/user/testing
</code>```

having the file testall.py

ow, how can I append PATHS, for test1 thru test4 to PYTHONPATH so that I can access the files under test1 thru 4.

btw, test1 thru 4 have multiple directories under them where the python files are located.

I tried:

```<code>import sys
import os
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0,os.path.join(PROJECT_ROOT,"test1"))
sys.path.insert(1,os.path.join(PROJECT_ROOT,"test2"))
sys.path.insert(2,os.path.join(PROJECT_ROOT,"test3"))
sys.path.insert(3,os.path.join(PROJECT_ROOT,"test4"))
</code>```

did not seem to work

also:

```<code>import sys
sys.path.append('/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4')
from test1.common.api import GenericAPI
</code>```

did not work.

basically:
from test1.common.api import GenericAPI
should work

答:
sys.path.append('/home/user/test1','/home/user/test2', ...) does not work because append() function can take only 1 argument.

What you could use instead is:

```<code>import sys
sys.path += ['/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4']
</code>```

Body:
I have 4 directories:

/home/user/test1
/home/user/test2
/home/user/test3
/home/user/test4

I have another directory with tests

/home/user/testing

having the file testall.py

ow, how can I append PATHS, for test1 thru test4 to PYTHONPATH so that I can access the files under test1 thru 4.

btw, test1 thru 4 have multiple directories under them where the python files are located.

I tried:

import sys
import os
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0,os.path.join(PROJECT_ROOT,"test1"))
sys.path.insert(1,os.path.join(PROJECT_ROOT,"test2"))
sys.path.insert(2,os.path.join(PROJECT_ROOT,"test3"))
sys.path.insert(3,os.path.join(PROJECT_ROOT,"test4"))

did not seem to work

also:

import sys
sys.path.append('/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4')
from test1.common.api import GenericAPI

did not work.

basically:
from test1.common.api import GenericAPI
should work

Body:
sys.path.append('/home/user/test1','/home/user/test2', ...) does not work because append() function can take only 1 argument.

What you could use instead is:

import sys
sys.path += ['/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4']


问:
Making buttons link - Adobe flex - Blackberry Playbook
Maybe a simple question but I'm having alot of trouble making a button change the view of a Flex blackberry playbook app. I am coding it entirely in actionscript, no MXML.

```<code>myButton.addEventListener(MouseEvent.CLICK, doSomethingOnClick);

private function doSomethingOnClick(e:MouseEvent):void {
    navigator.pushView(view.Login, "testdata");
}
</code>```

When I try this I get:

1120: Access of undefined property navigator.

Which is weird as it works in a MXML file. How do I change views in actionscript?

Thanks
Phil

EDIT:
Cheer J_A_X, but now i have:

```<code>navigator = new ViewNavigator();
navigator.pushView(net.airpoint.assessments.view.Login, " ");
</code>```

TypeError: Error #1009: Cannot access a property or method of a null object reference.

Apologies, as I realise this is really simple stuff but it just isnt clicking!

Update 2
*Assessments.as*

```<code>package
{
    import flash.display.Sprite;
    import flash.events.Event;

    import net.airpoint.assessments.view.*;

    import qnx.ui.core.Container;
    import qnx.ui.core.ContainerAlign;
    import qnx.ui.core.ContainerFlow;
    import qnx.ui.core.Containment;
    import qnx.ui.text.Label;

    import spark.components.ViewNavigator;

    [SWF(height="600", width="1024", frameRate="30", backgroundColor="#FFFFFF")]

    /* Main Layout */

    public class Assessments extends Sprite
    {
        //containers
        private var main:Container;
        private var menu:Container
        private var firstLabel:Label;
        private var navigator:ViewNavigator;

        public function Assessments()
        {
            initializeUI();
        }

        private function initializeUI():void
        {
            main = new Container();
            main.padding = Vector.<Number>([20,20,20,20]);
            main.flow = ContainerFlow.HORIZONTAL;
            main.debugColor = 0xFFCC00;

            firstLabel = new Label();
            firstLabel.text = "First label";
            firstLabel.size=35;

            main.addChild(firstLabel);

            addChild(main);

            navigator = new ViewNavigator();
            navigator.pushView(Login, " ");

        }
    }
}
</code>```

Login.as

```<code>package net.airpoint.assessments.view
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    import qnx.ui.buttons.Button;
    import qnx.ui.core.Container;
    import qnx.ui.text.Label;
    import qnx.ui.text.TextInput;

    import spark.components.View;

    public class Login extends View
    {

        private var usernameLabel:Label;
        public function Login()
        {
            initializeUI();
        }

        public function initializeUI():void
        {
            usernameLabel.text = "test";

            this.addChild(usernameLabel);
        }
    }
}
</code>```

答:
Something isn't right.  If it's a Flex Mobile Project, you need an Application at the top level (you know, like how Flash Builder created the project with an mxml file).  Either you create an actionscript file that extends Application as mentioned here or you just use an mxml file for the root component.

However, your argument to 'not use mxml' is redundant if you're using Flex components.  If you're using Flex components, you're using mxml no matter what, so there's no performance increase.  If anything, RIM is recommending to use AS only because their SDK is AS only (which is idiotic anyways).  You could always add their UI component through AS in mxml files.

So really, the point is moot and you should just use mxml anyways since it's better than straight AS for UI layout and skinning.  Either that or go Pure AS with no Flex components.

Body:
Maybe a simple question but I'm having alot of trouble making a button change the view of a Flex blackberry playbook app. I am coding it entirely in actionscript, no MXML.

myButton.addEventListener(MouseEvent.CLICK, doSomethingOnClick);

private function doSomethingOnClick(e:MouseEvent):void {
    navigator.pushView(view.Login, "testdata");
}

When I try this I get:

1120: Access of undefined property navigator.

Which is weird as it works in a MXML file. How do I change views in actionscript?

Thanks
Phil

EDIT:
Cheer J_A_X, but now i have:

navigator = new ViewNavigator();
navigator.pushView(net.airpoint.assessments.view.Login, " ");

TypeError: Error #1009: Cannot access a property or method of a null object reference.

Apologies, as I realise this is really simple stuff but it just isnt clicking!

Update 2
*Assessments.as*

package
{
    import flash.display.Sprite;
    import flash.events.Event;

    import net.airpoint.assessments.view.*;

    import qnx.ui.core.Container;
    import qnx.ui.core.ContainerAlign;
    import qnx.ui.core.ContainerFlow;
    import qnx.ui.core.Containment;
    import qnx.ui.text.Label;

    import spark.components.ViewNavigator;

    [SWF(height="600", width="1024", frameRate="30", backgroundColor="#FFFFFF")]

    /* Main Layout */

    public class Assessments extends Sprite
    {
        //containers
        private var main:Container;
        private var menu:Container
        private var firstLabel:Label;
        private var navigator:ViewNavigator;

        public function Assessments()
        {
            initializeUI();
        }

        private function initializeUI():void
        {
            main = new Container();
            main.padding = Vector.<Number>([20,20,20,20]);
            main.flow = ContainerFlow.HORIZONTAL;
            main.debugColor = 0xFFCC00;

            firstLabel = new Label();
            firstLabel.text = "First label";
            firstLabel.size=35;

            main.addChild(firstLabel);

            addChild(main);

            navigator = new ViewNavigator();
            navigator.pushView(Login, " ");

        }
    }
}

Login.as

package net.airpoint.assessments.view
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    import qnx.ui.buttons.Button;
    import qnx.ui.core.Container;
    import qnx.ui.text.Label;
    import qnx.ui.text.TextInput;

    import spark.components.View;

    public class Login extends View
    {

        private var usernameLabel:Label;
        public function Login()
        {
            initializeUI();
        }

        public function initializeUI():void
        {
            usernameLabel.text = "test";

            this.addChild(usernameLabel);
        }
    }
}


问:
RDD String to Spark csv Reader
I want to read the RDD[String] using the spark CSV reader. The reason I am doing this is, I need to filter some records before using the CSV reader.

```<code>val fileRDD: RDD[String] = spark.sparkContext.textFile("file")
</code>```

I need to read the fileRDD using the spark CSV reader. I wish not to commit the file as it increases the IO of the HDFS. I have looked into the options we have in the spark CSV, but didn't found any.

```<code>spark.read.csv(file)
</code>```

Sample Data

```<code>PHM|MERC|PHARMA|BLUEDRUG|50
CLM|BSH|CLAIM|VISIT|HSA|EMPLOYER|PAID|250
PHM|GSK|PHARMA|PARAC|70
CLM|UHC|CLAIM|VISIT|HSA|PERSONAL|PAID|72
</code>```

As you can see all the records starts with PHM has different number of columns and clm has different number of columns. That is the reason i am filtering and then applying schema. PHM and CLM records has different schema.

```<code>val fileRDD: RDD[String] = spark.sparkContext.textFile("file").filter(_.startWith("PHM"))

 spark.read.option(schema,"phcschema").csv(fileRDD.toDS())
</code>```

答:
Since Spark 2.2, method ".csv" can read dataset of strings. Can be implemented in this way:</p>

```<code>val rdd: RDD[String] = spark.sparkContext.textFile("csv.txt")
// ... do filtering
spark.read.csv(rdd.toDS())
</code>```

Title: RDD String to Spark csv Reader

Body:
I want to read the RDD[String] using the spark CSV reader. The reason I am doing this is, I need to filter some records before using the CSV reader.

val fileRDD: RDD[String] = spark.sparkContext.textFile("file")

I need to read the fileRDD using the spark CSV reader. I wish not to commit the file as it increases the IO of the HDFS. I have looked into the options we have in the spark CSV, but didn't found any.

spark.read.csv(file)

Sample Data

PHM|MERC|PHARMA|BLUEDRUG|50
CLM|BSH|CLAIM|VISIT|HSA|EMPLOYER|PAID|250
PHM|GSK|PHARMA|PARAC|70
CLM|UHC|CLAIM|VISIT|HSA|PERSONAL|PAID|72

As you can see all the records starts with PHM has different number of columns and clm has different number of columns. That is the reason i am filtering and then applying schema. PHM and CLM records has different schema.

val fileRDD: RDD[String] = spark.sparkContext.textFile("file").filter(_.startWith("PHM"))

 spark.read.option(schema,"phcschema").csv(fileRDD.toDS())

Body:
Since Spark 2.2, method ".csv" can read dataset of strings. Can be implemented in this way:

val rdd: RDD[String] = spark.sparkContext.textFile("csv.txt")
// ... do filtering
spark.read.csv(rdd.toDS())


问:
Get JSON to HTML JavaScript table
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

```<code>{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}
</code>```

Table like this:

```<code>| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....
</code>```

答:
Something along the lines of this?

This will generate html markup based on the JSON data. Then write it to the document.

var data = {
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  }
};

let htmlStr = "

Name	Count	Time	Language
";
const keys = Object.keys(data);
for (var key of keys) {
  let item = data[key];
  htmlStr += `<tr><td>${key}</td><td>${item.count}</td><td>${item.created}</td><td>${item.lang}</td></tr>`;
}
htmlStr += "
";
document.write(htmlStr);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
 border-collapse: collapse;
}

td {
 border: 1px solid black;
}</code>```

Title: Get JSON to HTML JavaScript table

Body:
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}

Table like this:

| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....

Body:
Something along the lines of this?

This will generate html markup based on the JSON data. Then write it to the document.

var data = {
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
  }
};

let htmlStr = "<table><tr><td>Name</td><td>Count</td><td>Time</td><td>Language</td></tr>";
const keys = Object.keys(data);
for (var key of keys) {
  let item = data[key];
  htmlStr += `<tr><td>${key}</td><td>${item.count}</td><td>${item.created}</td><td>${item.lang}</td></tr>`;
}
htmlStr += "</table>";
document.write(htmlStr);

table {
 border-collapse: collapse;
}

td {
 border: 1px solid black;
}


问:
unable to create Inbound shipment
unable to do inbound shipment</p>

```<code>{
   type: "error.SuiteScriptError",
   name: "SSS_INVALID_SUBLIST_OPERATION",
   message: "You have attempted an invalid sublist or line item operation. You are either trying to access a field on a non-existent line or you are trying to add or remove lines from a static sublist.",
   stack: [
      "anonymous(N/serverRecordService)",
      "inboundResults(/SuiteScripts/inboundResults.js:40)"
   ],
   cause: {
      type: "internal error",
      code: "SSS_INVALID_SUBLIST_OPERATION",
      details: "You have attempted an invalid sublist or line item operation. You are either trying to access a field on a non-existent line or you are trying to add or remove lines from a static sublist.",
      userEvent: null,
      stackTrace: [
         "anonymous(N/serverRecordService)",
         "inboundResults(/SuiteScripts/inboundResults.js:40)"
      ],
      notifyOff: false
   },
   id: "",
   notifyOff: false,
   userFacing: false
}

 var objRecord1 = record.load({
    type:"receiveinboundshipment",
    id: 2,
     isDynamic:true
});

var receiveItemCount=objRecord1.getLineCount('receiveitems');

var lineNum = objRecord1.selectLine({
    sublistId: 'receiveitems',
    line: 2
});

objRecord1.setCurrentSublistValue({
    sublistId: 'receiveitems',
    fieldId: 'receiveitem',
    value:  true,
    ignoreFieldChange: true
});

objRecord1.setCurrentSublistValue({
    sublistId: 'receiveitems',
    fieldId: 'quantitytobereceived',
    value:  1,
    ignoreFieldChange: true
});

objRecord1.commitLine({
    sublistId: 'item'
});

var recordId3 = objRecord1.save({
    enableSourcing: true,
    ignoreMandatoryFields: true
});
</code>```

答:
The record receiveinboundshipment it's accesible from the script and the fields receiveitem and quantitytobereceived are correct.

The only thing which is not correct is that you are doing commit on a sublist item instead of receiveitems.

```<code>objRecord1.commitLine({
    sublistId: 'receiveitems'
});
</code>```

You should replace the sublist 'item' for 'receiveitems' and it should work.

Good luck,

Title: unable to create Inbound shipment

Body:
unable to do inbound shipment

{
   type: "error.SuiteScriptError",
   name: "SSS_INVALID_SUBLIST_OPERATION",
   message: "You have attempted an invalid sublist or line item operation. You are either trying to access a field on a non-existent line or you are trying to add or remove lines from a static sublist.",
   stack: [
      "anonymous(N/serverRecordService)",
      "inboundResults(/SuiteScripts/inboundResults.js:40)"
   ],
   cause: {
      type: "internal error",
      code: "SSS_INVALID_SUBLIST_OPERATION",
      details: "You have attempted an invalid sublist or line item operation. You are either trying to access a field on a non-existent line or you are trying to add or remove lines from a static sublist.",
      userEvent: null,
      stackTrace: [
         "anonymous(N/serverRecordService)",
         "inboundResults(/SuiteScripts/inboundResults.js:40)"
      ],
      notifyOff: false
   },
   id: "",
   notifyOff: false,
   userFacing: false
}

 var objRecord1 = record.load({
    type:"receiveinboundshipment",
    id: 2,
     isDynamic:true
});

var receiveItemCount=objRecord1.getLineCount('receiveitems');

var lineNum = objRecord1.selectLine({
    sublistId: 'receiveitems',
    line: 2
});

objRecord1.setCurrentSublistValue({
    sublistId: 'receiveitems',
    fieldId: 'receiveitem',
    value:  true,
    ignoreFieldChange: true
});

objRecord1.setCurrentSublistValue({
    sublistId: 'receiveitems',
    fieldId: 'quantitytobereceived',
    value:  1,
    ignoreFieldChange: true
});

objRecord1.commitLine({
    sublistId: 'item'
});

var recordId3 = objRecord1.save({
    enableSourcing: true,
    ignoreMandatoryFields: true
});

Body:
The record receiveinboundshipment it's accesible from the script and the fields receiveitem and quantitytobereceived are correct.

The only thing which is not correct is that you are doing commit on a sublist item instead of receiveitems.

objRecord1.commitLine({
    sublistId: 'receiveitems'
});

You should replace the sublist 'item' for 'receiveitems' and it should work.

Good luck,


问:
How to autowire field in static @BeforeClass?
```<code>@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
    @Autowired
    private EntityRepository dao;

    @BeforeClass
    public static void init() {
        dao.save(initialEntity); //not possible as field is not static
    }
}
</code>```

How can I have my service injected already in the static init class?

答:
UPD for Spring 2.x versions.

Spring 2.x supports new feature a SpringExtension for Junit 5 Jupiter, where all you have to do is:

Declare your test class with @ExtendWith(SpringExtension.class)

Inject your @BeforeAll (replacement for @BeforeClass in JUnit 5) with the bean

For example:

```<code>@ExtendWith(SpringExtension.class)
...
public void ITest {

    @BeforeAll
    public static void init(@Autowired EntityRepository dao) {
        dao.save(initialEntity);
    }

}
</code>```

Assuming you correctly configured JUnit 5 Jupiter with Spring 2.x

More about it here: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-extension

Body:
@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
    @Autowired
    private EntityRepository dao;

    @BeforeClass
    public static void init() {
        dao.save(initialEntity); //not possible as field is not static
    }
}

How can I have my service injected already in the static init class?

Body:
UPD for Spring 2.x versions.

Spring 2.x supports new feature a SpringExtension for Junit 5 Jupiter, where all you have to do is:

Declare your test class with @ExtendWith(SpringExtension.class)

Inject your @BeforeAll (replacement for @BeforeClass in JUnit 5) with the bean

For example:

@ExtendWith(SpringExtension.class)
...
public void ITest {

    @BeforeAll
    public static void init(@Autowired EntityRepository dao) {
        dao.save(initialEntity);
    }

}

Assuming you correctly configured JUnit 5 Jupiter with Spring 2.x

More about it here: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-extension