text:
Q: How to parse dict in Ansible So I have a dict data like this:
{
  "json_response": [
    {
      "message": "The value is 1505. xxxxxxx: xxxxxx: This is a big value. xxxxx.",
      "value": "1505"
    },
    {
      "message": "The value is 5. xxxxxxx: xxxxxxx: This is a small value. xxxxx.",
      "value": "5"
    },
    {
      "message": "The value is 500. xxxxxxx: xxxxxxx: This is a medium value. xxxxx.",
      "value": "500"
    }
  ]
}

I want to parse the value in message and the output that i want to achieve is something like this:
{
  "json_response": [
    {
      "message": "The value is 1505. This is a big value.",
      "value": "1505"
    },
    {
      "message": "The value is 5. This is a small value.",
      "value": "5"
    },
    {
      "message": "The value is 500. This is a medium value.",
      "value": "500"
    }
  ]
}

What should i do to achieve this?

A: Unfortunately I didn't understand exactly what you want to do, but basically you can do a lot of crazy things:
- name: Define input json text block
  set_fact:
    input_json: |
      {
        "json_response": [
          {
            "message": "The value is 1505. xxxxxxx: xxxxxx: This is a big value. xxxxx.",
            "value": "1505"
          },
          {
            "message": "The value is 5. xxxxxxx: xxxxxxx: This is a small value. xxxxx.",
            "value": "5"
          },
          {
            "message": "The value is 500. xxxxxxx: xxxxxxx: This is a medium value. xxxxx.",
            "value": "500"
          }
        ]
      }

- name: Parse json
  set_fact:
    parsed_json: "{{ input_json | from_json }}"

- name: Print first response
  debug:
    msg: "{{ parsed_json['json_response'] | first }}"

- name: Print first values
  debug:
    msg: "{{ ['value'] | map('extract', ( parsed_json['json_response'] | first ) ) }}"

- name: Print all values
  debug:
    msg: "{{ range(parsed_json['json_response'] | length) | map('extract', parsed_json['json_response'], ['value']) }}"

- name: Print all messages
  debug:
    msg: "{{ range(parsed_json['json_response'] | length) | map('extract', parsed_json['json_response'], ['message']) }}"

- name: Fetch all values extracted from the messages
  debug:
    msg: "{{ range(parsed_json['json_response'] | length) | map('extract', parsed_json['json_response'], ['message']) | map('regex_search', '\\d+') }}"

This produces the following output
TASK [Define input json text block] ************************************************************************************
ok: [localhost]

TASK [Parse json] ******************************************************************************************************
ok: [localhost]

TASK [Print first response] ********************************************************************************************
ok: [localhost] => {
    "msg": {
        "message": "The value is 1505. xxxxxxx: xxxxxx: This is a big value. xxxxx.",
        "value": "1505"
    }
}

TASK [Print first values] **********************************************************************************************
ok: [localhost] => {
    "msg": [
        "1505"
    ]
}

TASK [Print all values] ************************************************************************************************
ok: [localhost] => {
    "msg": [
        "1505",
        "5",
        "500"
    ]
}

TASK [Print all messages] **********************************************************************************************
ok: [localhost] => {
    "msg": [
        "The value is 1505. xxxxxxx: xxxxxx: This is a big value. xxxxx.",
        "The value is 5. xxxxxxx: xxxxxxx: This is a small value. xxxxx.",
        "The value is 500. xxxxxxx: xxxxxxx: This is a medium value. xxxxx."
    ]
}

TASK [Fetch all values extracted from the messages] ********************************************************************
ok: [localhost] => {
    "msg": [
        "1505",
        "5",
        "500"
    ]
}

I hope this helps you to reach your goal.


text: Q: What kind of electronic device do I need? I'm looking for a switch that stays normally closed and when it receives power it stays closed for a few seconds before it opens. When power shuts off then the switch goes back to being closed. Is there an electronic device out there that will do this and can someone tell me the name of it

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django ORM can't execute it's own raw query I use Django with Postgres as my database.
If I run this code:
SomeClass.objects.filter(text__regex=rf"searchkeyword")
the_query = str(SomeClass.query)

The the_query variable will be this:
SELECT * FROM "SomeClass" WHERE "SomeClass "."text"::text ~ searchkeyword

But when you run this query using SomeClass.objects.raw(query), it will show this error:
Exception Value:
column "usa" does not exist
... WHERE "SomeClass"."text"::text ~* searchkeyword

So, basically, Django ORM can't run the raw query that it made itself.
Does anyone have any thoughts on this?
First Edit:
Even for simpler queries like this, I get the same error:
SomeClass.objects.filter(text="searchkeyword")

column "searchkeyword" does not exist
LINE 1: SELECT * FROM SomeClass WHERE text = searchkeyword

Second Edit:
This is a little different question than this:
Printing Django QuerySet SQL with ""
In my case, even it does not work if double quotations are used and not removed.


text:
Q: Word that means using a falsehood which can be used as a weapon to advocate for and execute something else What is a word that means using a falsehood which can be used as a means, as a weapon to advocate for and execute something else

The politician claimed that the government budget had a deficit to defend cuts in welfare and local services like libraries and nurseries. However this deficit did not exist so the politician was being ______

Guinness adverts once claimed that guinness is good for you and will help you be alert if you're driving, studying or doing manual labour. This made it marketed as a health drink which then could be an means to sell it in gyms.

Kyle claimed that his bank account was overdrawn and that he didn't want to receive a daily overdraft fee, which then allowed him to borrow £200 which he otherwise would not of been lent the money if he had been honest about his financial situation. This lie made meant he was ________

A: Difficult to find one word for all the three contexts. I first thought of fraudulent, but the second context does not seem to involve liability to law.
Maybe manipulative could work:

tending to influence or control someone or something to your advantage, often without anyone knowing it. (Cambridge)

But the -ing form of the verb to manipulate could also be used as an adjective:
manipulating
to manipulate means

to control something or someone to your advantage, often unfairly or dishonestly

*

*The opposition leader accused government ministers of manipulating the statistics to suit themselves. (Cambridge)

The politician, the Guinness adverts and Kyle could be said to be manipulative/manipulating.

A: However this deficit did not exist so the politician was being Machiavellian
from TFD

*(adj) being or acting in accordance with the principles of government analyzed in Machiavelli's The Prince, in which political expediency is placed above morality.

*(adj) characterized by unscrupulous cunning, deception, or expediency.

(noun) - a cunning, amoral, and opportunist person, esp a politician

References in literature::

*

*"In fact, moral courage, integrity, steadfastness, self-esteem, etc., are among the major disqualifications to survive in this field, which is a full-time risk-free business that requires Machiavellian approach."

*"This also applies to Machiavellian supervisors, who are characterized by behavior that is inherently manipulative and deceitful."

From Collins

If you describe someone as Machiavellian, you are critical of them because they often make clever and secret plans to achieve their aims and are not honest with people.


text:
Q: Is $\sum_{n=1}^\infty\frac{e^{\arctan(n)}}{n^2+1}$ convergent or divergent? I don't know how should I determine if this series is convergent or divergent.
$$\sum_{n=1}^\infty\frac{e^{\arctan(n)}}{n^2+1}$$
Any help would be appreciated.

A: It is convergent as arctan(x) for very large x, converges to $\frac{\pi}{2}$. Thus the series is bounded by $$e^{\frac{\pi}{2}}\sum\limits_{k=1}^{\infty}\frac{1}{k^2+1}$$ which is convergent.
To prove this consider $\sum\limits_{k=1}^{\infty}\frac{1}{k^2}$ and to prove that this converges, consider the integral $\int\limits_{1}^{\infty}\frac{1}{x^2}$ in relation to the sum.

A: Since $\arctan(x) < \frac{\pi}{2}$ for $x \ge 1$, we have that $e^{\arctan(n)} < e^{\pi/2}$ for $n \ge 1$.  Thus:
$$\sum_{n=1}^\infty\frac{e^{\arctan(n)}}{n^2+1}\le \sum_{n=1}^\infty\frac{e^{\pi/2}}{n^2+1} = e^{\pi/2}\sum_{n=1}^\infty\frac{1}{n^2+1}$$
Therefore, by comparison, the series...

A: How about using the integral test?
$$\int_1^\infty \frac{e^{\arctan x}}{x^2+1}$$
$$u=\arctan x,\;du=\frac{1}{x^2+1}$$
$$\int e^udu=e^u+C=e^{\arctan x}+C$$
$$\lim_{b\rightarrow\infty} e^{\arctan x}|_1^b=\lim_{b\rightarrow\infty}(e^{\arctan b}-e^{\arctan 1})=e^{\frac{\pi}{2}}-e^{\frac{\pi}{4}}$$
Since the integral converges, the series converges.

