text:
Q: Sending user defined class gives InvalidDefinitionException: No serializer found for class... and no properties discovered I have a map, Map<String, Object> map = new HashMap<>();
I am storing multiple types of data in this map. 1.) Primitive types 2.) User-defined class's object as a value in this map. When I am casting any primitive type value as Object and store in Map, its working fine but not in case of user-defined. While storing user-defined types data in this map, I am getting below error:-
**ERROR [WebExceptionHandler] Error occurred while serving request. Response is as [Response(

description=Type definition error: [simple type, class com.yyz.util.Abc];
nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
  No serializer found for class com.yyz.util.Abc
  and no properties discovered to create BeanSerializer
  (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

 (through reference chain: com.xyz.api.web.model.BuResponse["rows"]->java.util.ArrayList[0]->com.xyz.api.web.model.BuRow["children"]->java.util.ArrayList[11]->com.com.xyz.api.web.model.BuRow["[anySetter]"]->java.util.HashMap["column6"]), executionTime=0, responseEntity=<204 No Content,{}>,** responseStatus=ResponseStatus(hasError=true, responseKey=process-exception))]
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.yyz.util.Abc]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.yyz.util.Abc and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.xyz.api.web.model.BuResponse["rows"]->java.util.ArrayList[0]->com.com.xyz.api.web.model.BuRow["children"]->java.util.ArrayList[11]->com.com.xyz.api.web.model.BuRow["[anySetter]"]->java.util.HashMap["column6"])
      at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:265) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:182) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar!/:1.0.0.Final]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar!/:1.0.0.Final]
      at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at com.blackrock.myworld.common.security.xss.XssFilter.doFilter(XssFilter.java:83) [myworld-common-2.9-SNAPSHOT.jar:2.9-SNAPSHOT]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at com.blackrock.myworld.common.security.SecurityFilter.doFilter(SecurityFilter.java:73) [myworld-common-2.9-SNAPSHOT.jar:2.9-SNAPSHOT]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at com.blackrock.myworld.api.framework.filter.ImitateLoginInInternalFilter.doFilter(ImitateLoginInInternalFilter.java:66) [classes:?]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at com.blackrock.myworld.api.framework.filter.SimpleUserContextFilter.doFilter(SimpleUserContextFilter.java:42) [classes:?]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at com.blackrock.myworld.common.framework.filter.UserContextFilter.doFilter(UserContextFilter.java:74) [myworld-common-2.9-SNAPSHOT.jar:2.9-SNAPSHOT]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) [wildfly-undertow-8.2.0.Final.jar!/:8.2.0.Final]
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) [wildfly-undertow-8.2.0.Final.jar!/:8.2.0.Final]
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar!/:1.1.0.Final]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_20]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_20]
      at java.lang.Thread.run(Thread.java:745) [?:1.8.0_20]
**Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
No serializer found for class com.yyz.util.Abc and no properties discovered
to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
(through reference chain: com.xyz.api.web.model.BuResponse["rows"]->java.util.ArrayList[0]->com.com.xyz.api.web.model.BuRow["children"]->java.util.ArrayList[11]->com.com.xyz.api.web.model.BuRow["[anySetter]"]->java.util.HashMap["column6"])**
      at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:312) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:718) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.AnyGetterWriter.getAndSerialize(AnyGetterWriter.java:62) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:723) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1396) ~[jackson-databind-2.9.2.jar:2.9.2]
      at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:913) ~[jackson-databind-2.9.2.jar:2.9.2]
      at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:286) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
      ... 68 more

Can anyone explain why I am getting this error and what is the solution?
@Setter
@Getter
@ToString
@JsonPropertyOrder({ "numRecordsFound", "rowViewCount", "buyingUnitRows" })
public class BuResponse extends Response implements Serializable {

    private static final long serialVersionUID = -5269171275831114276L;

    private final List<BuRow> buRows = new ArrayList<>();

    private long numRecordsFound;

    private long rowViewCount;
}

@Getter
@Setter
@ToString
@EqualsAndHashCode(callSuper = false)
@JsonPropertyOrder({ "properties", "children", "positionData" })
public class BuRow extends TreeRow {

    private static final long serialVersionUID = -9087386484833636274L;

    private List<BuRow> children;

    private Map<String, Object> positionData = new HashMap<>();

    private Map<String, Object> properties;

    public Map<String, Object> getPositionData() {
        return positionData;
    }

    @JsonAnyGetter
    public Map<String, Object> getProperties() {
        return properties;
    }
}

Thanks in advance!

A: Make your field(s) / getter(s) -- public
The exception says your Abc class is an empty bean and SerializationFeature.FAIL_ON_EMPTY_BEANS is enabled (by default). For example, this class would be an empty bean for jackson serializer:
    public class Abc {
      boolean boo;
    }

If you had at least one public field, or a public getter, that would avoid the exception:
    public class Abc {
      public boolean boo;
    }

A: As you did not attach com.yyz.util.Abc class so can not tell the exact reason but ensure that all the getters and setters are present.
Refer this for more :
Serializing with Jackson (JSON) - getting "No serializer found"?


text:
Q: Loading XHR response data to index HTML page I have a .NET api endpoint that returns anonymous data and client side received these either through Promise like this:
function getDataByPromise(method, url) {
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.send();
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText,
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText,
      });
    };
  });
}

or through Callback like this:
function getDataByCallback(method, url, done) {
  let xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.send();
  xhr.onload = function () {
    done(null, xhr.response);
  };
  xhr.onerror = function () {
    done(xhr.response);
  };

or through Async/Await
async function getDataByAsyncAwait() {
  try {
    console.log("By Async Await");
    await getDataByPromise(method, url);
  } catch (error) {
    console.log(error);
  }
}

or through normal XHR like this:
function getDataByXHR(method, url) {
  let xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.onload = function () {
    console.log("By XHR: ");
    console.log(xhr.response);
    let gameSettings = JSON.parse(xhr.response);
    this.data = gameSettings;
    waitAsyncAwait(this.data);
    waitPromise(this.data);
  };
  xhr.onerror = function () {
    console.error("An error occur getting the XMLHttpRequest");
  };
  xhr.send();
}

How can I display these JSON object in the html file either by pushing a button or to a table?
Should I load a function into a button like this?
<button onclick="">Get Data By Normal XHR</button>

If that is the case then should I save the response of the XHR request into an array or const or variable of some sort and display them?
Or is there any other approach I should take to display the XHR response on the HTML dom?

A: here is an example:
var url = "https://sourceforge.net/projects/kaais/files/stats/json?start_date=2013-08-18&end_date=2018-04-19";

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    document.getElementById('output').innerHTML = JSON.parse(xmlHttp.responseText).total;
}
xmlHttp.open("GET", url, true);
xmlHttp.send();

Html:

NO DATA

redpajama_set_name: RedPajamaStackExchange


text:
Q: useState keeps the previous state In my app I click Play button and audio should start playing, when it's over speech recognition should start listening, when it's over the message should be printed in console (it will be change to some other actions further).
My app also has a feature to stop recognition process if I click stop button, for that I use useState where false state changes to true.
But, I face an issue: when I try to stop listening by clicking Stop button, the state changes to true and it should stop here, but despite that I have if(isPlaying === false) condition, after true I get false in console as last action ♂ Why it happens so, and how to fix it?
const [song] = useState(typeof Audio !== 'undefined' && new Audio())
  const [isPlaying, setIsPlaying] = useState(false)

  function playSong() {
    setIsPlaying(!isPlaying)
    if (listening) {
      SpeechRecognition.stopListening()
    }
    if (isPlaying === false) {
      song.src = 'https://raw.songToPlay.mp3'
      song.play()
      console.log('Song is playing: ' + isPlaying)
      song.addEventListener('ended', () => {
        console.log('Recognition is started: ' + isPlaying)
        SpeechRecognition.startListening()
      })
      recognition.addEventListener('audioend', () => {
        console.log('Recognition is finished: ' + isPlaying)
      })
    } else {
      console.log('When stop is clicked: ' + isPlaying)
    }
  }

  return (

Microphone: {listening ? 'on' : 'off'}

      <button onClick={playSong}>{isPlaying ? 'Stop' : 'Play'}</button>

{transcript}

  )

Output:

A: Logging the state from within playSong will log the state when the function was defined. This means that the value will be outdated, i.e. stale. This is because of a functional concept called closures. From Wikipedia "Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope."
So how should we log the current state when it is changed? By using the useEffect hook. This function will be re-run whenever any of the dependencies change.
You can also return a 'cleanup' function to remove listeners, etc.
CodeSandbox
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    if (!isPlaying) {
      console.log("Starting to play");
      // add your event listener here to wait for song to end and start speech recognition
    } else {
      console.log("When stop is clicked: " + isPlaying);
      // stop your speech recognition here
    }

    return () => {
      // this is a cleanup function - you can use it to remove event listeners so you don't add them twice
    };
  }, [isPlaying]);

  return (

      <button onClick={() => setIsPlaying(!isPlaying)}>
        {isPlaying ? "Stop" : "Play"}
      </button>

  );


text:
Q: Wordpress Rest Api categories serialization in kotlin data class I have project with android app that fetch post from wordpress rest api
some field that i take is like this list.
[
  {
    "id": 43600,
    "date": "2020-09-07T19:52:47",
    "title": {
      "rendered": "Video: .... "
    },
    "content": {
      "rendered": "

",
      "protected": false
    },
    "author": 31,
    "featured_media": 43601,
    "categories": [
      788,
      2760
    ]
  }
]

Already read :
https://developer.android.com/training/data-storage/room
How to parse data of WordPress REST API using Retrofit and GSON?
Wordpress API - How to loop through a JSON Array of objects in Android/Java
Android Kotlin parsing nested JSON
Parse Json to Primative Array Kotlin
the closest answer but mostly in converter
Android Room Database: How to handle Arraylist in an Entity?
https://medium.com/@gilesjeremydev/room-through-a-complete-example-ce5c9ed417ba
I tried to save it into local storage with room in single entity. But based on google doc, it would seperate into 2 entities tied with annotation @relation
@Entity(tableName = "post")
data class SomePost(

    @PrimaryKey
    @field:SerializedName("id")
    val id: Int,
    @field:SerializedName("date")
    val date: String,
    @Embedded
    @field:SerializedName("title")
    val title: PostTitle,
    @Embedded
    @field:SerializedName("content")
    val content: PostContent,

    @field:SerializedName("featured_media")
    val imageId: Int,
    @field:SerializedName("author")
    val author: Int

)

@Entity
data class PostCategories(

    @PrimaryKey(autoGenerate = true)
    val id: Int,
    @field:SerializedName("categories")
    val postCategories: Int

)

data class SomePostRelationship (
    @Embedded
    var post: SomePost? = null,

    @Relation(
        parentColumn = "id",
        entityColumn = "categories"
    )
    var categories: List<PostCategories>? = null
)

interface PostService {

    companion object {
        const val ENDPOINT = "https://example.com/wp-json/"
    }

    // Posts
    @GET("wp/v2/posts/")
    suspend fun getPostAll(
        @Query("page") page: Int? = null,
        @Query("per_page") perPage: Int? = null,
        @Query("search") search: String? = null,
        @Query("order") order: String? = null
    ): Response<List<somePost>>

The problem is data class PostCategories.
My question is how to serialization json array into entity data class of categories for android room.
if there already answer or same question hope can link to it.

A: After tried some variation.
I decided to used converter and combine it in on dataclass for now.
@Entity(tableName = "post")
data class SomePost(

...

    @field:SerializedName("categories")
    var categories: ArrayList<Int>? = null,
...
)

class Converters {

...
    @TypeConverter
    fun listToInt(value: ArrayList<Int>?): String? {
        return Gson().toJson(value)
    }

    @TypeConverter
    fun intToList(value: String?): ArrayList<Int>? {
        val type = object : TypeToken<ArrayList<Int>?>() {}.type
        return Gson().fromJson(value, type)
    }

}


text:
Q: type 'List' is not a subtype of type 'Map' getting this error in flutter app I am trying to load data from my strapi database list that is: http://localhost:1337/products
Below is one sample data from my database:

[{"picture":[{"_id":"602d327fe790253a44f466e7","name":"petromax.png","alternativeText":"","caption":"","hash":"petromax_14618add72","ext":".png","mime":"image/png","size":73.87,"width":444,"height":512,"url":"/uploads/petromax_14618add72.png","formats":{"thumbnail":{"name":"thumbnail_petromax.png","hash":"thumbnail_petromax_14618add72","ext":".png","mime":"image/png","width":135,"height":156,"size":30.2,"path":null,"url":"/uploads/thumbnail_petromax_14618add72.png"},"small":{"name":"small_petromax.png","hash":"small_petromax_14618add72","ext":".png","mime":"image/png","width":434,"height":500,"size":205.37,"path":null,"url":"/uploads/small_petromax_14618add72.png"}},"provider":"local","related":["602d3287e790253a44f466e8"],"createdAt":"2021-02-17T15:13:03.648Z","updatedAt":"2021-02-17T15:13:11.831Z","__v":0,"created_by":"60278359e1626337e009d550","updated_by":"60278359e1626337e009d550","id":"602d327fe790253a44f466e7"}],"_id":"602d3287e790253a44f466e8","name":"PetroMax LPG","description":"12 KG-22 mm || 35 KG-22 mm","Refill":800,"Cylinder":780,"createdAt":"2021-02-17T15:13:11.285Z","updatedAt":"2021-02-21T15:35:58.368Z","__v":0,"created_by":{"_id":"60278359e1626337e009d550","username":null,"firstname":"DokanDar","lastname":"eComm","createdAt":"2021-02-13T07:44:25.817Z","updatedAt":"2021-02-13T07:44:26.352Z","__v":0,"id":"60278359e1626337e009d550"},"updated_by":{"_id":"60278359e1626337e009d550","username":null,"firstname":"DokanDar","lastname":"eComm","createdAt":"2021-02-13T07:44:25.817Z","updatedAt":"2021-02-13T07:44:26.352Z","__v":0,"id":"60278359e1626337e009d550"},"Price":850,"id":"602d3287e790253a44f466e8"},

I want to show each of the products in this product_item.dart page:
import 'package:flutter/material.dart';
import 'package:flutter_ecommerce/models/app_state.dart';
import 'package:flutter_ecommerce/models/product.dart';
import 'package:flutter_redux/flutter_redux.dart';

class ProductItem extends StatelessWidget {
  final Product item;
  ProductItem({this.item});

  @override
  Widget build(BuildContext context) {
    final String pictureUrl = 'http://localhost:1337${item.picture['url']}';
    return GridTile(
        footer: GridTileBar(
            title: FittedBox(
                fit: BoxFit.scaleDown,
                alignment: Alignment.centerLeft,
                child: Text(item.name, style: TextStyle(fontSize: 20.0))),
            subtitle: Text("\$${item.price}", style: TextStyle(fontSize: 16.0)),
            backgroundColor: Color(0xBB000000),
            trailing: StoreConnector<AppState, AppState>(
                converter: (store) => store.state,
                builder: (_, state) {
                  return state.user != null
                      ? IconButton(
                          icon: Icon(Icons.shopping_cart),
                          color: Colors.white,
                          onPressed: () => print('pressed'))
                      : Text('');
                })),
        child: Image.network(pictureUrl, fit: BoxFit.cover));
  }
}

After starting the app am getting following error:

E/flutter (25288): [ERROR:flutter/lib/ui/ui_dart_state.cc(184)] Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
E/flutter (25288): #0      new Product.fromJson (package:flutter_ecommerce/models/product.dart:23:22)
E/flutter (25288): #1      getProductsAction.. (package:flutter_ecommerce/redux/actions.dart:33:37)
E/flutter (25288): #2      List.forEach (dart:core-patch/growable_array.dart:403:8)
E/flutter (25288): #3      getProductsAction. (package:flutter_ecommerce/redux/actions.dart:32:16)

These are product actions from actions.dart file:
ThunkAction<AppState> getProductsAction = (Store<AppState> store) async {
  http.Response response = await http.get('http://localhost:1337/products');
  final List<dynamic> responseData = json.decode(response.body);
  List<Product> products = [];
  responseData.forEach((productData) {
    final Product product = Product.fromJson(productData);
    products.add(product);
  });
  store.dispatch(GetProductsAction(products));
};

class GetProductsAction {
  final List<Product> _products;

  List<Product> get products => this._products;

  GetProductsAction(this._products);
}

This is also product.dart file:
import 'package:meta/meta.dart';

class Product {
  String id;
  String name;
  String description;
  num price;
  Map<String, dynamic> picture;

  Product(
      {@required this.id,
      @required this.name,
      @required this.description,
      @required this.price,
      @required this.picture});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
        id: json['id'],
        name: json['name'],
        description: json['description'],
        price: json['price'],
        picture: json['picture']);
  }
}