A: First note that this sum produces a monotonic sequence since all of its terms are non-negative so all that remains to show is that the sequence is bounded and that will imply convergence (Monotone Convergence Theorem). We can show it's bounded by comparing it to another series that is bounded. Since $\frac{-\pi}{2} \leq \arctan(n) \leq \frac{\pi}{2}$ you can see by comparison that since $\sum_{n=1}^{+\infty}{\frac{e^{\pi/2}}{n^2+1}}$ converges and $\arctan(n) \leq \frac{1}{n^2+1}$ for $1 \leq n \leq +\infty$ then it also converges.


text:
Q: How to read a value from an inputHidden using JSF/Javascript? I have a problem with my input in a form. I would like to get a value stored in an inputHidden but it doesn't work.
JSF Code :
<h:form id="testForm">
    <h:selectOneMenu id="list" ...>
               ....
    </h:selectOneMenu>
    <h:inputHidden id="codeShop" value="#{myBean.codeShop}" />
    <h:commandButton immediate="true" value="#{bundle.print}"
                        onclick="return test();"/>

JS Code :
function test(){
    var codeShop = document.getElementById("testForm:codeShop").value;
    var list = document.getElementById("testForm:list").value;
    ...
}

I succeed to get the selectOneMenu value but document.getElementById("testForm:codeShop") doesn't work.
Generated HTML output :
<input id="testForm:codeShop" type="hidden" name="testForm:codeShop"/>

I don't understand why my value is not in my inputHidden. Is this normal?
Thank you.

A: Use the code, as this is the correct code for getting value by Id.
function test(){
    var codeShop = document.getElementById("codeShop").value;
    var list = document.getElementById("list").value;
    ...
}


text:
Q: $A = B+ C$ then $(B^{-1} - A^{-1})$ and $(C^{-1} - A^{-1})$ are positive semidefinite Let $A$, $B$ and $C$ invertible and symmetric square real matrices of dimension $n$.
I want to show that if $A = B+ C$ then $(B^{-1} - A^{-1})$ and $(C^{-1} - A^{-1})$ are positive semidefinite.
For a bit of context, I came across this result when going over some material discussing efficiency of maximum likelihood estimators.

A: Let $A=-2I$, $B=C=-I$. Then $A=B+C$ but $B^{-1}-A^{-1}=-\frac{1}{2}I$ which is negative definite.
If $A, B, C$ were positive semidefinite then I think the claim is true by the following hint:
Hint: $$B(B^{-1}-A^{-1})A=A-B=C\implies T:=B^{-1}-A^{-1}=B^{-1}CA^{-1}.$$


text:
Q: Data Feeders implementation in Gatiling for RESTful webservices load testing I am working on implementing Gatling tool to load test few of our RESTful web API methods,
    for some reason I am not successful in parameterize my input data into the URI.
I am getting "i.g.h.a.AsyncHandlerActor" error..
it would be great if I'm able to see what exactly the end URI where the call was made.

below is my Scala code for one of the method to be load tested

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import java.util.concurrent.ThreadLocalRandom

class StockRun3 extends Simulation {

  val httpConf = http
    .baseURL("http://xxx.xxx.xx.xx:95/v9/stk")
    .acceptHeader("application/json")
    .authorizationHeader("appKeyToken=XXXXXXX&appKey=YYYYYYYYYY")

   object Search {
        val Datafeeder= csv("StockDataSource2.csv").random

        val search = feed(Datafeeder)
            .exec(http("Search")
            .get("/availability")
            .queryParam("""productIds""","""${product}""")
            .queryParam("""ocationIds""","""${store}""")
             )
            .pause(1)
    }

  val users = scenario("Users").exec(Search.search)

  setUp(
    users.inject(nothingFor(4 seconds),
    atOnceUsers(10),
    rampUsers(10) over(60 seconds),
    constantUsersPerSec(2) during(30 seconds))

  ).protocols(httpConf)
  }

A: As explained in the documentation, lower the logging level in logback.xml.
Then, you have a typo in "ocationIds" queryParam.


text:
Q: What will (getDirectoryFiles "" (dir > "//*.c")) actually match? I was experiencing unnecessary rebuilds while using this matching pattern:
getDirectoryFiles "" $ "foo" </> "//*.c"

I'm on Linux so from my understanding the second argument will evaluate to
"foo///*.c"

and I presume that it would be incorrect to replace this with
"foo" </> "/*.c"

as that would not work on windows? On Linux however this works as I expect it to.
From testing I concluded that the pattern matched files outside of "foo" which makes no sense in my world. As an example the pattern above would match both testA.c and testB.c in a directory structure like the one below.
foo/testA.c
bar/testB.c

I see now that there is a <//> operator, so maybe I should be using "foo" <//> "*.c" instead but still. This was quite nasty to find and what does "foo///*.c" actually do?

A: The problem is that the </> operator is defined so that:

"foo" </> "//*.c" == "//*.c"

That means that using </> to create a // value is almost never the right thing to do. <//> solves that, but as you note, it's not predictable and quite nasty.
The solution is using foo/**/*.c as an alternative pattern to foo//*.c. The advantage of the first form is that it is perfectly predictable and works well with </>, eliminating the need for <//>. Since Shake 0.15.6 that has been a permissible alternative, and in Shake 0.16 it will probably be recommended over //.
As to your other questions: 1) for Windows you can use either / or \ interchangeably in pattern values, so writing foo//*.c literally is just fine. 2) foo///*.c is equivalent to foo//*.c, and there are extensive test suites for such forms in Shake.


text:
Q: plupload pass values by upload url I am using plupload as an image upload script. I want to be able to save images on one folder or another, depending on a selected option from a . Something similar to...
<select id="dir">
    <option value="dir1">Option1</option>
    <option value="dir2">Option2</option>
</select>

The code for initializing the pluploader contains the url for the upload script:
url : "upload.php",

I would like to be able to pass the option values to upload.php, so I can the handle them with $_GET, something like:
url : "upload.php?d=" + dir,

I have tried using:
var element = document.getElementById("dir").selectedIndex;
var dir = document.getElementsByTagName("option")[element].value;

The javascript code:
<script type="text/javascript" language="javascript">
// Initialize the widget when the DOM is ready
$(function() {

    // Setup html5 version
    $("#uploader").pluploadQueue({
        // General settings
        runtimes : 'html5,flash,silverlight,html4',
        url : "../upload.php",

        chunk_size : '1mb',
        rename : true,
        dragdrop: true,

        filters : {
            // Maximum file size
            max_file_size : '10mb',
            // Specify what files to browse for
            mime_types: [
                {title : "Image files", extensions : "jpg,jpeg,gif,png"}
            ]
        },

        // Resize images on clientside if we can
        resize: {
            width : 800,
            height : 800,
            quality : 90,
            crop: false // crop to exact dimensions
        },

        // Flash settings
        flash_swf_url : '../js/Moxie.swf',

        // Silverlight settings
        silverlight_xap_url : '../js/Moxie.xap'
    });
});
</script>

But it always gets the first option value as it is initialized on DOM ready...
How can I do this?

SOLVED with:
1) Add:
$(function() {
    $("#uploader").pluploadQueue({ //...
        multipart: true,
        multipart_params: { 'dir': '' }, //...

2) Add:
var uploader = $('#uploader').pluploadQueue();
    uploader.bind('FilesAdded', function(up, files) {

    var element = document.getElementById("dir").selectedIndex;
    var dir = document.getElementsByTagName("option")[element].value;

    uploader.settings.multipart_params.dir = dir;
});

Source: http://williamjxj.wordpress.com/2011/03/25/jquery-plugin-plupload-for-multi-files-upload/

A: I don't have a way to test this, but it looks like you can catch a BeforeUpload event and make changes there:
var uploader = $("#uploader").pluploadQueue({
  // ...
});

uploader.bind("BeforeUpload", function() {
  var element = document.getElementById("dir").selectedIndex;
  var dir = document.getElementsByTagName("option")[element].value;
  uploader.settings.url = "upload.php?d=" + dir;
});


text:
Q: Axis2 Web Service client fails AxisFault: Address already in use: NET_Bind I am developping a web service using Axis 2 and tomcat maven plugin (launched with Eclipse embedded Maven).
For testing purpose, I developped a web service client using AXIOM.
When I run the client on my system (Windows 7 Pro), I got various behavior, most of them failures :
org.apache.axis2.AxisFault: Address already in use: NET_Bind
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:197)
    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
    at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
    at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)
    at com.nm.bdl.Launcher.main(Launcher.java:82)
Caused by: java.net.BindException: Address already in use: NET_Bind
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:398)
    at java.net.Socket.bind(Socket.java:582)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:615)
    at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:139)
    at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:125)
    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
    ... 10 more