A: I think you are getting Map<String, dynamic> from json.decode(response.body). but you are trying to store it in List<dynamic> inside the getProductsAction() method. Can you change the type and check like below?
final Map<String, dynamic> responseData = json.decode(response.body);


text:
Q: Steps or Procedure to create and authenticate web SDK I tried searching in various places, googling about how I can create and authenticate an SDK which I can use as a starting point. Here is what I am trying to achieve.
My Application:
I am creating a saas similar to firebase, supabase etc., where a user signs up on my application and adds some data, say a todo list.
Now, I would have to provide a client SDK(javascript) and server SDK(python, nodejs). Using this the customer should be able to add the SDK to his own application (Customer Application) and be able to access the data that My Application provides.
To do this, when the SDK is used in the Customer Application, I need to authenticate and get the user details, roles and provide the data from My Application. How can I do this?
I have seen that there is some kind of Client key and Server key generated in My Application. These keys can be used by the customer in his application and initialize the sdk using the Client key.

*

*What kind of auth mechanism is this

*How is the Client key and Server key generated securely

Any link/pointers to resources will be very helpful.

A: We use JWT based auth that encode certain Postgres user roles. You can find more information on it here: https://supabase.com/docs/guides/api#api-security


text:
Q: How to use points and pixels on iphone? I know there is 960 x 640 screen resolution on iPhone4 and 480 x 320 on iPhone3 GS. Does that mean number of max pixels or number of points? I'm actually using points because I'm using functions like CGPointMake and I would like to know what is the max of points. But I'm a little bit confused about how many of them there are and how I should design my code when programming on iPhone3, iPhone4 and maybe above versions.

A: Those resolutions are in pixels. Almost all of the time, you should be dealing with points. iPhone screens are 320 x 480 points. The right thing happens on a retina display: CGPointMake(160, 240) will always be the center of the screen.


text:
Q: Is background-size property not animatable in IE11? I've been trying to get this text underline transition to work: https://codepen.io/shshaw/pen/pdyJBW

a, .strike {
  color: #FF5151;
  text-decoration: none;
  display: inline;
  background-image: linear-gradient(to bottom, transparent 20%, currentColor 21%);

  background-position: 0 1em;
  background-repeat: no-repeat;
  background-size: 0% 6px;

  transition: background-size 0.5s ease-in-out 0.2s;
}

a:hover,
a:focus {
  background-size: 100% 6px;
  transition-delay: 0s;
}

.strike {
  color: #307672;
  background-size: 0% 2px;
  background-position: 0 0.5em; /*1em;*/
}

.strike:hover,
.strike:focus {
  background-size: 100% 2px;
  transition-delay: 0s;
}

html {
  background: #000249;
  color: #FFF;
  font-size: 62.5%;
  display: flex;
  height: 100%;
}

body {
  font-size: 1.6rem;
  line-height: 1.4;
  max-width: 30em;
  width: 90%;
  margin: auto;
  background: inherit;
  -webkit-font-smoothing: antialiased;
  font-smoothing: always;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est. Mauris vehicula cursus risus id luctus. Curabitur accumsan venenatis nibh, non egestas ipsum vulputate ac. Vivamus consectetur dolor sit amet enim aliquet eu scelerisque ipsum hendrerit. Donec lobortis suscipit vestibulum. Nullam luctus pellentesque risus in ullamcorper. Nam neque nunc, mattis vitae ornare ut, feugiat a erat. Ut tempus iaculis augue vel pellentesque.

Vestibulum nunc massa, gravida quis porta nec, feugiat id metus. Strike me! Nunc ac arcu dolor, quis vestibulum leo. Cras viverra mollis ipsum, non rhoncus lectus aliquam et. Morbi faucibus purus sit amet lacus aliquet elementum. Donec sit amet posuere enim. Cras in eros id tortor fringilla ultricies. Mauris faucibus ullamcorper velit, pulvinar varius odio eleifend eu. Quisque id odio metus. Morbi adipiscing ultricies posuere. Pellentesque elementum porttitor eros in molestie. Maecenas ut leo quis nisi tempor tincidunt.

Donec nunc ligula, vulputate quis mollis eu, interdum quis libero. Donec nulla ante, facilisis sit amet vulputate at, tincidunt a velit. Maecenas vestibulum, nulla sed tincidunt viverra, lorem turpis aliquam urna, ut pretium orci purus consequat augue. Etiam a enim orci, vitae pulvinar odio. In elit urna, tincidunt a pellentesque et, scelerisque at nibh. Sed nec est sapien. Aliquam ullamcorper eros eu quam ultrices vel faucibus eros interdum. Etiam mattis eleifend sapien, eu iaculis massa feugiat sed. Aliquam erat volutpat. Vivamus facilisis ultricies eros, a pretium purus mollis id. Sed dapibus elit ut neque rutrum dignissim. Nulla eros nisl, venenatis quis rhoncus sit amet, molestie nec nisl. Pellentesque vel neque sapien, et sagittis nulla.

Aliquam eu iaculis mauris. Etiam arcu lectus, imperdiet sit amet volutpat vitae, commodo sed nibh. Fusce faucibus tempor cursus. Donec ut ligula tortor. Maecenas malesuada, diam vitae pharetra dictum, erat ante iaculis risus, sed sollicitudin nisl nisl vel metus. Nulla libero augue, convallis nec luctus id, iaculis nec urna. Cras vitae mi ut augue ultricies tempus.

And I've got it working in all major browsers except IE11.  I've seen this SO question (Background size animation not working in IE11 or Ipad) where the accepted answer says: "Internet Explorer 11's set of animatable CSS properties is the same like they've started in IE 10 with, and background-size is not among those animatable ones."
That answer also links here: https://www.w3schools.com/cssref/css_animatable.asp
Which lists the animatable properties, and lists background-size as one of those animatable properties, but when I try to run their example (https://www.w3schools.com/cssref/tryit.asp?filename=trycss_anim_background-size) in IE11, it doesn't work.
I can't seem to find any documentation that explicitly lists the animatable properties in IE11, so is background-size simply not animatable in IE11, and is there any documentation that says so?


text:
Q: send udp message from android phone to PC(windows) not working I want to send a UDP message from my android phone 4.2(client) to PC(server) using WIFI connection. My phone and PC are connected via wireless router.  But no message is received from phone to mobile.  I have also tested this code for PC to PC connection successfully. I have added internet permission to manifest.xml. I would be greatefull, if you could help me. Thank you. I have added this permission.
 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Client:
@Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = (Button) findViewById(R.id.button1);
        final TextView tv = (TextView) findViewById(R.id.textView1);
        final TextView tv2= (TextView) findViewById(R.id.textView2);

        button1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {

                boolean morgan= isOnline();
                String s = String.valueOf(morgan);
                tv.setText(s);

                try{

                    //InetAddress ipaddress = InetAddress.getByName("localhost");
                    InetAddress ipaddress = InetAddress.getByName("192.168.10.11");
                    int port = 6500;
                    //byte[] buffer = new byte[1024]; // empty byte array
                    String msg ="hello goooooooogle"; // send this message to the server
                    byte [] b_array = msg.getBytes();

                    //on SERVER side DatagramSocket able to receive packets on 8080 port
                    DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number)
                    DatagramSocket socket = new DatagramSocket();
                    socket.send(packet);
                    socket.close();

                }
                catch(Exception e)
                {
                    System.out.println(e);
                }
                }

        });
    }

    public boolean isOnline() {

        Runtime runtime = Runtime.getRuntime();
        try {

            Process ipProcess = runtime.exec("/system/bin/ping -c 1 192.168.10.11");
            //Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);

        }
        catch (IOException e)
        { e.printStackTrace(); }
          catch (InterruptedException e) { e.printStackTrace(); }

        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Server
public class server
{
    public static void main(String args[])
    {

        try{
            System.out.println("aaa");
            byte[] inbuf = new byte[1000]; // default size
            DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);

            DatagramSocket socket = new DatagramSocket(6500);
            socket.receive(packet);

            int numBytesReceived = packet.getLength();
            System.out.println(numBytesReceived);
            String s = new String(inbuf);
            System.out.println(s);
            //System.out.println(inbuf[2]);

            socket.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

A: When dealing with network operations on Android it is recommended to use a separate thread to perform such operations. So try isolating your code in the onClick() method into an AsyncTask to run it in the background.
private class SendMessageTask extends AsyncTask<String, Void, Void> {
 protected Void doInBackground(String... ip) {
     // run network socket code here
     return null;
 }
}

Then onClick() will contain something like this:
new SendMessageTask().execute("IP_HERE");

Obviously you can modify it to fit your needs. However, if you need to send more data during the lifetime of your app, you may want to use your own background thread. Here's a more detailed explanation to why network operations can't / shouldn't be done in the UI thread - http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html


text:
Q: Using GammaRay Client without GUI I would like to perform a click on a QT pushButton using GammaRay. I managed to do it using the GammaRay Client GUI. But I need to reproduce it using code or terminal command. Is there any way to do it with GammaRay? Is there any alternative?

A: For automation and testing I recommend to use Squish, because the purpose of GammaRay is introspection not automation.
https://www.froglogic.com/de/squish/editions/qt-gui-test-automation/


text:
Q: Equivalent WPF binding syntax I need some help with WPF binding syntax:
public class ApplicationPresenter
{
    public ObservableCollection<Quotes> PriceList {get;}
}

public class WebSitePricesView
{
    private IApplicationPresenter presenter
    {
        get { return (ApplicationPresenter)DataContext; }
    }

//  public ObservableCollection<Quotes> PriceList
//  {
//      get {return presenter.PriceList; }
    }
}

This XAML works fine:
<UserControl.Resources>
    <ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
    <xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Path=PriceList} />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />

However I don't want WebSitePricesView to expose PriceList, I want to bind the DataGridCollectionViewSource directly to ApplicationPresenter.PriceList.
This XAML doesn't bind any values to the grid. Obviously I'm doing something wrong in defining the Binding Source for price_list .....
<UserControl.Resources>
    <ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
        <xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Source={StaticResource ApplicationPresenterDS}, Path=PriceList />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />

The debug output for the first successful binding is:
Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 :   Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 60 : BindingExpression (hash=35059110): Use Framework mentor <null>
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 65 : BindingExpression (hash=35059110): Framework mentor not found
System.Windows.Data Warning: 61 : BindingExpression (hash=35059110): Resolve source deferred
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got InheritanceContextChanged event from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 67 : BindingExpression (hash=35059110): DataContext is null
System.Windows.Data Warning: 52 : Created BindingExpression (hash=53154844) for Binding (hash=52037308)
System.Windows.Data Warning: 54 :   Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=53154844): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=53154844): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=53154844): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=53154844): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=53154844): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item <null>
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with <null>, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from <null> using <null>: <null>
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value <null>
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value <null>
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110):   At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=22260412), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=22444475 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=22444475 Count=0) using <null>: DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got PropertyChanged event from ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=61423861 Count=27), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=61423861 Count=27) using <null>: DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=61423861 Count=27)

The debug output for the second binding is:
Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 :   Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: <null> (OK)
System.Windows.Data Warning: 73 : BindingExpression (hash=35059110): Use Data from ObjectDataProvider (hash=61302538)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=20390146)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110):   At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=20390146), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=20390146) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 52 : Created BindingExpression (hash=12661120) for Binding (hash=31408037)
System.Windows.Data Warning: 54 :   Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=12661120): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=12661120): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=12661120): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=12661120): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=12661120): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=12661120): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=12661120): Activate with root item DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=12661120): Replace item at level 0 with DataGridCollectionView (hash=49343907 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=12661120): GetValue at level 0 from DataGridCollectionView (hash=49343907 Count=0) using <null>: Data``GridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=12661120): TransferValue - got raw value DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=12661120): TransferValue - using final value DataGridCollectionView (hash=49343907 Count=0)
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

A: Not sure what your problem is, the bindings (apart from the missing end quotes) appear to be fine. The following code works fine for me.
public class Quotes
{
    public string Description { get; set; }
    public decimal Value { get; set; }
}

public class ApplicationPresenter
{
    public ApplicationPresenter()
    {
        PriceList = new ObservableCollection<Quotes>()
        {
            new Quotes(){Description="Quote One", Value=10m},
            new Quotes(){Description="Quote Two", Value=10m},
            new Quotes(){Description="Quote Three", Value=10m},
            new Quotes(){Description="Quote Four", Value=10m},
        };
    }
    public ObservableCollection<Quotes> PriceList { get; private set; }
}

<Window
    x:Class="ObjectDataProviderPresenterSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"
    xmlns:local="clr-namespace:ObjectDataProviderPresenterSample"
    Title="Window1"
    Height="300"
    Width="300"
    >
    <Window.Resources>
        <ObjectDataProvider
            x:Key="ApplicationPresenterDS"
            ObjectType="{x:Type local:ApplicationPresenter}"
            />
        <xcdg:DataGridCollectionViewSource
            x:Key="price_list"
            Source="{Binding
                        Source={StaticResource ApplicationPresenterDS},
                        Path=PriceList}"
            />
    </Window.Resources>

    <Grid>
        <xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}}" />
    </Grid>
</Window>

A: I am not sure, since it is not very clear from your code where data go to PriceList, but what I see is that this collection is just empty in second xaml.
Creating ObjectDataProvider in xaml in both cases just creates object of type ApplicationPresenter through default constructor. Your constructor creates empty collection PriceList. (Ian's constructor creates PriceList AND fills it with fake data. That's why his example works).
So, DataGridCollectionViewSource in second xaml of your example basically refers to  ApplicationPresenter with empty PriceList.
The first xaml, in contrast, refers to PriceList of WebSitePricesView which, I believe, somehow is filled somewehere outside given slice of code.
If my theory is good, the removal of ObjectDataProvider from the first xaml won't cange anything - it sill will be working, because data goes directly to presenter.PriceList.
But, again, I am not sure.


text:
Q: Is there a way to extend SmartGit so it works with Gerrit? We use SmartGit for much of our interaction with Git. SmartGit doesn't allow you to specify custom URIs for remote branches. It likes you to select from a list, which doesn't include changes listed under refs/for/master. I was wondering if there was some way to add a custom menu action to SmartGit for checking out from Gerrit. I guess there's no way to add macros in SmartGit? I understand I can always use commandline or eGit, but I'm trying to keep all git management under one tool, if at all possible.
Update
Forgot to mention, I'm interested in getting checkouts to work as well. For specific refs which represent changes. For example:  refs/changes/10/35020/1.

A: In SmartGit you can use Push Advanced, select Into a non-default remote branch there and enter refs/for/master. SmartGit currently does not allow to pull an arbitrary ref nor does it display any other refs than refs/heads, refs/remotes and refs/tags.


text:
Q: How to highlight or mark changed lines in Vim? In many IDEs and editors, the lines which have been changed since file load can be marked or highlighted. How can I do this in Vim?

A: Vim - highlight changed lines


text:
Q: Counting specified repeated characters in python A programmer is building a function that checks if the letter 'a' in one string occurs the same number of times as 'z' in a second string.
def check_words(word1, word2):
    count1 = 0
    for char in word1:
        if char == "a":
            count1 += 1

    count2 = 0
    for char in word2:
        if char == "z"
            count2 += 1

    return count1 == count2