A very few cases, the client program succeeds reaching the web service.
The web service and the client programs are working fine, I tested both on others computers (still Windows 7 Pro). It also works when I run the web service client from another computer with success.
Here is the definition of tomcat plugin in the pom.xml :
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>tomcat-maven-plugin</artifactId>
    <dependencies>
      <dependency>
          <groupId>jaxen</groupId>
          <artifactId>jaxen</artifactId>
          <version>full</version>
      </dependency>
    </dependencies>
    <configuration>
      <server>tomcat-development-server</server>
        <port>9966</port>
        <path>/</path>
        <systemProperties>
            <logs.dir>logs</logs.dir>
        </systemProperties>
        <useNaming>true</useNaming>
        <contextFile>${basedir}/src/test/resources/tomcatconf/context.xml</contextFile>
        <!--
        <configurationDir>${basedir}/src/main/tomcatconf</configurationDir>
         -->
    </configuration>
    <executions>
      <execution>
        <id>run-tomcat</id>
        <phase>pre-integration-test</phase>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

The web service client program :
  static String address_WS   = "http://localhost:9966/services/GetGedFile";

  /**
   * @param args
   */
  public static void main(String[] args) {

    final EndpointReference targetService = new EndpointReference(address_WS);

    /* ... */

    try {
      Options options = new Options();

      ServiceClient client = new ServiceClient();
      options.setTo(targetService);
      options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
      options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true");
      options.setTimeOutInMilliSeconds(360000);

      client.setOptions(options);

      OMElement result = client.sendReceive(serviceOp);

      String response = result.getFirstElement().getText();
      System.err.println("WS call result: " + response);

      OMNode node = result.getFirstElement().getFirstOMChild();
      if (node instanceof OMText) {
        OMText txt = (OMText) node;

        String data = txt.getText();
        byte[] dataBytes = Base64.decode(data);

        String realString = new String(dataBytes,"UTF-8");
        System.out.println("pseudo binary data received : " + realString);
      }

    } catch(AxisFault af) {
      af.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

I have tried to clean windows services, to stop the antivirus, to use other ports (different from port 9966), replace localhost by the IP adress : in vain.
I have monitored my system with TCPView to check that axis web service uses same port as configured in the tomcat plugin.
Any other idea please ?
EDIT: another error stacktrace
log4j:WARN No appenders could be found for logger (org.apache.axis2.context.AbstractContext).
log4j:WARN Please initialize the log4j system properly.
org.apache.axis2.AxisFault: com.ctc.wstx.exc.WstxIOException: Unrecognized Windows Sockets error: -1: socket available
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:123)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:67)
    at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:354)
    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
    at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
    at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)
    at com.nm.bdl.Launcher.main(Launcher.java:82)
Caused by: org.apache.axiom.om.OMException: com.ctc.wstx.exc.WstxIOException: Unrecognized Windows Sockets error: -1: socket available
    at org.apache.axiom.om.impl.llom.factory.AbstractOMMetaFactory.createXMLStreamReader(AbstractOMMetaFactory.java:63)
    at org.apache.axiom.om.impl.llom.factory.AbstractOMMetaFactory.createSOAPModelBuilder(AbstractOMMetaFactory.java:129)
    at org.apache.axiom.om.OMXMLBuilderFactory.createSOAPModelBuilder(OMXMLBuilderFactory.java:426)
    at org.apache.axiom.om.OMXMLBuilderFactory.createSOAPModelBuilder(OMXMLBuilderFactory.java:405)
    at org.apache.axis2.builder.SOAPBuilder.processDocument(SOAPBuilder.java:55)
    at org.apache.axis2.transport.TransportUtils.createDocumentElement(TransportUtils.java:179)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:145)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:108)
    ... 8 more
Caused by: com.ctc.wstx.exc.WstxIOException: Unrecognized Windows Sockets error: -1: socket available
    at com.ctc.wstx.stax.WstxInputFactory.doCreateSR(WstxInputFactory.java:548)
    at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:604)
    at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:629)
    at com.ctc.wstx.stax.WstxInputFactory.createXMLStreamReader(WstxInputFactory.java:324)
    at org.apache.axiom.util.stax.wrapper.XMLInputFactoryWrapper.createXMLStreamReader(XMLInputFactoryWrapper.java:95)
    at org.apache.axiom.util.stax.wrapper.WrappingXMLInputFactory.createXMLStreamReader(WrappingXMLInputFactory.java:116)
    at org.apache.axiom.util.stax.wrapper.XMLInputFactoryWrapper.createXMLStreamReader(XMLInputFactoryWrapper.java:95)
    at org.apache.axiom.util.stax.wrapper.WrappingXMLInputFactory.createXMLStreamReader(WrappingXMLInputFactory.java:116)
    at org.apache.axiom.util.stax.wrapper.XMLInputFactoryWrapper.createXMLStreamReader(XMLInputFactoryWrapper.java:95)
    at org.apache.axiom.om.util.StAXUtils$1.run(StAXUtils.java:201)
    at java.security.AccessController.doPrivileged(AccessController.java:241)
    at org.apache.axiom.om.util.StAXUtils.createXMLStreamReader(StAXUtils.java:197)
    at org.apache.axiom.om.impl.llom.factory.AbstractOMMetaFactory.createXMLStreamReader(AbstractOMMetaFactory.java:55)
    ... 15 more
Caused by: java.net.SocketException: Unrecognized Windows Sockets error: -1: socket available
    at java.net.PlainSocketImpl.socketAvailable(Native Method)
    at java.net.PlainSocketImpl.available(PlainSocketImpl.java:487)
    at java.net.SocketInputStream.available(SocketInputStream.java:246)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:332)
    at org.apache.commons.httpclient.WireLogInputStream.read(WireLogInputStream.java:69)
    at org.apache.commons.httpclient.ChunkedInputStream.read(ChunkedInputStream.java:182)
    at java.io.FilterInputStream.read(FilterInputStream.java:134)
    at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:108)
    at java.io.FilterInputStream.read(FilterInputStream.java:134)
    at org.apache.axiom.om.util.DetachableInputStream.read(DetachableInputStream.java:147)
    at java.io.FilterInputStream.read(FilterInputStream.java:134)
    at java.io.PushbackInputStream.read(PushbackInputStream.java:182)
    at java.io.FilterInputStream.read(FilterInputStream.java:113)
    at com.ctc.wstx.io.UTF8Reader.loadMore(UTF8Reader.java:365)
    at com.ctc.wstx.io.UTF8Reader.read(UTF8Reader.java:110)
    at com.ctc.wstx.io.ReaderBootstrapper.initialLoad(ReaderBootstrapper.java:245)
    at com.ctc.wstx.io.ReaderBootstrapper.bootstrapInput(ReaderBootstrapper.java:132)
    at com.ctc.wstx.stax.WstxInputFactory.doCreateSR(WstxInputFactory.java:543)
    ... 27 more

A: My problem is solved by changing the java runtime of the client program.
I was using IBM Jdk 5 (which is a requirement for the web service server) and I switched to standard Jre 6.


text:
Q: java synchronized bank account transfer I tried to write synchronized code for the classic problem of BankAccount transfer. Now I am trying to figure out the problem with the solution. In any solution that I found on the web the transfer method used two locks but I did not use any.
    class BankAccount
    {
      double balance;

      public void synchronized deposit(double amount)
      {
          balance+=amount;
       }

      public void synchronized withdraw(double amount)
      {
         balance-=amount;
      }

      public void transferTo(BankAccount b, double amount)
      {
           this.withdraw(amount);
           b.deposit(amount);

       }
   }

Please tell me what could be the problem with transferTo(). Please excuse leaving out the limit checking on balance. I am actually concerned about whether not making the transferTo atomic would cause problems (deadlocks). An example of such a situation would be great.

A: Apart from the use of double, I don't see any particular problems, though you have to keep in mind that transferTo not being atomic may cause issues later. However, you are in fact using locks. Each synchronized method implicitly uses a lock.

A: You are using intrinsic lock.

A: You are using locks as soon as you put synchronized block in place. In this case the lock will be acquired over the class object which is under modification and this is the reason your code would be working fine.
But your transferTo method might not work correctly as both operations inside this are synchronized but not the whole transaction.
Hope this helps!!!


text:
Q: How to use Wobly serializer on Android I'm looking for the alternatives to serialize objects in my Android project. I found Wobly which seem to be fast and small. I understand how to create Wobly wrappers using WoblyImpl but I'm totally confused with how to write/read these objects from the file system? When to run WoblyGenerator and can it be done within my code? Can someone post a code example?

A: Wobly doesn't support unknown Object fields. So fields like:
Object a;
List<Object> b;
Map<Integer, Object> c;

cannot be serialized with Wobly.
It supports all primitive classes (and their boxed counterparts), all Wobly classes, any Array/List/Map combination of the above.
So in your case, problem is that JSONArray implements List<Object>. If you know what kind of object JSONArray holds, for example List<Map<Integer, String>>, you can write:
class Example extends WoblyImpl {
  @WoblyField(id = 0)
  List<Map<Integer, String>> array;

  public void setArray(JSONArray json) {
    array = (List)json;
  }
}