Is there anyway that this code could be simpler and more modular by placing existing code into a new function.

A: You can use .count()  which counts the character you are looking for in a sequence such as a string or a list.
s1 = "aaa"
p1 = "a"
s2 = "zzz"
p2 = "z"

def check_words(s1, s2, p1, p2):
    return s1.count(p1) == s2.count(p2)

print(check_words(s1, s2, p1, p2))

A: @Andreas's answer should be the most efficient you can do in Python. Concerning your question about modularizing your code, the best thing to do generally is to try to see which pieces of code do almost the same task, up to some parameter. Here, you can see that:
    count1 = 0
    for char in word1:
        if char == "a":
            count1 += 1

and
    count2 = 0
    for char in word2:
        if char == "z"
            count2 += 1

are almost identical, the only thing changed being the character. Hence, you can write this as a function and call it in your code:
def count(word, c):
    count = 0

    for char in word:
         if char == c:
             count += 1

    return count

def check_words(word1, word2):
    count1 = count(word1, "a")
    count2 = count(word2, "z")

    return count1 == count2

You can see that this code is very similar to @Andreas'. The difference is that they're using the count method of a string object which is already implemented in Python, and should be much faster than this pure-Python implementation.

A: from collections import Counter

def check_words(word1, word2):
    dict_1 = Counter(word1)
    dict_2 = Counter(word2)
    return dict_1['a'] == dict_2['z']

This should be fastest way to do so, of course it's better to add 2 more arguments instead of hardcoding 'a' and 'z'


text:
Q: How to remove new files from a directory? I'm used to do this when I want to rollback changes in a directory:
$ git checkout path/to/dir/

But now I need to remove files that have been created (not modified) in that dir, and checkout didn't work. What can I do?

A: git clean -f or git clean -f -d if you also want to remove directory. Source
Also check out the official documentation


text:
Q: Windows Phone 7 Boot Startup Receiver Callback WP7 Does WP7 have have some kind of receiver/callback for when the device is booted up. I would like to schedule some task when the device is started up

A: No, it does not. Perhaps if you setup a periodic task - you could get some information within about half hour after it starts that it is running, so if it was not reporting as running earlier - you might use this information, but otherwise - your code is pretty much sandboxed and does not know anything about what the system is doing when your application is not running.


text:
Q: Operator '==' cannot be applied to types string and number How to check the value of a number?
for(var index in this.choicesDM) {
  if(index == 0) {
    this.currentChoice = this.choicesDM[index]
  }
}

Here I get the error as mentioned in the title of the question. I also tried to explicitly define the type of index. But didn't work.
Found this link but didn't got the solution.

A: In JavaScript (and thus, TypeScript), the in operator returns a string. This is because for in loops iterate over an object's keys, which are strings in JavaScript/TypeScript. So, when you compare index == 0, index is a string and 0 is an integer, thus the error.
Note what I said before, though, that for in enumerates over an object's properties. In the case of arrays, this also includes things like the length property, so it's generally a bad idea to loop over arrays with for in. What you might want instead is a for of loop, where of gives you the value of each object in the array.

A: The reason for this is because == and other related comparison operators operate on operands with same type or type of 1 operand should be subtype of other operand. But in your case 0 is integer and "index" is string. Hence the error.


text:
Q: Using ResultReceiver what happen if activity is destroyed and intent service is still running This question has already been asked here but yet no good answer.
So basically I have an intent service running in the background to do some stuff and once finished I send the result back to activity using resultreceiver so what I need to know is the following:

*

*How can I handle a situation when activity is destroyed while intent
service is still running?

*How to know if activity is destroyed from intent service?

*What happens to resultreciever when sending the result back to
activity when the activity is already destroyed? Does that produce an error?

A: This is a late answer, but I was researching the functioning of IntentService and I came across your question.

how can handle a situation when activity is destroyed while intent service is still running ?

Since the IntentService is a separate component it will continue to run until the task designated to it is complete or the process on which the application is running is destroyed. The initial thought might be to stop the IntentService when the activity is destroyed. Simple, isn't it? Well, not quite. As it turns out when you call stopService(Intent), though the onDestroy() method of the IntentService is called, the background thread will continue to run until it's complete and deliver a result to the receiver.

how to know if activity is destroyed from intent service?

This is a good question and something that I myself wondered. One neat solution is described here - IntentService responding to dead ResultReceiver

what happen to resultreciever when sending the result back to activity when the activity is already destroyed ?does that produced error?

This will most likely not result in any visible exception as the activity is not visible. But it could result in a memory leak on a configuration change as you have a reference to an object defined in the activity (which will prevent the activity from being garbage collected as long the thread continues to run - see IntentService prevents activity from destroying). But the answer linked above should alleviate this problem as it nulls out the reference of the ResultReceiver in onDestroy, avoiding any potential memory issues
Also, it would be worthwhile to mention that you can consider the approach of a LocalBroadcastManager which makes it easier to work with the lifecycle of the Activity by registering/unregistering the BroadcastReceiver. Example available here from the google samples repo


text:
Q: Animate content in a list I want to make it so that when I hover over one of the items in a list, it moves that element.
Here is my HTML code for the list:

Home

News

About us

Venue

Affiliations

Players & Officers

Fixtures & Results

Coaching

Contact us

And here is my Jquery code:
    $(document).ready(function() {
      $('').mouseenter(function() {
        $(this).animate({ left: '+=100px' });
      });

      $('').mouseleave(function() {
        $(this).animate({ left: '-=100px' });
      });
    });

Basically, my question is what goes in the quote marks in the JQuery functions?

A: Use the on event
$(document).ready(function () {

    $('.nav').on({
         mouseenter : function(){
            $(this).animate({left: '+=100px'});
         },
        mouseleave : function(){
            $(this).animate({left: '-=100px'});
         }
     }, 'li');
 });

A: Try this:
$(document).ready(function()
    {
    $('.nav li').mouseenter(function()
    {
        $(this).animate({left: '+=100px'});
    });

    $('.nav li').mouseleave(function()
    {
        $(this).animate({left: '-=100px'});
    });
});

A: You can use $('.nav li') to target list items of your nav:
$(document).ready(function () {
    $('.nav li').mouseenter(function () {
        $(this).animate({
            left: '+=100px'
        });
    });

    $('.nav li').mouseleave(function () {
        $(this).animate({
            left: '-=100px'
        });
    });
});

Also, you need to set position: relative for your list items, so the left value can work:
.nav li {
    position: relative;
}

Fiddle Demo

A: You might want to consider the .on and event map approach.
$('.nav').on({
  mouseenter : function(){
    $(this).animate({left: '+=100px'});
  },
  mouseleave : function(){
    $(this).animate({left: '-=100px'});
  }
}, 'li');

A: HTML Code:

Home

News

About us

Venue

Affiliations

Players & Officers

Fixtures & Results

Coaching

Contact us

Javascript:
$(document).ready(function () {
    $('.nav li').mouseenter(function () {
        $(this).animate({
            left: '+=100px'
        });
    });

    $('.nav li').mouseleave(function () {
        $(this).animate({
             left: '-=100px'
        });
    });
});

A little CSS tweek to make the list hover animation work:
.nav {
   padding: 20px 0 0 20px;
}
.nav li {
   position: relative;
}

Check the demo at: DEMO


text:
Q: Extract gridded data from GEE I would like to extract data from certain satellite images (e.g. average night lights) in GEE for square grids in a given country in order to analyse the data in R. The square grids are supposed to be rather small (100x100m²). What is the most efficient way to accomplish that?
My current approach would be to create a suitable shapefile in R, upload that to GEE, extract the data and download the results. Unfortunately it's computationally very intensive to do this for such small grids (and currently I'm not sure GEE allows me to do that). Is there a more efficient alternative to get to my goal?

A: Here's how you can export an ee.Image for the desired region at a different scale.
// Example night lights image
var nl = ee.ImageCollection('NOAA/VIIRS/DNB/MONTHLY_V1/VCMCFG').first().select(0);

// All countries
var countries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');

// For example
var brazil = countries.filter(ee.Filter.eq('country_na', 'Brazil'));
Map.addLayer(brazil)

// Desired output resolution in meters.
var scale = 100;

// export the image at the desired scale
Export.image.toDrive({ image: nl,
                       region: brazil,
                       scale: scale });


text:
Q: How to change the ragged right CR/LF position in .txt file (ie using UltraEdit) before importing in SQL Server? I was provided a ragged right UNIX text file with the CR/LF position of most lines appears to be set at 100. I was provided a column layout document that takes the file out to position 150. Is there a way to change the CR/LF position to 150? If I import into SQL Server using the format provided, since the linefeed is at 100, SQL Server grabs the first 50 characters of the next line.

A: I can offer 2 solutions.
Using column mode

*

*Move caret to column 151 according to status bar in first line of file.
There are now 150 characters left of caret position.

*Click in menu Column on menu item Column Mode to turn on this mode.

*Click in menu Column on menu item Insert/Fill Columns, enter a single character like # and execute this command.

*You see now character # on all lines inserted at column 151.
Click in menu Column on menu item Delete Columns, enter 1 and execute the command.

*Click in menu Column on menu item Column Mode to turn off this mode.

Now all lines in file have 150 characters. You might want to go to end of file using Ctrl+End and delete the 150 spaces in last line if this line does not contain anything else.
You can enable Show Line Endings in menu View to check the lines visually.
This solution is often the easiest method for small files.
Using Perl regular expression replaces

*

*Insert at top of your file 150 spaces, select the 150 spaces using Ctrl+Shift+Home and cut them with Ctrl+X to the clipboard.

*Run a Perl regular expression Replace All from top of file with $ as search string (means end of line) and paste with Ctrl+V the 150 spaces into the replace edit field replacing everything already existing in this edit field.
Now all lines have 150 or more characters.

*Run one more Perl regular expression Replace All from top of file with ^(.{150}).*$ as search string and \1 as replace string.

The second Perl regular expression using a marking group for the first 150 characters of each line back referenced with \1 to keep them removes all other inserted spaces from each line from column 151 to end of line.
This solution is better for very large files and of course works also with other editors supporting Perl regular expression replaces.


text:
Q: Why does this login fail for user 'Servername\Guest'? I install SQL Server 2005 EXPRESS edition on one computer, Computer Name = 'MyServe'  and Database name='MyDB',take it as database server. it is configured as both Database and Windows Authentication Mode. with username=sa and password=adminaa.
I have application in C#.Net
 my connection string is
ConnectionString = "Data Source=MyServe\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True;User ID=sa;Password=adminaa";
when I run the application on the computer called MyServe, the database server, it works well, while when I install the application on different computer, when it tries to connect the database it gives an error called "login failed for user 'MyServe\Guest" what is wrong with configuration in the database server or other mistakes. please help me. thankyou in advance.
Metasebia

A: If you want to use SQL authentication, remove the 'Integrated Security=true' from your connection string. This will trump the values in the UserId and Password fields, forcing integrated windows authentication to occur.


text:
Q: Issues in parsing JSON file There was an example of reading jsonp request in jquery given in stackoverflow. This below code works fine.
$(document).ready(function() {
   var url =  "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
   $.getJSON(url + "?callback=?", null, function(tweets) {
    for(i in tweets) {
        tweet = tweets[i];
        $("#tweet-list").append(tweet.text + "<hr />");
    }
   });
});

I uploaded the json file into a temp webserver with url being http://cruzer.net76.net/twitter.json
But my json doesn't seemed to get parsed and the browser shows no errors/warnings.
Any help..

A: Your code as-is works: http://jsfiddle.net/vWRAw/
The json being returned from your temp-webserver however is JSON and not JSONP. If you want to request it as JSON, remove the ?callback=? however that would mean your temp webserver would need to be on the same domain as the page making the request.


text:
Q: Unable to mount root fs after loss of power I accidentally pulled the power cort of my Computer while it was running. After I turned it on again it said "unable to mount root fs" so I tried to boot an old kernel. It worked and I am now able to save my data at least. What is the most accurate step from this position to repair the system. Reinstall Ubuntu, boot from live CD or any way from the loaded kernel desktop to operate?
UPDATE: the Computer can sometimes not even boot the kernel selection. I guess reinstall Ubuntu is necessary, is there a way to check the hard disk if it took damage?


text:
Q: Running tasks from broadcast receiver while app is closed [Android] I have an app that downloads data and put it into an SQLite Database when a notification is issued. This works fine while the app is in use but I need it to work when the app is closed too.
I have set up a BroadcastReceiver within that is called when the app is closed but I'm not sure how to get it to continue with adding to the database.
Here is the code I am using:
AndroidManifest.xml
<manifest....

   <application...

     <receiver android:name=".broadcast.PacksReceiver" >
        <intent-filter>
            <action android:name="ADD_PACK" >
            </action>
        </intent-filter>
    </receiver>

PacksReceiver
public class PacksReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("PacksReceiver", "onReceive");

    String message = intent.getStringExtra("message");

    PacksActivity pa = new PacksActivity();
    pa.downloadPack(null, message);
  }
}

PacksActivity
public void downloadPack(View v, String thisPackID){
    Log.d("download", "pack");
    //THIS LOG IS CALLED EVERYTIME
    vRef = v;
    if(vRef != null){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onScreenProgressBar = (ProgressBar) vRef.findViewById(R.id.onScreenProgress);
                onScreenProgressCircle = (ProgressBar) vRef.findViewById(R.id.onScreenProgressCircle);
                dlPercent = (TextView) vRef.findViewById(R.id.dlPercent);

                onScreenProgressCircle.setVisibility(View.VISIBLE);

                onScreenProgressBar.setVisibility(View.VISIBLE);
                onScreenProgressCircle.setProgress(0);
            }
        });
    }
    if(thisPackID == null){
        thisPackID = pack_id;
    }

    String url = MyApp.getAppContext().getString(R.string.serverURL) +
            MyApp.getAppContext().getString(R.string.getAppendixA) + "/" + thisPackID;
    Intent appA_Intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);
    appA_Intent.putExtra("url", url);
    appA_Intent.putExtra("onCreate", "false");
    appA_Intent.putExtra("receiver", downloadPackReceiver);
    appA_Intent.putExtra("downloadType", "GET_APPENDIX_A");
    appA_Intent.putExtra("requestId", 101);
    MyApp.getAppContext().startService(appA_Intent);
}

A: start the Service from
onReceive()

method because you can get mutiple broadcast one after another.

A: Write the code  to add data in your database in your PackReciever inside OnRecieve() Method because that is where you recieve push notifications.

A: Don't call activity inside the receiver. Instead, use IntentService to download all packs. IntentService automatically finishes once it completes its work.
Override its onHandleIntent() method and download packs and save to database there.


text:
Q: org.openqa.selenium.SessionNotCreatedException:
Starting ChromeDriver 109.0.5414.74
(e7c5703604daa9cc128ccf5a5d3e993513758913-refs/branch-heads/5414@{#1172})
on port 57071 Only local connections are allowed. Please see
https://chromedriver.chromium.org/security-considerations for
suggestions on keeping ChromeDriver safe. ChromeDriver was started
successfully. Exception in thread "main"
org.openqa.selenium.SessionNotCreatedException: Could not start a new
session. Response code 500. Message: unknown error: Chrome failed to
start: crashed.   (unknown error: DevToolsActivePort file doesn't
exist)
(The process started from chrome location
C:\Users\ajays\AppData\Local\Google\Chrome\Application\chrome.exe is
no longer running, so ChromeDriver is assuming that Chrome has
crashed.)
Build info: version: '4.3.0', revision: 'a4995e2c09*' System info:
host: 'LAPTOP-8VG52IH3', ip: '192.168.20.2', os.name: 'Windows 11',
os.arch: 'amd64', os.version: '10.0', java.version: '17.0.5' Driver
info: org.openqa.selenium.chrome.ChromeDriver Command: [null,
newSession {capabilities=[Capabilities {browserName: chrome,
goog:chromeOptions: {args: [], extensions: []}}],
desiredCapabilities=Capabilities {browserName: chrome,
goog:chromeOptions: {args: [], extensions: []}}}]     at
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:144)
at
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:102)
at
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:67)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:156)
at
org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)
at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569)
at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:264)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:179)
at
org.openqa.selenium.chromium.ChromiumDriver.(ChromiumDriver.java:101)
at
org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:81)
at
org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:49)
at javaeclipseselenium.Test1.main(Test1.java:13)
getting "Could not start a new session. Response code 500. Message:
unknown error: Chrome failed to start: crashed"