Though after deserialization you will get ArrayList<HashMap<Integer,String>> and not JSONArray back.
If you don't know what object JSONArray is holding, it would be painful to make it work with Wobly, if at all possible. You can check out comprehensive comparison of serialization libraries here:
https://github.com/eishay/jvm-serializers/wiki

A: OK, I got it. If you wondered here and want to know how to do it here are the steps:

*

*Create your class by extending WoblyImpl and annotate the fields according to the instructions

*Then run WoblyGenerator.updateSourceFolder("c:/foo/src"); where the parameter is directory containing your file (or package). I created a small project in Eclipse for that but you can also run this from the command line using supplied wobly-generator.jar

*This step will inject serialization code into your source file which will include read and write methods

*Gotcha: this didn't work for smart-json JSONObject or JSONArray or for HashMap. The error I got is this:
java.lang.IllegalArgumentException: next type for class net.minidev.json.JSONObject of  index 0, class java.lang.Class
at  com.wowd.wobly.generation.WoblyGeneratorUtils.extractNextType(WoblyGeneratorUtils.java:91)
at   com.wowd.wobly.generation.types.impl.MapTypeCodeGenerator.defaultTypeFormat(MapTypeCodeGenerator.java:163)
at com.wowd.wobly.generation.types.TypeCodeHandler.defaultTypeFormat(TypeCodeHandler.java:121)
at com.wowd.wobly.generation.WoblyGeneratorUtils.adjusFormatForCompressed(WoblyGeneratorUtils.java:317)
at com.wowd.wobly.generation.WoblyCodeGenerator.generateWriteFieldCode(WoblyCodeGenerator.java:178)
at com.wowd.wobly.generation.WoblyCodeGenerator.generateWriteMethod(WoblyCodeGenerator.java:270)
at com.wowd.wobly.generation.WoblyCodeGenerator.generateFieldsAndMethods(WoblyCodeGenerator.java:647)
at com.wowd.wobly.generation.WoblyCodeGenerator.generateRegularCode(WoblyCodeGenerator.java:721)
at com.wowd.wobly.generation.WoblyCodeGenerator.generateCode(WoblyCodeGenerator.java:677)
at com.wowd.wobly.updater.GenerateAndReplace.update(GenerateAndReplace.java:130)
at com.wowd.wobly.updater.GenerateAndReplace$1.execute(GenerateAndReplace.java:198)
at com.wowd.wobly.updater.GenerateAndReplace$1.execute(GenerateAndReplace.java:1)
at com.wowd.common.functions.impl.FilterProcedure.execute(FilterProcedure.java:40)
at com.wowd.wobly.updater.SourceFilesVisitor.visitDir(SourceFilesVisitor.java:69)
at com.wowd.wobly.updater.SourceFilesVisitor.visitDir(SourceFilesVisitor.java:60)
at com.wowd.wobly.updater.SourceFilesVisitor.visitDir(SourceFilesVisitor.java:60)
at com.wowd.wobly.updater.SourceFilesVisitor.visitDir(SourceFilesVisitor.java:60)
at com.wowd.wobly.updater.SourceFilesVisitor.visitPackage(SourceFilesVisitor.java:38)
at com.wowd.wobly.updater.GenerateAndReplace.updateInPackage(GenerateAndReplace.java:190)    WoblyParcel                             error

at com.wowd.wobly.WoblyGenerator.updatePackage(WoblyGenerator.java:60)
at com.wowd.wobly.WoblyGenerator.updateSourceFolder(WoblyGenerator.java:49)
at Generator.main(Generator.java:19)

If someone can tell me how to fix that - post it as a separate answer and I'll accept it


text:
Q: Change SELECT-OPTIONS text programmatically I'm trying to replace the selection-option name when it's showed in the screen by using abap code. not the "Goto->Text Elements->Selection Text".
If there is any kind of solution with you please share with me.
Thank you in advance,

A: I found the answer.. :) :) :)

 INITIALIZATION.
 %_name_%_app_%-text = 'Carrier ID'.


text:
Q: Listbox RemoveAt Method Causing AutoScroll Nutshell: How can I disable the auto-scroll back to the top of a ListBox when I call RemoveAt(0)?
Background:
I have a simple list box that I mash full of data at regular intervals.
Basically I'm using it is a status reporting tool.
Every iteration of my program causes 100 or so lines of data to be thrown into the listbox and the best way to dump piles of information in is by always adding it to the bottom.
I want newest results to be at the bottom, and the oldest results to be "pushed up". Because the size of this listbox becomes rather large after a short period of time I limit the size to 1000 items.
When the box gets more than 1000 items, I use RemoveAt(0) till I get 1000 items again.
To always display the most relevant information I scroll the listbox all the way down. The problem with this is that whenever I call RemoveAt(0), the box is auto-scrolled back up to the new item 0. Basically, every time I add items to a "full" list box, the effect is a quick scroll up 1000 items, then back down 1000 items, making for a clumsy looking display.
How can I disable the auto-scroll back to the top of a ListBox when I call RemoveAt(0)?

A: This will only happen when there is no selected item.  Or in other words, ListBox.SelectedIndex = -1.  The simple workaround is to select an item.  Like the last one.

A: I can't answer your question. Even if I knew the technology, I might not have an answer that would fulfill your needs. Part of the issue is you are asking "help me solve this in the way I am trying to solve it" rather than "here is the business problem, what is the best solution".
My advice: Go back to the core problem, which sounds like "I need a way of updating a 'list' with new events while keeping the list to 1000 items or less". From this, you have a solution of a ListBox appended to bottom and cleared from top as your solution. And, I am not sure how to turn off scrolling in your solution, but I am not convinced it is the only way to solve the business problem.
Broken down, there are a few questions to answer:

*

*How do I bind/update the data?

*How do I keep the control from scrolling to a new position when I change the number of items bound?

As far as binding, the programatic addition is one option, whether you add from bottom and prune top or add to top and prune bottom. Another is to assemble the data and rebind. I would imagine there are others.
The scrolling problem is not really a scrolling problem as much as a "remember what I am looking at" problem or a "always display newest" problem. If always display newest, you need to figure out a way to make sure you are at the end when something is added or removed. If user can change position, you need to have a means of storing where he is and getting back to that position. You have added some complexity, as your list can be 1 to 1000 items long, so scroll position, except always at bottom, is dicey, unless you work in percentages. Regardless of whether turning off scrolling solves the immediate problem, if there is a business requirement to remember the user's position, you should have a check step after data is updated.
As a last suggestion, look at how other people have solved the problem of displaying streaming data. Following a well-known pattern is a good idea, as it gives the user a familiar interface. Often, with streaming data, the stream has a very small set of lines (enough to fill a screen, not 1000), but allows you to go back and look at previous "logged" events, if needed. Once again, I am not sure your solution requires a streaming type solution, but you still should go back to the core business problem and start from there.


text:
Q: QProcess dies for no obvious reason While coding a seemingly simple part of a Qt application that would run a subprocess and read data from its standard output, I have stumbled upon a problem that has me really puzzled. The application should read blocks of data (raw video frames) from the subprocess and process them as they arrive:

*

*start a QProcess

*gather data until there is enough for one frame

*process the frame

*return to step 2

The idea was to implement the processing loop using signals and slots – this might look silly in the simple, stripped-down example that I provide below, but seemed entirely reasonable within the framework of the original application. So here we go:
app::app() {
  process.start("cat /dev/zero");
  buffer = new char[frameLength];
  connect(this, SIGNAL(wantNewFrame()), SLOT(readFrame()), Qt::QueuedConnection);
  connect(this, SIGNAL(frameReady()), SLOT(frameHandler()), Qt::QueuedConnection);
  emit wantNewFrame();
}

I start here a trivial process (cat /dev/zero) so that we can be confident that it will not run out of data. I also make two connections: one starts the reading when a frame is needed and the other calls a data handling function upon the arrival of a frame. Note that this trivial example runs in a single thread so the connections are made to be of the queued type to avoid infinite recursion. The wantNewFrame() signal initiates the acquisition of the first frame; it gets handled when the control returns to the event loop.
bool app::readFrame() {
  qint64 bytesNeeded = frameLength;
  qint64 bytesRead = 0;
  char* ptr = buffer;
  while (bytesNeeded > 0) {
    process.waitForReadyRead();
    bytesRead = process.read(ptr, bytesNeeded);
    if (bytesRead == -1) {
      qDebug() << "process state" << process.state();
      qDebug() << "process error" << process.error();
      qDebug() << "QIODevice error" << process.errorString();
      QCoreApplication::quit();
      break;
    }
    ptr += bytesRead;
    bytesNeeded -= bytesRead;
  }
  if (bytesNeeded == 0) {
    emit frameReady();
    return true;
  } else
    return false;
}

Reading the frame: basically, I just stuff the data into a buffer as it arrives. The frameReady() signal at the end announces that the frame is ready and in turn causes the data handling function to run.
void app::frameHandler() {
  static qint64 frameno = 0;
  qDebug() << "frame" << frameno++;
  emit wantNewFrame();
}

A trivial data processor: it just counts the frames. When it is done, it emits wantNewFrame() to start the reading cycle anew.
This is it. For completeness, I'll also post the header file and main() here.
app.h:
#include <QDebug>
#include <QCoreApplication>
#include <QProcess>

class app : public QObject
{
Q_OBJECT
public:
  app();
  ~app() { delete[] buffer; }

signals:
  void wantNewFrame();
  void frameReady();

public slots:
  bool readFrame();
  void frameHandler();

private:
  static const quint64 frameLength = 614400;
  QProcess process;
  char* buffer;
};

main.cpp:
#include "app.h"

int main(int argc, char** argv)
{
    QCoreApplication coreapp(argc, argv);
    app foo;
    return coreapp.exec();
}

And now for the bizarre part. This program processes a random number of frames just fine (I've seen anything from fifteen to more than thousand) but eventually stops and complains that the QProcess had crashed:
$ ./app
frame 1
...
frame 245
frame 246
frame 247
process state 0
process error 1
QIODevice error "Process crashed"

Process state 0 means "not running" and process error 1 means "crashed". I investigated into it and found out that the child process receives a SIGPIPE – i.e., the parent had closed the pipe on it. But I have absolutely no idea of where and why this happens. Does anybody else?

A: The code is a bit weird looking (not using the readyRead signal and instead relying on delayed signals/slots). As you pointed out in the discussion, you've already seen the thread on the qt-interest ML where I asked about a similar problem. I've just realized that I, too, used the QueuedConnection at that time. I cannot explain why it is wrong -- the queued signals "should work", in my opinion. A blind shot is that the invokeMethod which is used by the Qt's implementation somehow races with your signal delivery so that you empty your read buffer before Qt gets a chance to process the data. This would mean that Qt will ultimately read zero bytes and (correctly) interpret that as an EOF, closing the pipe.
I cannot find the referenced "Qt task 217111" anymore, but there is a couple of reports in their Jira about waitForReadyRead not working as users expect, see e.g. QTBUG-9529.
I'd bring this to the Qt's "interest" mailing list anmd stay clear of the waitFor... family of methods. I agree that their documentation deserves updating.


text:
Q: Why is a tangent function being used to find horizontal length? Problem:
Why does the tangent function $175\tan(\theta)$ give us the horizontal length between either anchor 1 or 2 and the base? Doesn't tangent just give us the slope of the terminal ray, whereas sine and cosine gives us vertical and horizontal lengths? I don't understand why this solution works.

A:
Doesn't tangent just give us the slope of the terminal ray, whereas sine and cosine gives us vertical and horizontal lengths?

Actually, no. Observe the ratio.
$$\tan{\alpha}=\frac{opposite}{adjacent}$$
Note that the opposite side in this case is the horizontal distance while the adjacent distance is the length of the pole, 175ft. Hence, this becomes:
$$\tan{\alpha}=\frac{opposite}{175}$$
Therefore, $$opposite=175\tan{\alpha}$$


text:
Q: Spring MVC: Deserialise query parameters to POJO using Jackson objectMapper Spring web application configuration contains Jackson ObjectMapper configured like this
  objectMapper.disable(ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
  objectMapper.registerModule(new JavaTimeModule())

JavaTimeModule is added to handle deserialisation of ZonedDateTime. There are two endpoint which handle a POJO which contains ZonedDateTime. The POJO is like this:
class MyRequest {
  ZonedDateTime from
  ZonedDateTime to
}

and controller with endpoints is:
@Slf4j
@RestController
class MyController {

  @GetMapping('/pojo')
  void getPojo(MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }

  @PostMapping('/pojo')
  void postPojo(@RequestBody MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }
}

When I send POST /pojo with body
{"from": "2017-03-15T00:00:00Z", "to": "2017-03-16T00:00:00Z"}

The response is 200 and deserialisation is successful.
Contrary, when I send
GET /pojo?from=2017-03-15T00:00:00Z&to=2017-03-15T00:00:00Z

The 400 Bad Request is received with error
Failed to convert from type [java.lang.String] to type [java.time.ZonedDateTime] for value '2017-03-15T00:00:00Z'

This make sense, since in GET request, I'm not sending JSON and therefore JSON object mapper is not called.
Is there a way to use objectMapper for GET requests also, so query parameters are converted into POJO object?
By the way, I know that it can be deserialised for GET endpoint like below, but I want to use same converter for GET and POST endpoint
@DateTimeFormat(iso = ISO.DATE_TIME)
ZonedDateTime from
@DateTimeFormat(iso = ISO.DATE_TIME)
ZonedDateTime to

A: Injecting objectMapper and converting query parameters map into object solves the problem
@Slf4j
@RestController
class MyController {

  @Autowired
  private ObjectMapper objectMapper

  @GetMapping('/pojo')
  void getPojo(@RequestParam Map<String, String> allRequestParams) {
    MyRequest request = objectMapper.convertValue(allRequestParams, MyRequest)
    log.debug("Request received: $myRequest")
  }
...


text:
Q: Subtract days or years from new java.text.SimpleDateFormat Application:  SoapUI XML Resquest
I could swear this worked at one time where I use the below:
${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )}

To Subtract or Add I would add enclose the -# or +# like so:
 ${=${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )}-1

The result of the -1 is showing up as 1982
QUESTIONS:

*

*Why is it taking away the -MM-dd part?

*Why is it subtracting 23 years for -1
GOAL:
To be able to subtract from sysdate and the request show in yyyy-MM-dd format
i.e. if I want someone to be 65 years old - i want to subtract from sysdate to get that.
Again this is a SoapUI tag I'm populating the expression in.

A: You have the brackets misplaced! Let me break it down for you:
def yesterday = new Date() - 1
def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd")
def yesterdayFormatted = sdf.format(yesterday)

If you want it in a SoapUI property one liner:
${=new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date() - 1)}

Note that you can achieve the exact same thing with (slightly more compact):
${=String.format('%tF', new Date() - 1)}

Docs for the formatter.


text:
Q: Add a second domain to Active Directory on Windows Server 2008 is there a way to add a second domain to an Active Directory installation? We are buying one of our partner companies, and want to migrate their users into our AD into a new domain. Buying another Windows Server to create a new DC is not an option.
Thanks in advance!

A: If you're asking if it's possible to have a single server act as a domain controller for two AD domains, then.. no
Depending on the resources of the server, you could look at installing the Hyper-V role and create a new virtual DC for the new domain.

A: A single Domain Controller cannot provide directory services for more than one domain. You will need at least one additional domain controller. It can be physical or virtual, but it has to exist separately.

A: You have basically two options here: keep their domain alive and create a trust relationship between it and your own, in order to let the two domains share users and resources, or migrate their users into your Active Directory and get rid of their domain altogether.
The first solution is a lot simpler, but requires keeping their domain around.
The second solution can be quite easy or a real pain, depending on some factors:

*

*How many users and computers do you need to migrate?

*Do they have servers (file, print, database...) to migrate, too?

*Do they have Exchange in their domain? Do you? If yes to both: do you need to migrate their mailboxes, too?

If the number of users/computers is high and Exchange is involved, you should try avoiding a domain migration, or hire someone who really knows what he's doing.
That said, if you really need to migrate their users and computers into your own Active Directory, you have two choices here, too:

*

*Migrate them into your domain (possibly in their own OU hierarchy).

*Create a new domain into your forest and migrate them into it.

The second option requires at least an additional domain controller (preferably two) for the new domain, because your existing one(s) can not provide domain services for two domains at the same time. Howewer, it is very rarely required to create an additional domain: a proper OU planning and administration delegation can definitely be enough for your needs.

A: If you're buying the company, I'm assuming you are buying their equipment as well, including their domain controllers. You should be able to set up a two-way forest trust between your domains so users from both companies can access each other's resources. This should be suitable for the time being while you plan a long-term domain migration strategy.

A: I'd also ask why you're wanting to use a separate domain under the same Forest.  Microsoft generally encourages you to accomplish what you want in terms of resource segregation, etc. though OUs and Group Policy.
If you're determined to kill their existing AD, I would look at migrating them into your existing domain, just with proper planning for the OUs.


text:
Q: Get data from db, java servlet Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method
    public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
    List<Dvd> dvds = new ArrayList<Dvd>();
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        connection = getConnection();
        preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
        preparedStatement.setString(1, user_id);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            Dvd dvd = new Dvd();
            dvd.setId(resultSet.getInt("id"));
            dvd.setUser_id(resultSet.getString("user_id"));
            dvd.setName(resultSet.getString("name"));
            dvd.setBorrower(resultSet.getString("borrower"));
            dvd.setMail(resultSet.getString("mail"));
            dvd.setBorrow_date(resultSet.getString("borrow_date"));
            dvd.setBorrow_until(resultSet.getString("borrow_until"));
            dvds.add(dvd);
        }

    } catch (SQLException e) {
        throw e;
    } finally {
        cleanUp(connection, preparedStatement);
    }

    return dvds;
}