*

*Installed java

*Installed selenium jars and build the path.

*My downloaded chrome driver and the chrome version are same. (note:
firstly my chrome version and downloaded driver version was
different so downgraded the chrome and made sure both are sameenter
image description here).

package javaeclipseselenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test1 {

    public static void main(String[] args) throws InterruptedException{
        // TODO Auto-generated method stub
                System.setProperty("webdriver.chrome.driver","C:\\Users\\ajays\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.selenium.dev/selenium/web/web-form.html");
        driver.quit();
    }
}

I have checked for all the options online to solve the issue even with maven webdrivermanager ....can anyone please help with this ? i'm stuck since 2 days.


text:
Q: Rand order in stock SQL Woocommerce I have these 2 codes, currently it runs randomly but it does not filter the products in stock.
How would it be to be random and respect woocommerce "instock" products?
Code1:$sortQuery = 'ORDER BY RAND()';
Code 2: $sortQuery = ' AND id NOT IN (SELECT post_id FROM'.FSwpTable('feeds')."WHERE schedule_id='" . (int)$scheduleId . "') ORDER BY RAND()";
I have understood that the stock is stored here

meta_value = _stock_status WHERE meta_key = 'instock';

Thanks

A: You may need to tweak this a bit as I don't have a WP database in front of me at the moment, but I believe you want an SQL query as such
SELECT wp_postmeta.post_id
FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.Id = wp_postmeta.post_id
WHERE wp_post.meta_key = 'instock'
ORDER BY RAND();


text:
Q: find in deep nested array (tree) recursivley I want to find a value in the following nested array without using loops:
let children = [
  {
    name: 'grand 1',
    children: [
      {
        name: 'parent 1.1',
        children: [
          {
            name: 'child 1.1.1',
            children: [
              // more...
            ]
          },
          // more...
        ],
      },
      // more...
    ],
  },
  // more...
];

This is what I'd do if I was only searching in the horizontal axis:
let childrenHorizontal = [
  { name: 'grand 1' },
  { name: 'grand 2' },
  { name: 'grand 3' },
  // more
];

function findHorizontal(name, childrenHorizontal) {
  let [head, ...tail] = childrenHorizontal;
  if (head.name === name)
    return head;
  else if (tail.length)
    return findHorizontal(name, tail);
}

But how do I search the nested array both horizontally and vertically?

A: A bit more generically, we can write a deepFind function that takes an arbitrary predicate and returns a function that tests a tree in a depth-first manner until it finds a matching node, returning undefined if no match is found. (This is JS, after all!)  Then we can write findByName as a function that that takes a target name and passes to deepFind a function that tests whether a given node's name matches that target.  It might look like this:

const deepFind = (pred) => ([head, ...tail]) =>
  head == undefined
    ? undefined
  : pred (head)
    ? head
  : deepFind (pred) (head .children) || deepFind (pred) (tail)

const findByName = (target) => deepFind (({name}) => name == target)

let children = [{name: 'grand 1', children: [{name: 'parent 1.1', children: [{name: 'child 1.1.1', children: []}]}, {name: 'parent 1.2', children: []}]}]

console .log ('parent 1.1:', findByName ("parent 1.1") (children))
console .log ('child 1.1.1:', findByName ("child 1.1.1") (children))
console .log ('parent 1.2:', findByName ("parent 1.2") (children))
.as-console-wrapper {max-height: 100% !important; top: 0}

(Note that I added a parent 1.2 node in the obvious location in the tree to demonstrate searching multiple children of one node.)
This finds the first node in a pre-order traversal of the tree that matches our predicate.  We use the short-circuiting feature of JavaScript's || operator to stop as soon as we've found a match.

A: Ok I figured it out. The trick is to concatenate the two axes:
function find(name, children) {
  let [head, ...tail] = children;
  if (head.name === name)
    return head;
  return find(name, [...head.children, ...tail]);
}

But then I realized it is wasteful to concatenate the arrays when I can just use logical OR (using the null-coalescing operator):
function find(name, children) {
  let [head, ...tail] = children
  if (head.name === name) return head
  return find(name, head.children) ?? find(name, tail) // no concat!
}

And I also learned that you must always check if the input array is empty, otherwise head could be undefined!
function find(name, children) {
  if (children.length == 0) return; // exit early if children is empty
  let [head, ...tail] = children;
  if (head.name === name) return head;
  return find(name, head.children) ?? find(name, tail);
}

One possible way to restore the tail call is to use continuation-passing style:
const identity = x => x

function find(name, children, k = identity) {
  if (children.length == 0) return;
  let [head, ...tail] = children;
  if (head.name === name) return k(head);
  return find(name, head.children, result => // tail find
    result ?? find(name, tail, k)            // tail find
  );
}

I also learned that destructuring assignment let [head, ...tail] creates new tail arrays - for every node along the way! find is a sort of read operation on the structure, so it would be wasteful to create single-use data along the way:
function find(name, children, i = 0) {
  if (i >= children.length) return; // exit if i is out of bounds
  let head = children[i] // "head" is now a cursor over the array
  if (head.name === name) return head;
  return find(name, head.children) ?? find(name, children, i + 1);
}

If I want the user to prevent accidentally passing initial i argument, I can wrap in an outer function. And I could add the CPS technique for tail call, if needed.

A: You need to use recursion :

const data = [{
    name: 'grand 1',
    children: [{
        name: 'parent 1.1',
        children: [{
            name: 'child 1.1.1',
            children: []
          },
          // more...
        ],
      },
      // more...
    ],
  },
  // more...
];

const find = (name, children) => {
  for (const child of children) {
    // if the chidren's name corresopnds to the one provided, return it
    if (child.name === name) return child

    // here is the recursion
    const e = find(name, child.children)

    // if we found it on the child, we return the one found, else we keep going
    if (e) return e
  }

  // if none of the children or grand-children ... found, return null
  return null
}

console.log(find('parent 1.1', data))


text:
Q: prefered input type EditText I create dynamically an EditText.
For the forced inpt type with numbers ill use  .setInputType(InputType.TYPE_CLASS_NUMBER);
Now I want only the prefered input type is numbers, but characters are allowed. The keyboard popup should first show the numberpad. Is that possible?
thanks


text:
Q: CSS Bulma with different font-family and line-height I am using Bulma css framework with custom font Comfortaa from https://fonts.google.com/specimen/Comfortaa
But the font has some extra space at bottom and it makes all text of elements to be little higher than it should be.
On img: 1) comfortaa 2) roboto 3) Segoe UI (with button and h1 with border)
see comparision img
How to make text of elements with Comfortaa font on same level as others ?
Preferably in Bulma. Thank you.

A: You could add extra padding to the text container to push it down a little. You'll need to tweak the amount of padding to suit. Below is an example of how that could work. I have created a class .text-offset that pushes the text down 1px with padding-top.
The whitespace you have outlined in your image is the fonts line height, it is different from font to font. Apparently, some web fonts try to balance the top and bottom spacing out for this reason.

body {
  font-family: 'Comfortaa', cursive;
  padding: 20px;
}