and I don't know how to set up logged user id in servlet's doGet method:
dvds = this.dvdDao.getDvdsByUserId();

loginServlet
 public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private UserDao userDao;

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    DbSettings dbSettings = new DbSettings();

    dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
    dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
    dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
    dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
    dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));

    try {
        this.userDao = new UserDao(dbSettings);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Unable to initialize DB driver", e);
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        if (getLoggedUser(request, response) != null) {
            response.sendRedirect("/list");
            return;
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
        dispatcher.forward(request, response);
    } catch (Exception e) {
        getServletContext().log("error", e);
    }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        if (getLoggedUser(request, response) != null) {
            response.sendRedirect("/list");
            return;
        }
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("password");

        if (nickname != null && password != null) {
            User user = userDao.getByLogin(nickname);
            if (user != null && UserUtil.checkLogin(user, password)) {
                HttpSession session = request.getSession(true);
                Long userId = user.getId();
                session.setAttribute("userId", userId);
                session.setAttribute("loggedUser", user);
                request.getSession().setAttribute("nickname", nickname);

                response.sendRedirect("/list");
            } else {
                request.setAttribute("message", "Login se nepovedl.");
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
                dispatcher.forward(request, response);
            }
        } else {
            response.sendRedirect("/login");
        }
    } catch (Exception e) {
        getServletContext().log("error", e);
    }
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("loggedUser");
    return user;
}
}

Does anybody have an idea please?

A: According to my understand of your requirement first you validate whether username and password are matching then you pass the control to the servlet so on the request set the userid .Then you can acquire the userid in the doGet() method using the request.getParameter() method.

A: Get Logged User Id In Servlet Using Session.

HttpSession session=request.getSession(true);
session.setAttribute("user", userLoggedId);

Later You can retrieve Session Data :

HttpSession session=request.getSession(true);
String userId=(String)session.getAttribute("user");

A: This can be done in many ways.
I think you are using form because in servlet you are calling doget().So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");
The other way is to keep the user in session
After the login if you are calling any servlet or jsp page then keep the user there in session like this way
session.setAttribute("username","username");

and in the servlet you can retrieve by using
session.getAttribute("username");


text:
Q: linking a framework to project For example to add a framework to workspace
 steps involved are:
1.Right click on the framework
2.select the Framework and click on Add
it will link  the respective framework to project
is there any other method to add the framework to project

A: No. That's the preferred Apple way of doing it. Are you looking to do a different way for any specific reason?


text:
Q: get-itemproperty reporting item doesn't exist, when it does I am having some odd trouble getting a REG_SZ value using:
(get-itemproperty -Path "Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\VLC media player" -Name UninstallString).UninstallString
(get-itemproperty -Path "Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\VLC media player" -Name UninstallString).UninstallString

get-itemproperty : Cannot find path 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\VLC media player' because it
does not exist.
At line:1 char:2
+ (get-itemproperty -Path "Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (HKEY_LOCAL_MACH...LC media player:String) [Get-ItemProperty], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand

This method works for another REG_SZ without issue, but when I call for many keys below Uninstall it fails.
Specifically, it works with:
(get-itemproperty -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Command Processor" -Name autorun).AutoRun
Both data entries exist on my system as visible in regedit....
However, what is very interesting, they do not exist in the resultant of:
Get-ChildItem "Registry::HKEY_LOCAL_MACHINE\software\microsoft\windows\currentversion\uninstall\"

There are several more "missing" keys as well.  This seems like some odd registry namespace virtualization that I am not familiar with (similar to HKEY_CLASSES_ROOT)?

A: A forum thread lead me to the answer.
It discusses the virtualization of the registry for 32-bit and 64-bit programs.
In this case, since the key "is missing," additional paths must be checked (note that I should be checking for paths with test-path in a conditional before trying any "errorable" actions).
PS > (dir HKLM:\SOFTWARE\wow6432node\Microsoft\Windows\CurrentVersion\Uninstall | measure).count
134
PS > (dir hklm:\software\microsoft\windows\currentversion\uninstall | measure).count
134

So, I must be running 32-bit powershell.exe.
PS > [Environment]::Is64BitProcess
False

Also, HKEY_CLASSES_ROOT\Installer\Products is another location that lists programs installed with the Windows Installer.
This answer is helpful in regards to 32-bit vs. 64-bit powershell.exe.
The solution to this problem is robust.  I have modified the previously linked function a bit to make it more accessible.
P.S. I'm running Windows 7 on bootcamp on a macbook pro.  Oddly, regardless of the powershell.exe I execute, it is 32-bit.  I simply can not see the registry keys regardless of whether or not the location is beneath the wow6432node.


text:
Q: How fadeout element in dataTemplate when mouse clicked its containter? My idea throw always exception This code throw always exception. Is a way to get TextBox (x:Name = "MyBox") to hide (fadeout) when we click in its container (here ListViewItem)? What's wrong with my code?
 <ListView x:Name="ListViewMy" IsItemClickEnabled="True" ItemsSource="{Binding list, Mode=TwoWay}" HorizontalAlignment="Left" Height="223" Margin="240,350,0,0" VerticalAlignment="Top" Width="582" >
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <Grid x:Name="GridMy">
                                <ContentPresenter x:Name="MyContentPresenter">
                                    <ContentPresenter.ContentTemplate>
                                        <DataTemplate x:Key="DataTemplate">
                                            <Grid Background="#FF25C1D1" Margin="-30,0,0,0" x:Name="GridBlue">
                                                <TextBox x:Name="MyBox" HorizontalAlignment="Left" Margin="135,0,0,0" TextWrapping="Wrap" Text="{Binding}" VerticalAlignment="Top" Width="352" Height="81" Background="{x:Null}" BorderBrush="#FF25C1D1" FontFamily="Segoe WP Semibold" FontSize="32" FontWeight="Bold" Foreground="White"/>
                                            </Grid>
                                        </DataTemplate>
                                    </ContentPresenter.ContentTemplate>
                                </ContentPresenter>
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualState x:Name="Normal" />
                                        <VisualState x:Name="MouseOver"/>
                                        <VisualState x:Name="Pressed" >
                                            <Storyboard>
                                                <FadeOutThemeAnimation TargetName="MyBox" Duration="0:0:5"></FadeOutThemeAnimation>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Disabled" />
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>

A: The problem with your code is that your animation, in the ControlTemplate for ListViewItem, should only target other elements within the ControlTemplate for ListViewItem.  The DataTemplate won't work here because x:Name="MyBox" won't resolve.  DataTemplates are reusable pieces of UI so Name expansion is skipped on them.
A good way to achieve your scenario is to target the animation to the ContentPresenter that is in fact part of your ControlTemplate, i.e.:
<FadeOutThemeAnimation TargetName="MyContentPresenter" Duration="0:0:5" />


text:
Q: UFW firewall start up on ubuntu 14.04.3 On all 3 of my Ubuntu 14.04.3 workstations when restarted the UFW firewall is deactivated and has to be started manually sudo ufw enable. My UFW.conf is set to enable startup as follows:

# Set to yes to start on boot. If setting this remotely, be sure to add a rule
  # to allow your remote connection before starting ufw. Eg: 'ufw allow 22/tcp'
  ENABLED=yes

A: I know this was a while ago, but here is a solution.
(Duplicate of 14.04 missing "/etc/init.d/ufw"? my firewall never auto starts)
For the effort that went into figuring out the solution, the answer is surprisingly simple.
In /etc/init/ufw.conf:
1) Comment out lines 9 - 11
2) Insert after line 11: start on startup
Fixes the whole problem, including logging to /var/log/ufw.log.
Note
If you have iptables-persistent installed, you must disable it.
Move iptables-persistent out of /etc/init.d and rename all the symlinks in rc0.d-rcS.d by making the 1st letter (S or K) lower case.  (Or move them out.)


text:
Q: What is the correct way of implementing this custom priority_queue I want to build a priority queue of an object having three elements having my own comparator. I tried the following code but is showing error .

#include<bits/stdc++.h>
using namespace std;

class triplet {
    public:
        int data;
        int arr;
        int index;
};

bool compare( triplet x, triplet y ){

    if(x.data < y.data){
        return true;
    }
    else{
        return false;
    }
}

int main(){

 priority_queue<triplet,vector<triplet>,compare> pq1;

}

getting the following error
enter image description here

A: Comparison routines must return false if the two elements are equal, but your version returns true.
Try this instead
bool compare(triplet x, triplet y) {

    if (x.data < y.data) {
        return true;
    }
    else {
        return false;
    }
}

or to make it a little simpler like this
bool compare(triplet x, triplet y) {
    return x.data < y.data;
}

But the important point is < not <=.
EDIT
Your code also uses compare incorrectly. compare is not a type, so it's not a valid argument for the priority_queue template.
The type of compare is bool (*)(triplet, triplet) so the right way to do this is to use that type in the template and pass the actual comparison function to the constructor. Like this
priority_queue<triplet, vector<triplet>, bool (*)(triplet, triplet)> pq1(compare);

BTW normally you would do this by creating a comparison functor, not a function. It's a little cleaner that way (and potentially more efficient).


text:
Q: Button ControlTemplate - TextBlock narrows as more text added I am trying to make a Button ControlTemplate in which the the text will scale itself within the control. I have had some amount of success, but one issue is still plaguing me: The more text I add to the button, the narrower the TextBlock gets -- so the text doesn't span the width of the button. To illustrate:

And here is my template code:
    <Style
        x:Key="OptionButton"
        TargetType="{x:Type Button}">

    <Setter Property="BorderBrush" Value="{StaticResource WhiteBrush}" />
    <Setter Property="BorderThickness" Value="2" />
    <Setter Property="TextBlock.Foreground" Value="{StaticResource WhiteBrush}" />
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="MinWidth" Value="100" />
    <Setter Property="MinHeight" Value="75" />
    <Setter Property="Padding" Value="5,0,5,0" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Height="70">
                    <Rectangle
                        Width="{TemplateBinding Width}"
                        Height="{TemplateBinding Height}"
                        Stretch="Fill"
                        Fill="{TemplateBinding Background}"
                        Stroke="{TemplateBinding BorderBrush}"
                        StrokeThickness="1">
                        <Rectangle.Clip>
                            <RectangleGeometry Rect="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type Grid}}, Converter={StaticResource ButtonBackRectConverter}}" />
                        </Rectangle.Clip>
                    </Rectangle>
                    <Ellipse
                        Width="70"
                        Height="70"
                        Stretch="Fill"
                        HorizontalAlignment="Left"
                        Fill="{TemplateBinding Background}"
                        Stroke="{TemplateBinding BorderBrush}"
                        StrokeThickness="1">
                        <Ellipse.Clip>
                            <RectangleGeometry Rect="0,0,35,70" />
                        </Ellipse.Clip>
                    </Ellipse>
                    <Ellipse
                        Width="70"
                        Height="70"
                        Stretch="Fill"
                        HorizontalAlignment="Right"
                        Fill="{TemplateBinding Background}"
                        Stroke="{TemplateBinding BorderBrush}"
                        StrokeThickness="1">
                        <Ellipse.Clip>
                            <RectangleGeometry Rect="35,0,35,70" />
                        </Ellipse.Clip>
                    </Ellipse>

                    <Viewbox
                        StretchDirection="DownOnly"
                        Stretch="Uniform">

                        <ContentPresenter
                            Name="ToastButtonContentPresenter"
                            TextBlock.Foreground="{TemplateBinding TextBlock.Foreground}"
                            Style="{StaticResource LargeText}"
                            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                            RecognizesAccessKey="True"
                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" >

                            <ContentPresenter.Resources>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="TextWrapping" Value="Wrap" />
                                    <Setter Property="Width" Value="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}" />
                                    <Setter Property="Padding" Value="5" />
                                    <Setter Property="TextAlignment" Value="Center" />
                                    <Setter Property="HorizontalAlignment" Value="Stretch" />
                                </Style>
                            </ContentPresenter.Resources>
                        </ContentPresenter>
                    </Viewbox>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Would greatly appreciate any guidance to help me solve this problem.

A: One idea can be to use a converter in width and height property of the button and pass the text length as parameter.
Based on the length you can write your logic and return a new length.

Width = "{Binding ButtonText, Converter={StaticResource
  TextToLengthConverter}, ConverterParameter=ButtonText}"

Above is only pseudo code. Try and let me know.


text:
Q: onClick php PHP Function then redirect I have a page full of links that go to pdf's I want to track which links are being clicked. I thought I could do something like follows but am having issues:
<?
    function track($link)
    {
    $sql = "UPDATE database WHERE something = 'something';
    $db = new connection();
    $result = $db->query($sql);

    if($result){
                  header( 'Location: http://mywebsite/docs/. $link .' ) ;
                }
    }
?>

and my HTML would look like:
File Name

Ok it looks like I am just going to use the link to pass the file name to a php script and once that is done I will redirect the user to the pdf.

A: you are mixing JavaScript (client-site) with PHP (server-site) - will not work
It look like you want to count how many time pdfs are clicked (delivered) - consider other ways:

*

*check access log and count

*if your PDF is created by script - make update before created

*execute AJAX request onclick which will update your database

A: As mentioned by others you are mixing client side code (the browser code) with the server side code (php). You need to change the html to be
File Name

You then need to create a php script to handle the request. For example redirector.php could look like this:
<?php
function track($link) {
    $sql = "UPDATE database WHERE something = 'something'";
    $db = new connection();
    $result = $db->query($sql);
    if ($result) {
        header('Location: http://mywebsite/docs/' . $link);
        exit;
    }
}

if (isset($_GET['file'])) {
     track($_GET['file']);
}

A: Try using the href attribute instead of onClick() which is for javascript

A: you are missing a double quote after 'something' you can't call php function like that after the page is rendered. Go with ajax or a GET/POST to your php script

A: you should try with jquery ajax
File Name

in update.php
<?php

$link=$_GET['link'];
 $sql = "UPDATE database WHERE something = 'something'";
    $db = new connection();
    $result = $db->query($sql);

    if($result){
        echo "DONE";
    }

?>


text:
Q: Use topojson to project shapefiles with different extents I have US Census shapefiles for each decade from 1790 to 1860. Because the US grew, the extents of these shapefiles are different. Using ogrinfo -so -al here is the extent for 1790, Extent: (-94.732708, 30.355644) - (-66.949831, 48.999992), and for 1860, Extent: (-124.762578, 24.521051) - (-66.949831, 49.384358).
I want to use topojson's --projection flag to project these to screen coordinates. Running this command works for each of the files:
topojson -o us_1790.json --simplify-proportion 0.10 \
  --projection 'd3.geo.albers()' \
  --width 960 \
  --height 500 \
  --margin 10 \
  -- shp/epsg4326/county_1790.shp

And I can then display the maps in d3. The difficulty is that each of the maps of the US is centered, which means that the map of the US in 1790 does not line up with the map for 1860, and so on. Here's what I mean:

I've tried using the --bbox flag and setting a bounding box to the extent in 1860, but that doesn't work. I've also tried searching for a way to set the extent with ogr2ogr.
If need be I can do the projection in the browser, but I'd prefer to pre-project them so that the map is as speedy as possible. What should I do?

A: Don't use --width and --height; specify the projection's scale and translate instead, and you'll get a fixed projection that will be the same for all inputs. In fact, since the default d3.geo.albers scale and translate is designed to fit in a 960×500 viewport, you can simply say:
topojson \
  -o us_1790.json \
  --simplify-proportion 0.10 \
  --projection 'd3.geo.albers()' \
  -- shp/epsg4326/county_1790.shp


text:
Q: while upgrading tensorflow to gpu version , it thowrs PermissionError
Exception: Traceback (most recent call last):   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pip\basecommand.py", line
  215, in main
      status = self.run(options, args)   File "C:\ProgramData\Anaconda3\lib\site-packages\pip\commands\install.py",
  line 342, in run
      prefix=options.prefix_path,   File "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_set.py", line
  784, in install
      **kwargs   File "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_install.py",
  line 851, in install
      self.move_wheel_files(self.source_dir, root=root, prefix=prefix)   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pip\req\req_install.py",
  line 1064, in move_wheel_files
      isolated=self.isolated,   File "C:\ProgramData\Anaconda3\lib\site-packages\pip\wheel.py", line 345,
  in move_wheel_files
      clobber(source, lib_dir, True)   File "C:\ProgramData\Anaconda3\lib\site-packages\pip\wheel.py", line 323,
  in clobber
      shutil.copyfile(srcfile, destfile)   File "C:\ProgramData\Anaconda3\lib\shutil.py", line 115, in copyfile
      with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied:
  'C:\ProgramData\Anaconda3\Lib\site-packages\wheel\archive.py'

A: Yea I think I had the same experience. Most likely you had tensorflow activated. Make sure you close all applications that use tensorflow and then upgrade.
EDIT: This is from personal experience. My advice may or may not work however I do want to make it clear that it is not an answer but merely a suggestion.


text:
Q: $\lnot\exists x(S(x) \Rightarrow R(x))$ VS $\forall x(S(x) \Rightarrow R(x))$ Without Using De Morgan's Law I was doing logic exercises the other day and I encountered the following:

Write this statement symbolically and verify your answer using De Morgan's Law:
No squares are rectangles