.text-offset {
  padding-top: 1px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">

  GitHub


text:
Q: Light weight container around const char* & length without copying the data I have a underlying API that passes a const char* and a length:
foo(const char* data, const uint32_t len);

I'd like to wrap this data/length in a light weight container that can be iterated and has the ability to be randomly accessed but not make a copy (e.g. like a vector). What is the best way to achieve this? The const char* data is not necessarily a 'string'; it may contain NULL's throughout.
I am using STL and Boost. I've seen boost::as_array<> and as_literal<> -- is one of these appropriate here?

A: It would be easy to make such a class. Something like this:
template <class T>
class array_ref {
public:
    // makes it work with iterator traits..
    typedef T         value_type;
    typedef size_t    size_type;
    typedef ptrdiff_t difference_type;

    typedef T*        pointer;
    typedef T*        iterator;
    typedef T&        reference;

    typedef const T*  const_pointer;
    typedef const T*  const_iterator;
    typedef const T&  const_reference;

public:
    array_ref(T *p, size_t n) : data_(p), len_(n) {}

    // iteration
    iterator begin()             { return data_; }
    iterator end()               { return data_ + len_; }
    const_iterator begin() const { return data_; }
    const_iterator end() const   { return data_ + len_; }

    // access
    reference operator[](size_t n)             { return data_[n]; }
    reference at(size_t n)                     { return data_[n]; }
    const_reference operator[](size_t n) const { return data_[n]; }
    const_reference at(size_t n) const         { return data_[n]; }

    // capacity
    size_t size() const { return len_; }
    bool empty() const  { return size() == 0; }

    // raw access
    T* data() const { return data_; }

    // etc...
private:
    T* data_;
    size_t len_;
};

This looks like a bunch of code, most of it isn't strictly necessary. However, since it is a template the compiler will only generate code for the methods used. And the actual class itself only uses space for the pointer and the length members.
But in the end, this really isn't much of a gain. Since pointers themselves are nice pointers, I'd probably just use raw pointers here.

A: I have used iterator_facade http://www.boost.org/doc/libs/1_43_0/libs/iterator/doc/iterator_facade.html together with iterator_range
you can easily use iterator_range to construct your wrapper, http://www.boost.org/doc/libs/1_42_0/libs/range/doc/utility_class.html#iter_range
boost::iterator_range<char*> range(begin, begin + N);

special cases can be handled with iterator_facade

A: I don't think as_array and/or as_literal will do what you want. While not terribly difficult to write, I don't know of an existing class intended to do what you you want (or at least what I think you want).
Edit: I probably shouldn't say I don't know of any such classes -- I just don't know of any that's particularly well known, widely used, or thoroughly tested. If you search the archives of comp.lang.c++ and/or comp.lang.c++.moderated from, say, 12 to 15 years ago or so, you can probably find at least a dozen (at least provided Google's newsgroup searching is working at the moment). Unless memory fails me particularly badly, I posted one myself somewhere along the line (though I can't seem to find it right now...) As you might guess from their age, however, you probably wouldn't want to use most (any?) of them as-is -- their use of C++ is often quite primitive.


text:
Q: SharePoint 2007: AfterProperties of person input field shows always -1 as lookupid I'm struggling with the SharePoint 2007 AfterProperties. I've a people input field, where several people can be added.
On the ItemUpdating event I now need to determine which users were added, removed or stayed the same.
Unfortunately this becomes quit difficult, as the id of the untouched users turns to -1 in the AfterProperties, so that I cant not use SPFieldUserValueCollection to find the user.
An example. properties.ListItem["AssignedTo"].ToString() shows:
1;#domain\user1;#2;#domain\user2
properties.AfterProperties["AssignedTo"].ToString() shows:
-1;#domain\user1;#-1;#domain\user2;#3;#domain\user3 <-Added a user
I planned to use following code, to determine removed and added users:
foreach (SPFieldUserValue oldUser in oldUserCollection)
{
   if (newUserCollection.Find(x => x.LookupId == oldUser.LookupId) == null)
   {
      RemoveRole(aListItem, oldUser.User, roleDefCollection[workerRoleName]);
   }
}

foreach (SPFieldUserValue newUser in newUserCollection)
{
   if(oldUserCollection.Find(x => x.User.LoginName == newUser.LookupValue) == null)
   {
      AddRole(aListItem, newUser.User, roleDefCollection[workerRoleName]);
   }
}

How can I archive, that the AfterProperties show the right lookupid?

A: Solved the problem by myself. Instead of using the SPFieldUserCollection I'm now using a list and try to parse all the information by myself out of the string.
Regex reg = new Regex(@"\;\#");
string[] usernameParts = reg.Split(usernames);
List<SPUser> list = new List<SPUser>();
int id;

foreach (string s in usernameParts)
    {
        if (!string.IsNullOrEmpty(s))
        {
            if (!Int32.TryParse(s, out id))
            {
                if (list.Find(x => x.ID == spweb.Users[s].ID) == null)
                    list.Add(spweb.Users[s]);
            }
            else
            {
                if (Convert.ToInt32(s) != -1)
                {
                    if (list.Find(x => x.ID == Convert.ToInt32(s)) == null)
                        list.Add(spweb.Users.GetByID(Convert.ToInt32(s)));
                }
            }
        }
    }


text:
Q: type: 'ckeditor' doesn't work in EasyAdminBundle I'm follow the guide on To Integrating IvoryCKEditorBundle in EasyAdminBundle, I'm using Symfony 3.1.10 version and EasyAdminBundle 1.17.12
I put on AppKernel
new Ivory\CKEditorBundle\IvoryCKEditorBundle(), //CK Editor

and just like say in the documentation
easy_admin:
entities:

    Genus:
        class: AppBundle\Entity\Genus
        label: Genuses
        help: Genuses are not covered under warranty!
        form:
            fields:
                -
                    property: id
                    type_options: {disabled: true}
                - name
                - speciesCount
                - { property: funFact ,  type: ckeditor  }
                - isPublished
                - { property: 'firstDiscoveredAt', type_options: { widget: 'single_text' }}
                - { property: 'subFamily', type: 'easyadmin_autocomplete' }
                -
                    property: genusScientists
                    type: 'collection'
                    type_options:
                        entry_type: AppBundle\Form\GenusScientistEmbeddedForm
                        allow_delete: true
                        allow_add: true
                        by_reference: false
                - { property: 'funFact', type: 'textarea' }

I config the property funFact for use ckeditor but does not work
image of the form with funFact without ckeditor on
in web profile of easyAdminBundle this parameter is put as texarea and not appear nothing about ckeditor web profile
Hope yours could help me , Thanks.

A: my mistake I don't see I put at the end again
- { property: 'funFact', type: 'textarea' }

and that replace the property heheh


text:
Q: How do I mutate/modify an instance attribute? I want to distinguish the first time I initiate a class from all the other times I initiate it. I've created an instance attribute and set its value to True. What do I do for all subsequent instances to have that attribute value as False?
class Cool(Dude):

    def __init__(self):
        self.coolnesscheck = True

A: You can use a class attribute, to indicate if the first object has been created or not. Example -
class Cool:
    __firstinit = True

    def __init__(self):
        self.coolnesscheck = Cool.__firstinit
        Cool.__firstinit = False

I am prepending __ in the name to introduce Name Mangling , so that the attribute is not easily accessible outside the class.

A: Use a class attribute, and set it to False when you instantiate an object of that class:
>>> class Cool:
...     coolnesscheck = True
...     def __init__(self):
...         self.coolnesscheck = Cool.coolnesscheck
...         Cool.coolnesscheck = False
...
>>> Cool.coolnesscheck
True
>>> a = Cool()
>>> Cool.coolnesscheck
False
>>> a.coolnesscheck
True
>>> b = Cool()
>>> Cool.coolnesscheck
False
>>> b.coolnesscheck
False


text:
Q: What is F-Bounded Polymorphism in TypeScript I notice version 1.8 of TypeScript supports F-Bounded Polymorphism. In layman's terms, what is it and how is this helpful? I am assuming since this feature was included early it must be pretty important.

A: It basically means that you have your list of generics that the function references, and within that list of generics, one type can reference another type, to define a relationship between the two generic types.
function someFunction <T, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Cat());

Hooray!
Now, with bounded generics, they can reference one another to define the bounds of the relationship they have with each other:
function someFunction <T extends U, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Pet());
const cow = someFunction(new Cow(), new Animal());
const BOOM = someFunction(new Cat(), new Dog()); // *BEWM!*