My solution:
Let $R(x): x$ is a rectangle and $S(x): x$ is a square. Now, we know none of the squares are rectangles; so in other words, there doesn't exist a square that's also a rectangle. I thought the following would be the its equivalent: $\lnot\exists x(S(x) \Rightarrow R(x))$ but I also thought, can't we say all squares are not rectangles and so I wrote the following:  $\forall x(S(x) \Rightarrow \lnot R(x))$ but using De Morgan's law, these two are obviously not equivalent and only the latter is right. Could you explain,without using De Morgan's Law, why the first statement is wrong?
Thanks in advance for any help!

A:
No squares are rectangles

is the same as "There is no object that is both a Square and a Rectangle".
Thus, in symbols :

$¬∃x(S(x) \land R(x))$;

This in turn is equivalent to :

$∀x(S(x) \to ¬R(x))$,

and this is exactly : "All squares are not rectangles".
The quantifiers equivalence : $\lnot \exists \equiv \forall \lnot$ is one of the most intuitive logical equivalence : if there is no Black swan, then all swans are not-Black (and vice versa).
The next step needs the propositional equivalence is : $\lnot (p \land q) \equiv (p \to \lnot q)$.

Let's start with : "All squares are not rectangles".
What about if there is an object $a$ that is a Triangle ? It is neither a Square nor a Rectangle, and thus $S(a) \to ¬R(a)$ is True ($\text F \to \text T = \text T$).
This means that the object $a$ does not contradict the formula $∀x(S(x) \to ¬R(x))$.
What happens with $¬∃x(S(x) \land R(x))$ ? We have that $S(a) \land R(a)$ is False, and thus we have no issue also with $¬∃x(S(x) \land R(x))$.
But what about $¬∃x(S(x) \to R(x))$ ?
We have that $S(a) \to R(a)$ is True, and thus the Triangle $a$ satisfy the formula $∃x(S(x) \to R(x))$.
This means that the existence of the Triangle $a$ contradicts the formula $¬∃x(S(x) \to R(x))$, and this means that this formula is not equivalent to : "All squares are not rectangles", and thus is not equivalent to "No squares are rectangles" either.

A: $S(x)\Rightarrow R(x)$ is always true when $S(x)$ is false, that is, when $x$ isn't a square. Therefore the statement $\neg \exists x (S(x)\Rightarrow R(x)) $ would imply, among other things, that there is no object which isn't a square. This is clearly not a conseqence of what you want to convey. As long as there exists object that isn't a square, its existance makes the statement $\neg \exists x (S(x)\Rightarrow R(x)) $ false, but it doesn't falsify the statement "no squares are rectangles".


text:
Q: Map data to table I am trying to map my data stored in  mongodb to a table in React
I have data stored in my database in the following way below in the link below:
https://drive.google.com/file/d/1g-kOjw5dp4ailubqPflI9_vuDLW82Awh/view?usp=sharing
I want the data to be mapped in the following way.

I have managed to bring the column headings dynamically, but I cannot figure out how to map the data to the table for each employee dynamically.

The code for the to bring the table headings dynamically is given below

            Employee ID
            {data.map((emp) => {
              return (

                  {emp.Date}

              );
            })}

            {data.map((emp) => {
              return (
                <>
                  Shift In
                  Shift Out
                  Actual In
                  Actual Out
                </>
              );
            })}

Please help me fill the data for the columns.


text:
Q: 15.10 won't upgrade to 16.04 due to unsupported packages I've been trying to upgrade my 15.10 installation to 16.04, but it says that it cannot upgrade due to unsupported packages, and I cannot find any of the packages that are conflicting to the upgrade.

A: I think you want to do a "package upgrade". I would recommen to make a "fresh install". Download the ISO-image, burn it to a DVD, reboot from the burned DVD and follow the installation programme. NOTE: PLEASE MAKE A BACKUB BEFORE INSTALLING, OTHERWISE YOU WHILL LOOSE YOUR DATA!


text:
Q: a good book to study the theory of Finite ellement methods I am dealing with elliptic PDE with dirichlet boundary condition,
In consequence of that, I started looking for a book that deals with Finite ellements method (FEM)
I am interested in a book oriented for mathematitians.
Do you suggest any?


text:
Q: How to link changing scroll offset variable to Animated variable in React native? The thing is that i have hierarchy of components. I have a parent component, child component and child's child component (for easier navigation through code). In the parent's component I have a ScrollView and a variable (not Animated variable) contentOffset (in parent's state), that is changing whenever the scroll happens. The variable interval is between [-100,100].
Parent's component
 constructor(props) {
 super(props);
 this.state = {
   contentOffset: 1
 }
 this.onScrollEvent = this.onScrollEvent.bind(this);
 }

 onScrollEvent = event => {
 this.setState(
   {
     contentOffset: event.nativeEvent.contentOffset.y,
   }
 )
 }
 render() {
    return (
    <ScrollView
     showsVerticalScrollIndicator={false}
     onScroll={this.onScrollEvent.bind(this)>
        <ChildOne
           animation={this.state.contentOffset}/>
    );
  }

Child component
  constructor(props) {
      super(props);
  }
  render() {
     return (
     <NestedChild
              handleClick={this.openSettingsInHeader}
              header="What the..."
              transformAnimation={this.props.animation}/>
     );
   }

Child's child component
   constructor(props) {
       super(props);
       this.state = {
           AnimatedTextValue: new Animated.Value(0),
           ProfileOffset: this.props.transformAnimation
       }
   }

   render() {

      const animatedStyles = {
           transform: [
             { scale: this.props.transformAnimation }]} <== if I'll pass it here the scale would be huge [-100,100], so we need to interpolate this, but the variable that's passed through props is not animated value and .interpolate function is not working
      return (
      <Animated.Text style={[styles.nameStyle,animatedStyles]}>Hi</Animated.Text>
      );
    }

I pass the contentOffset variable as prop to child component and then to child's child component . If I'll use the code, the scale interval will be the same [-100,100] (and the text would be scaled as much so that we couldn't see it).
For this, in React Native we have function .interpolate in Animated lib that takes the input interval and gives the output (so when the contentOffset is -100 we will scale down/up for example only on 4 points, not on 100.
But we can't pass the contentOffset variable, because it's not Animated.Value
This is the right code for interpolation and it would work, but the AnimatedTextValue from Child's child component is not linked with the
contentOffset variable from parent's state
  const headerTranslate = this.state.AnimatedTextValue.interpolate({
  inputRange: [-100, 100],
  outputRange: [4,-4],
  extrapolate: 'clamp'
});

How can we link this variable to Child's child Animated.Value?

A: Why not make contentOffset an Animated.Value? Then use setValue instead of setState like this:
constructor(props) {
  super(props);

  this.state = {
    contentOffset: new Animated.Value(0)
  };

  this.onScrollEvent = this.onScrollEvent.bind(this);
}

onScrollEvent = event => {
  this.state.contentOffset.setValue(event.nativeEvent.contentOffset.y);
}


text:
Q: Can't parse date in datepicker i have a problem to filter range of dates HERE  is the project. The filter works fine but when i try to filter the flowing dates 01/08/2016 and 01/09/2016 - the filter returns false.
At the beginning i thought something is worng with the filter's conditions:
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {

    var min = new Date($('#filter_start_date').val());
    var max = new Date($('#filter_end_date').val());
    var date_var =   new Date(data[4]); // use data for the date column

    if (
        ( isNaN( min ) && isNaN( max ) ) ||
        ( isNaN( min ) && date_var <= max ) ||
        ( min <= date_var   && isNaN( max ) ) ||
        ( min <= date_var   && date_var <= max )
        )
    {
        return true;
    }
    return false;

}

);
But the i realize that it's probably something to do with the parsing of the dates...

A: dateString in new Date(dateString) must be in certain format to work properly, please see, for example, here for some guidelines.
A quick fix to make your example work is to change dateFormat in datepicker options:
...
dateFormat: 'yy-mm-dd',
...

If you do not like the displayed format, there are options in datepicker to change that.

A: Got it - i changed the filter format to yy-mm-dd like this :
$.fn.dataTable.ext.search.push(
 function(settings, data, dataIndex) {

 function reverse_date(inputDate){

        var date_to_fix = inputDate.split("/");
        var fixed = date_to_fix.reverse().join('-');

        return fixed; // creates yy-mm-dd format
    };

var min = new Date(reverse_date($('#filter_start_date').val()));
var max = new Date(reverse_date($('#filter_end_date').val()));
var date_var = new Date(reverse_date((data[4]))); // use data for the age
column

if (
  (isNaN(min) && isNaN(max)) ||
  (isNaN(min) && date_var <= max) ||
  (min <= date_var && isNaN(max)) ||
  (min <= date_var && date_var <= max)
) {
  return true;
}
return false;

}
);
And it solved the problem.
Here is the project.


text: Q: How to add code autocompletion to PyCharm when working with graphical .ui components In VisualStudio, when you access a component through a dot, you are immediately offered methods and data that belong to this class. In PyCharm, when working with .ui files, it feels like you are accessing a black box about the contents of which nothing is known. Are there any plugins or other ways to autocomplete text for graphical components in PyCharme like VisualStudio does?