Q: Test if value of double is less than maximum value of an int Assume that d is a double variable. Write an if statement that assigns d to the int variable i if the value in d is not larger than the maximum value for an int.
The method below is my attempt at this problem:
public static void assignInt(double d)
{
  int i = 0;
  if(d < Integer.MAX_VALUE)
    i =  (int)d;
  System.out.print(i);
}

Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold? With this assumption in mind, I attempt to call assingDoubleToInt() three times:
public static void main(String[] args)
{
  assignDoubleToInt(2147483646); //One less than the maximum value an int can hold
  assignDoubleToInt(2147483647); //The maximum value an int can hold
  assignDoubleToInt(2147483648);//One greater than the maximum value an int can hold. Causes error and does not run.
}

The first two calls output:
2147483646
0

And the third call, assignDoubleToInt(2147483648);, throws "The literal 2147483648 of type int is out of range."  Isn't the comparison 2147483648 < 2147483647 here? Why is i being assigned the value if the comparison should evaluate to false?
Using the comparison d < Integer.MAX_VALUE is not the proper way to do this. How can I test whether a double variable can fit in an int variable?

A: The int range issue is because you have an int literal. Use a double literal by postfixing 'd':
public static void main(String[] args) {
    assignDoubleToInt(2147483646); // One less than the maximum value an int can hold
    assignDoubleToInt(2147483647); // The maximum value an int can hold
    assignDoubleToInt(2147483648d);// One greater than the maximum value an int can hold. Causes error and does not
                                  // run.
}

I believe your equality test should be <=, also: "if the value in d is not larger than the maximum value for an int" - so if it is EQUAL to the maximum value for an int, it's valid:
public static void assignDoubleToInt(double d) {
    int i = 0;
    if (d <= Integer.MAX_VALUE)
        i = (int) d;
    System.out.println(i);
}

A:
Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold?

Yes.

throws "The literal 2147483648 of type int is out of range."

You can't create an int literal representing a number outside of the int range, so 2147483647 is legal but 2147483648 is not.  If you want a larger integer literal, use a long literal, with the letter L appended: 2147483648L, or a double literal with a decimal point (or D appended): 2147483648.0 (or 2147483648D).

is not the proper way to do this.

The comparison d < Integer.MAX_VALUE is legal and correct, because Integer.MAX_VALUE will be widened to a double for the comparison, and a double can be (much) larger in value than Integer.MAX_VALUE.  You just need to make sure you can pass the proper value in as detailed above.
(As noted in a comment above, it should be d <= Integer.MAX_VALUE, with <=.)


Q: randomBytes vs pseudoRandomBytes In what situations is it acceptable (from a security standpoint) to use node's crypto.pseudoRandomBytes instead of the cryptographically-strong crypto.randomBytes?
I assume pseudoRandomBytes performs better at the expense of being more predictable (incorrect), but the docs don't really have much to say about how less-strong it is.
Specifically, I'm wondering if I'm ok using pseudoRandomBytes to generate a CSRF token.

A: As it turns out, with the default OpenSSL (which is bundled with node, but if you've built your own, it is possible to configure different engines), the algorithm to generate random data is exactly the same for both randomBytes (RAND_bytes) and pseudoRandomBytes (RAND_pseudo_bytes).
The one and only difference between the two calls depends on the version of node you're using:

*

*In node v0.12 and prior, randomBytes returns an error if the entropy pool has not yet been seeded with enough data.  pseudoRandomBytes will always return bytes, even if the entropy pool has not been properly seeded.

*In node v4 and later, randomBytes does not return until the entropy pool has enough data.  This should take only a few milliseconds (unless the system has just booted).

Once the the entropy pool has been seeded with enough data, it will never "run out," so there is absolutely no effective difference between randomBytes and pseudoRandomBytes once the entropy pool is full.
Because the exact same algorithm is used to generate randrom data, there is no difference in performance between the two calls (one-time entropy pool seeding notwithstanding).

A: Just a clarification, both have the same performance:
var crypto = require ("crypto")
var speedy = require ("speedy");

speedy.run ({
    randomBytes: function (cb){
        crypto.randomBytes (256, cb);
    },
    pseudoRandomBytes: function (cb){
        crypto.pseudoRandomBytes (256, cb);
    }
});

/*
File: t.js

Node v0.10.25
V8 v3.14.5.9
Speedy v0.1.1

Tests: 2
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per test: ~3000ms (3s 0ms)
Total time: ~6000ms (6s 0ms)

Higher is better (ops/sec)

randomBytes
  58,836 ± 0.4%
pseudoRandomBytes
  58,533 ± 0.8%

Elapsed time: 6318ms (6s 318ms)
*/

A: If it's anything like the standard PRNG implementations in other languages, it is probably either not seeded by default or it is seeded by a simple value, like a timestamp. Regardless, the seed is possibly very easily guessable.


Q: browser waiting for server indefinitely I have an issue with a long-running page. ASP.NET page takes about 20 minutes to get generated and served to the browser.
Server successfully completes the response (according to logs and ASP.NET web trace) and I assume sends it to the browser. However, browser never recieves the page. It (IE8 & Firefox 3 both) keeps spinning and spinning (I've let it run for several hours, nothing happens).
This issue only appears on the shared host server. When I run the same app on dev machine or internal server, everything works fine.
I've tried fiddler and packet sniffing and it looks like server doesn't send anything back. It doesn't even send keep-alive packets. Yet both browsers I've tried don't time out after pre-defined timeout period (1 hour in IE I believe, not sure what it is in Firefox).
The last packet server sends back is ACK to the POST from the browser.
I've tried this from different client machines, to ensure it's not a broken configuration on my machine.
How can I futher diagnose this problem? Why doesn't browser time-out, even though there're no keep-alive packets?
p.s. server is Windows 2003, so IIS6. It used to work fine on shared hosting, but they've changed something (when they moved to new location) and it broke. Trying to figure out what.
p.p.s. I know I can change page design to avoid page taking this long to get served. I will do this, but I would also like to find the cause of this problem. I'd like to stay focused on this issue and avoid possible alternative designs for the page (using AJAX or whatever else).

A: Check the server's connection timeout (on the Web Site properties page).
A better approach would be to send the request, start the calculation on the server, and serve a page with a Javascript timer that keeps sending requests to itself. Upon post-back, this page checks whether the server process has completed. While the process is still running, it responds with another timer. Once it has completed, it redirects to the results.

A: Would you clarify how you fixed this problem? It seems I have the same one. I'm getting .docx report and both browsers (IE10 and Fx37) indefinitely wait for a response (keep on spinning).
But it works great in VS2012's IIS Express and on my localhost IIS7.
Although server has IIS6.1
And when it works on localhost, it's just several minutes to get a report.


Q: Ring properties proofs. Prove the following properties of a ring R:
(a) For all a,b,c in R we have $a(b-c) = ab -ac$
(b) If R has multiplicative identity 1, then $(-1)(-1) = 1$.
(c) If R has multiplicative identity 1, then for all a in the ring we have $(-1)a = -a$
Attempt: I will use for the following
axioms for all a,b,c in R
i) $(ab)c = a(bc)$
ii) $a(-b) = -ab$
iii) $a + (-a) = 0$
Proof(a): Suppose a,b,c are in R. Then $a(b-c) = a(b + (-c)) = ab + a(-c) = ab + (-ac) = ab -ac$
Proof (b): 1 is in R, then $(-1)(-1) + (-1) = (-1)[(-1) + (1)] = (-1)(0) = 0$
Proof (c) : Suppose 1 is in R, then $(-1)a = (-1)a + (1)(a) - a = 0 - a = -a$
Please can anyone please verify this are all correct, and if not, can anyone please give some feedback. I would really appreciate it.
Thank you.

A: First proof looks good to me.
The second proof shows that $(-1)(-1) + (-1) = 0$. This is close to the final conclusion you wish to draw; push it one step further.
The third proof is good, though you elided over a bit in the middle. After the second inequality, you might write:
$$ = (-1 + 1)a - a = 0a - a = 0 - a = -a.$$
Even in the added steps above, it assumes familiarity with the fact that $0a = 0$.
(If this has not been established, use the standard trick of $0a = (0+0)a = 0a + 0a$ and cancel.)


Q: How to concatenate columns without null value in sql This question is asked many time here but i am not getting the proper output as i am expecting:
I have a table in which i need to concatenate columns but i don't want NULL value in it. I want it in sql server 2008 concate function does not work in 2008.
Example:
OrderTable
 Customer_Number   order1   order2  order3   order4
    1               NULL      X       Y       NULL
    2               NULL      A       B       NULL
    3                V       NULL     H       NULL

Now want i want is the data in concatenated manner for order only like this:
Customer_Number     Order
  1                 X,Y
  2                 A,B
  3                 V,H

This is the code i used
 Select Customer_number, ISNULL(NULLIF(order1,' ')+',','')+
 ISNULL(NULLIF(order2,' ')+',','')+
 ISNULL(NULLIF(order3,' ')+',','')+
 ISNULL(NULLIF(order4,' ')+',','')
 as Order from Ordertable

I got the below output
Customer_Number      Order
  1                NULL,X,Y,NULL
  2                NULL,A,B,NULL
  3                V,NULL,H,NULL

I already try Coalesce, Stuff, ISNULL, NULLIF but all have same result
Thanks in advance !!!

A: Another variation, for fun and profit, demonstrating the FOR XML trick to concatenate values pre-SQL Server 2012.
SELECT Customer_Number, STUFF(
    (SELECT ',' + order1, ',' + order2, ',' + order3, ',' + order4 FOR XML PATH('')),
    1, 1, ''
)

This is slight overkill for a constant number of columns (and not particularly efficient), but an easy to remember pattern for concatenation. Also, it shows off STUFF, a function any SQL developer should learn to love.

A: Example
 Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into @YourTable Values
 (1,NULL,'X','Y',NULL)
,(2,NULL,'A','B',NULL)
,(3,'V',NULL,'H',NULL)

 Select Customer_Number
       ,[Order] = IsNull(stuff(
                  IsNull(','+order1,'')
                 +IsNull(','+order2,'')
                 +IsNull(','+order3,'')
                 +IsNull(','+order4,'')
                 ,1,1,''),'')
 From  @YourTable

Returns
Customer_Number Order
1               X,Y
2               A,B
3               V,H

EDIT - IF the "NULL" are strings and NOT NULL Values

Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into @YourTable Values
 (1,'NULL','X','Y','NULL')
,(2,'NULL','A','B','NULL')
,(3,'V','NULL','H','NULL')

 Select Customer_Number
       ,[Order] = IsNull(stuff(
                  IsNull(','+nullif(order1,'NULL'),'')
                 +IsNull(','+nullif(order2,'NULL'),'')
                 +IsNull(','+nullif(order3,'NULL'),'')
                 +IsNull(','+nullif(order4,'NULL'),'')
                 ,1,1,''),'')
 From  @YourTable

A: This is a bit unpleasant, it needs to be in a subquery to remove the trailing comma efficiently (though you could use a CTE):
SELECT
    Customer_number,
    SUBSTRING([Order], 0, LEN([Order])) AS [Order]
FROM(
    SELECT
        Customer_number,
        COALESCE(order1+',', '') +
        COALESCE(order2+',', '') +
        COALESCE(order3+',', '') +
        COALESCE(order4+',', '') AS [Order]
    FROM
        OrderTable) AS SubQuery

A: You were on the right track with the Coalesce, or IsNull.  Instead of trying to track the length and use substring, left or stuff, I just used a replace to remove the trailing comma that would show up from the coalesce.
Select Customer_number,
    Replace(
        Coalesce(Order1 + ',','')+
        Coalesce(Order2 + ',','')+
        Coalesce(Order3 + ',','')+
        Coalesce(Order4 + ',','')
     +',',',,','') --Hack to remove the Last Comma
 as [Order] from Ordertable


Q: Oculus SDK: Unable to run Oculus Tiny Room using OpenGL I am getting started with Oculus SDK. As a first step, I decided to try out the "OculusRoomTiny (GL)" example from the provided samples. The project compiles all right on Visual Studio 2017. However, when I run the binary, I get the following error

OpenGL supports only the default graphics adapter.

I am using a Windows 10 desktop with Intel(R) Core(TM) i7-6700k CPU @ 4.00GHz and a dedicated NVIDIA GeForce GTX 980 Ti GPU.
Things I have tried so far:

*

*Update NVIDIA drivers

*Go to Nvidia Control Panel --> Manage 3D settings --> OpenGL Rendering GPU and change that from "Auto" to "GeForce GTX 980 Ti"

*Change BIOS to set the dedicated GPU as the primary GPU

*Disable multi-monitor support in BIOS

None of have provided any positive results.
I have already looked at all the online posts I could find and haven't been able to find a solution in a couple of days. So any help is much appreciated!

A: I finally figured it out. The error was caused because the Oculus was plugged into the dedicated GPU and the monitor for the desktop was plugged into the on-chip Intel GPU. It was resolved when I plugged both of them into the NVIDIA GPU.


Q: npm install bootstrap vs download source code I'm trying to use Bootstrap's build tools but I'm having trouble using them when I use npm install bootstrap. When I download the files from their site, I have no problems.
When I install Bootstrap via npm (npm install bootstrap) and then run npm install inside the bootstrap folder, it looks like it installs, but then none of the commands (like npm run dist) work.
When I download the files from the site and then run npm install on the folder, I have no problem running the commands.
I noticed that the npm installation includes far fewer files:

Compared to the downloaded version:

What am I missing? Was I supposed to install other things separately?
I'm in a mac, with node 8.11.2 and npm 6.1.0

A: When installing Bootstrap from their GitHub repository, you get a large amount of files that are only required for debugging, testing, compiling from source, etc. It includes many operations that are only needed if you are trying to contribute to Bootstrap.
The NPM version is just a packaged, production-ready version of Bootstrap. Even after running npm install, you don't get all of the GitHub files, as they are unnecessary for a production environment. You cannot therefore build the NPM version, except by adding basically everything from the GitHub version.


Q: Derivative of trace of inverse of a matrix function I am trying to derive the derivative of the trace of inverse of a matrix function (of X), i.e.
$$f(X)=Tr\left((HXH^{H}+I)^{-1}\right) $$
where $H\in R^{n\times m}, X\in R^{m\times m}$.
So $HXH^{H}+I$ is invertible while $HXH^{H}$ is not.
Any one know how to find $\frac{\partial f}{\partial X}$ ?
Thanks in advance!

A: Note: In the below, I used $X$ instead of $H$ by accident.  Also, $X^*$ is my notation for $X^H$.

We can find this inverse by the chain rule.  Note that $f = f_1 \circ f_2 \circ f_3$, where
$$
f_1(A) = Tr(A)\\
f_2(A) = A^{-1}\\
f_3(A) = XAX^* + I
$$
The derivatives of these functions are given by
$$
[f_1'(A)](B) = Tr(B)\\
[f_2'(A)](B) = -A^{-1}BA^{-1}\\
[f_3'(A)](B) = XBX^*\\
$$
The chain rule tells us that
$$
[(f_1 \circ f_2 \circ f_3)'(A)] = \\
[f_1'(f_2(f_3(A)))]\circ
[f_2'(f_3(A))] \circ f_3'(A)
$$
So, all together, that gives us
$$
[f'(A)] = \\
(B \mapsto Tr[(XBX^* + I)^{-1}])\circ
(B \mapsto -A^{-1}(XBX^* + I)A^{-1})\circ
(B \mapsto XBX^*) =\\
(B \mapsto Tr[(XBX^* + I)^{-1}])\circ
(B \mapsto -A^{-1}(X[XBX^*]X^* + I)A^{-1}) =\\
(B \mapsto Tr[(XBX^* + I)^{-1}])\circ
(B \mapsto -A^{-1}(X^2BX^{*2} + I)A^{-1}) =\\
(B \mapsto Tr[(X[-A^{-1}(X^2BX^{*2} + I)A^{-1}]X^* + I)^{-1}])
$$
In other words, if $A$ is parameterized as a function of $t \in \Bbb R$, then we can write
$$
\frac{d}{dt}f(A(t)) =
Tr[(X[-A^{-1}(X^2\frac{dA}{dt}X^{*2} + I)A^{-1}]X^* + I)^{-1}]
$$

Clarification of my derivatives:
By $[f'(A)](B)$, I mean that for every $A$, $f'(A)$ is a function on $B$.  You are right to be confused.  Let's look at an example.
Take $f(X) = Tr(X)$, and find its derivative my way.  In fact, $f$ is linear, so this will be easy: we have
$$
[f'(A)](B) = Tr(B)
$$
Note that, in this case, $A$ doesn't pop up in the definition of $f'$. In other words, $f$ has a constant derivative.  This makes sense because $f$ is linear.  Another way of writing the above is to say that if $A(t)$ is a matrix-valued function on $t \in \Bbb R$, then
$$
\frac{d}{dt}f(A(t)) = Tr \frac{dA}{dt}
$$
Now, my understanding of your notation is that
$$
\frac{\partial f}{\partial X}[i,j] = \frac{\partial f}{x_{ji}}
$$
equivalently, define $A_{ij}(t) = A + t E_{ji}$ (where $E_{ji}$ is the matrix with $0$s everywhere except at the $j,i$ entry, where it has a $1$).  Then we should have
$$
\frac{\partial f}{\partial X}(A)[i,j] =
\frac {d}{dt} f(A_{ij}(t))
$$
By my above statement, that means we can write
$$
\frac{\partial f}{\partial X}(A)[i,j] = Tr(E_{ji}) =
\begin{cases}
1 & i=j\\
0 & i \neq j
\end{cases}
$$
In other words, $\frac {\partial f}{\partial X}$ is $I$, which is exactly what we expected.

A: I got an answer myself in a relative simple way: $$\frac{\partial f}{\partial X}=H^H((HXH^H+I)^{-2})^{H}H$$ through the chain rule. That is, let $U=HXH^H$ and $g(U)=Tr((U+I)^{-1})$, then $$\frac{\partial f}{\partial X_{i,j}}=Tr[(\frac{\partial g(U)}{\partial U})^H \frac{\partial U}{\partial X_{i,j}}]$$.Since we can easily get $\frac{\partial g(U)}{\partial U}=(U+I)^{-2}$ and
$$U=\sum_i \sum_j X_{i,j} h_i h_j^H$$, we know $$\frac{\partial U}{\partial X_{i,j}}=h_i h_j^H$$.We thus have $$\frac{\partial f}{\partial X_{i,j}}=Tr[((HXH^H+I)^{-2})^{H}h_ih_j^{H}]=Tr[h_j^{H}((HXH^H+I)^{-2})^{H}h_i]=h_j^{H}((HXH^H+I)^{-2})^{H}h_i$$.
Reorganizing them in a compact form we have the above result (hopefully there is no error).
Actually the $X$ I am dealing with is diagonal, so the derivation is simpler than above.
Thank you all for your attention and especially for @Omnomnomnom!


Q: How to control display in UIPickerView using selected state of button hi i have used UIButton and also UIpickerview,when i select value(select team) ,the value is changed(india).but
when i hold the button(india) ,the value is changed to initial value(select team).if i release the button from pressing ,the value is changed(india).but i want to do when i hold , the button must show (india) ...i want to use selected state configuration...anyhelp?

A: What is value here? UIPicker's value? or it's some other control in your view?
Check out Highlighted state for UIButton in Interface Builder... hope this helps!


Q: maven compilation fails because unavailable dependency I'm trying to run java program with maven but when i compiled using the command mvn -U compile
he shows me the following error
[root@onePK-EFT1 tutorials]# mvn -U compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building onePK Java Tutorials 0.6.0.5
[INFO] ------------------------------------------------------------------------
Downloading: http://repo.maven.apache.org/maven2/com/cisco/onep/libonep-core-rel
/0.6.0.5/libonep-core-rel-0.6.0.5.pom
[WARNING] The POM for com.cisco.onep:libonep-core-rel:jar:0.6.0.5 is missing, no
dependency information available
Downloading: http://repo.maven.apache.org/maven2/com/cisco/onep/libonep-
core-rel/0.6.0.5/libonep-core-rel-0.6.0.5.jar
[INFO] ------------------------------------------------------------------------
INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.517s
[INFO] Finished at: Tue Jul 09 07:28:28 PDT 2013
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project java-tutorials: Could not resolve
dependencies for project com.cisco.onep:java-tutorials:jar:0.6.0.5: Could not find
artifact com.cisco.onep:libonep-core-rel:jar:0.6.0.5 in central
(http://repo.maven.apache.org/maven2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read
 the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN
/DependencyResolutionException

and this is my pom.xml file
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org
 /2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cisco.onep</groupId>
<artifactId>hello-network-app</artifactId>
<version>0.1-SNAPSHOT</version>
<name>The onePK Hello Network Example Application</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12</version>
            <configuration>
                <forkMode>always</forkMode>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.8</version>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>com.cisco.onep</groupId>
        <artifactId>libonep-core-rel</artifactId>
        <version>0.6.0.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.thrift</groupId>
        <artifactId>libthrift</artifactId>
        <version>0.6.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
</dependencies>

<developers>
    <developer>
        <name>onePK Team</name>
        <email>onepk-feedback@cisco.com</email>
        <organization>Cisco.com</organization>
    </developer>
</developers>

I think it's because he can't find libonep-core-rel.jar which i have it included
please any help

A: The simple solution is to use the appropriate maven repository for the artifacts com.cisco.onep* which are not located in Maven central.

A: As an immediate solution, but not a recommendation, you can use system dependencies to resolve artifacts on your local filesystem.
As @khmarbaise implied, try to publish those corporate artifacts to your corporate Maven repository (Nexus, Artifactory, Archiva, etc.), even an FTP/HTTP server would do...
Once you publish those corporate artifacts to your "corporate" repository(hopefully it's already in place), you just need a new repository declaration in your Maven POM.


Q: Reverse Proxy on a Lotus Domino Server? Can Lotus Domino be setup as a reverse proxy server?  I have 1 Domino server (web facing) which I would like to configure as a reverse proxy server for an IIS application running on another server?
Is this possible, or do we need to use an apache (or another) web server to do this?
I have checked the IBM docco - they speak about it for iNotes however I do not think it's the same thing.

A: If you wish to do that via iNotes/DWA then this can be done as mentioned here:
How to Configure a Reverse Proxy server for iNotes and Sametime Proxy Integration
And here is a howto from 2008 but the basics should be the same:
Setup Reverse Proxy with Apache for Lotus Notes Webmail
Please read also this one:
Configuring iNotes Web Access with a WebSphere Edge reverse proxy server
However from home IBM Lotus Domino couldn´t act as a Reverse Proxy.


Q: How to read notification while app is in background? I'm using swift 3 and trying to read notifications in didReceiveRemoteNotification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print(userInfo)
}

It's working while app is running but not printing anything while app is background (inactive). How can I read notifications while app is in background (inactive).

A: After taking appropriate permissions for the background notifications in your app and adopting UNUserNotificationCenterDelegate in the appropriate viewController. You can implement this method to trigger notifications in the background and take actions to perform any action from the notification. To perform any action from the notification you need to adopt the function userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void).
func startNotifications() {

        let notificationCenter = UNUserNotificationCenter.current()

// to include any action in the notification otherwise ignore it.

        let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])

        let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [],  options: [])

        notificationCenter.setNotificationCategories([category])

        let content = UNMutableNotificationContent()
        content.title = "Your Title"
        content.body = "Message you want to give"
        content.sound = UNNotificationSound.default

      // To trigger the notifications timely and repeating it or not
           let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)

        content.categoryIdentifier = "CategoryName"

            print("Notifications Started")

            let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)

            notificationCenter.add(request, withCompletionHandler: { (error) in
                if error != nil {
                    print("Error in notification : \(error)")
                }
            })

    }

Disclaimer: do apply the solution according to your need and ask if anything wrong happens. This code is for triggering background notifications.


Q: Problem with delay before LED turns on Series LED:

How do you make a LED circuit in series where the next LED will turn on, with equal brightness after a certain time delay?
For example, when I turn on the power, the red lights will turn on and after 10 seconds, the orange ones will light and 10 seconds after the orange LED lights up, the yellow ones will light up.
We have tried using this circuit for 1 LED but the LED did not have a delay before turning on. The following is the LED Delay circuit??

Where we computed the time delay as resistor value from +9V multiplied by the capacitance.
(Source: http://www.ehow.com/how_7700687_add-delay-led.html)

A: That circuit is not the best way to do this, since you will a very large capacitance for any reasonable delay. As stated in the link, 0.01F (10,000uF) is a huge amount for only 3 seconds, which will make the capacitor physically large and not so cheap. For 10 seconds you will need even more than this.
A better way is to use the RC circuit together with a MOSFET for each set of series LEDs (you can use a bipolar, but you need to take the base current required into account) in a circuit such as this one. Due to the MOSFETs almost infinite input impedance, and being able to separate the RC control from the LED drive, we can use high value resistors and therefore smaller capacitors than the RC only circuit:
MOSFET LED Delay:

Simulation:

I have used all the same LEDs here, obviously the series resistors will need to be adjusted for the desired current in your circuit. The MOSFETs can be any general purpose N-channel capable of handling the current (if it's <100mA then almost anything will be suitable).   Watch the gate-sourve voltage doesn't exceed the MOSFET specs (check datasheet) - if your supply is >10V you may need to use a divider to feed the capacitor.
The turn on time is dictated by the MOSFET threshold voltage and RC time constant. You can alter this as necessary by changing the capacitor/resistor values. The timing won't be very accurate, as threshold voltages can vary quite widely, and electrolytic capacitor value tolerances are not so good, but it should be suitable for a rough delay circuit (you can tweak to suit)
If you need more accurate timing, a timer IC or small microcontroller would be better.

A: The obvious answer is to use a small microcontroller.  That will be a lot fewer parts than trying to do this in analog.  You can then also arbitrarily program the delays.  You only need a micro with 4 output pins and preferably a internal oscillator to make the circuit simple.  I'd use one of the PIC 12F parts.  These come in 8 pin packages and have up to 5 output pins, which is one more than you need.


Q: How Can I SignUp new User with AWS cognito with Postman without using hosted UI Basically I want the below flow in the application .
I have created one user pool in the cognito and configure it.
I want to integrate cognito authentication and authorization with below flow.

*

*Register new user with by using cognito signUp api via postman (I dont want to use hosted UI) .

once user is successfully registered in cognito.

*User will call the cognito login api via postman - On successful login cognito will return access_token.

*I will use that access token in all subsequent requests to make sure the user is authenticated and authorized .
The main thing here is I do not want to use that hosted UI given by cognito .I want to achieve this via api calls .
I am not sure for achieving this what I need to . You can tell me if any more steps needed before the first step I wrote like authorize my app or anything like that.
I understood I need to authorize my app before it uses the signup api  but I am not sure about exact flow and process or in which manner I need to perform the steps .
Please guide..

A: There are aws sdks available for different platform. You need to implement one of them according to your backend technology and expose your api and test it out in the post man. Please go through this link docs.aws.amazon.com/cognito-user-identity-pools/latest/… There are sdks links at the bottom.


Q: Expanding UIView -Iphone I'm working on an i-phone app that when you press a button a UITableView drops down. I want to push/animate the objects that are underneath the button so that they are underneath the tableview.
For each label/textfield that needs to be moved down would I need something like:
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration:0.3f];
self.view.frame = CGRectOffset(self.view.frame, 0, 70);

Any examples would be helpful.

A: In iPhone OS 4.0 and later, block-based animation methods are recommended by Apple such as
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations

for eg.
[UIView animateWithDuration:0.3
                      delay:0
                    options:UIViewAnimationOptionBeginFromCurrentState
                 animations:(void (^)(void)) ^{
                     self.view.frame = CGRectOffset(self.view.frame, 0, 70);                     }
                 completion:^(BOOL finished){

                 }];

A: So, there will be a UITableView that come from above to self.view and you wanted to move down all the elements in self.view, except the UITableView.
How about putting all the elements in self.view to a container view what have the same size as self.view? And then you can animate all the UI elements with one move

A: Yes, you missed commitAnimations for the view.

A: try this,
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelay:0.3];
self.view.frame = CGRectOffset(self.view.frame, 0, 70);
[UIView commitAnimations];


Q: Creating a module for raising class-specific errors In my rails projects, I often use this sort of behavior in my classes and models:
class Whatever

  class WhateverError < StandardError; end

  def initialize(params={})
    raise WhateverError.new("Bad params: #{params}") if condition
    # actual class code to follow
  end
end

The trouble is, this is both hugely repetitive and fairly verbose. I'd love it if I could just do this whenever I need to raise a class-specific error:
class ErrorRaiser
  include ClassErrors
  def initialize(params={})
    error("Bad params: #{params}") if condition
    error if other_condition # has default message
    # actual class code to follow
  end

  def self.class_method
    error if third_condition # class method, behaves identically
  end
end

I'm having major trouble creating such a module. My sad early attempts have tended to look something like the below, but I'm pretty confused about what's available within the scope of the module, how to dynamically create classes (within methods?) or whether I have straightforward access to the "calling" class at all.
My basic requirements are that error be both a class method and an instance method, that it be "namespaced" to the class calling it, and that it have a default message. Any thoughts/help? Is this even possible?
module ClassErrorable

  # This and the "extend" bit (theoretically) allow error to be a class method as well
  module ClassMethods
    def self.error(string=nil)
      ClassErrorable.new(string).error
    end
  end

  def self.included(base)
    set_error_class(base)
    base.extend ClassMethods
  end

  def self.set_error_class(base)
    # I'm shaky on the scoping. Do I refer to this with @ in a class method
    # but @@ in an instance method? Should I define it here with @ then?
    @@error_class = "##{base.class}Error".constantize
  end

  def self.actual_error
    # This obviously doesn't work, and in fact,
    # it raises a syntax error. How can I make my
    # constant a class inheriting from StandardError?
    @@actual_error = @@error_class < StandardError; end
  end

  def initialize(string)
    @string = string || "There's been an error!"
  end

  def error(string=nil)
    raise @@actual_error.new(string)
  end

end

A: How about something like this (written in pure Ruby; it could be refactored to use some Rails-specific features like .constantize):
module ClassErrorable
  module ClassMethods
    def error(message = nil)
      klass = Object::const_get(exception_class_name)
      raise klass.new(message || "There's been an error!")
    end

    def exception_class_name
      name + 'Error'
    end
  end

  def self.included(base)
    base.extend ClassMethods
    Object::const_set(base.exception_class_name, Class.new(Exception))
  end

  def error(message = nil)
    self.class.error(message)
  end
end


Q: Hide content in listbox item depending on a binding property in Silverlight I have xaml that lookes like this
<ListBox>
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <TextBlock Text="{Binding Name}" />
            <StackPanel Orientation="Vertical" x:Name="contentPanel" >
            Content goes here...
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

The listbox binds to an object with a bool property called ShowContent.
How do I get silverlight to hide the contentPanel if the object with ShowContent is false?

A: Write a BoolToVisibility IValueConveter and use it to bind to the Visibility property of your contentPanel
<StackPanel Visibility="{Binding YourBoolProperty, Converter={StaticResource boolToVisibilityResourceRef ..../>

You can find a BoolToVisibility pretty easy anywhere.
Check IValueConveter if you are new to that. http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

A: I would recommend setting the ListBoxItem visibility at the ListBoxItem level or you will end up with tiny empty listbox items due to the default padding and border values e.g.
<ListBox>
     <ListBox.Resources>
          <Style TargetType="ListBoxItem">
               <Setter Property="Visibility" Value="{Binding MyItem.IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" />
          </Style>
     </ListBox.Resources>
     <ListBox.ItemTemplate>
          <DataTemplate>
               <StackPanel Orientation="Vertical">
                    <CheckBox Content="{Binding MyItemName}" IsChecked="{Binding IsVisible, Mode=TwoWay}"/>
               </StackPanel>
          </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

This hides the entire ListBoxItem not just the contents of it.


Q: Im trying to combine date times and string in the same column of a list I have a list of names like this:
['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover',....]
And a list of date-times:
[datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17),.....]
now I'm trying to add them together in between of each other like this in a new list:
[('Albert Einstein', datetime.date(1879, 3, 14)),...
Nothing I tried seem to work. It also doesn't seem possible to me with append or extend, hope someone can help me.

A: Use zip(a, b) for the two lists, e.g.
a = [1, 2, 3]
b = ["a", "b", "c"]
print(list(zip(a, b)))

[(1, "a"), (2, "b"), (3, "c")]

A: As mentioned in the comments you can simply use zip which can take lists as parameters and returns an iterator, with tuples of i-th position of the lists passed as arguments, therefore if we try to print it, we'll get a zip object at ... that's why we need to use list() so we can access the values in a list format:
import datetime
people = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]
output = list(zip(people,dates))

For example:
[('Albert Einstein', datetime.date(1642, 12, 25)),
 ('Benjamin Franklin', datetime.date(1879, 3, 14)),
 ('J. Edgar Hoover', datetime.date(1706, 1, 17))]

A: Try this:
names = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]

print(list(zip(names, dates)))

Output:
[('Albert Einstein', datetime.date(1642, 12, 25)), ('Benjamin Franklin', datetime.date(1879, 3, 14)), ('J. Edgar Hoover', datetime.date(1706, 1, 17))]


Q: SQLAlchemy Datetime Differences In SQLAlchemy, you can do a query similar to:
self.session.query(JobsRunning).filter((datetime.datetime.utcnow() - JR.start_time) > datetime.timedelta(hours=3)).all()

This fails because I'm assuming that datetime.datetime.utcnow() returns a double after being subtracted with JR.start_time. Is there a way around this without pulling the datetime.datetime.utcnow() outside of the query itself?
For some, this may make the query look cleaner.


Q: Unit sphere is sequentially compact \ compact If $V$ is a liniar space and $dimV=n$ finite, then the set $ S=\{x \in V;\|x\|_1=1\}  $ is bounded and closed .And from Heine Borel theorem $S$ will be compact.$$ $$ My question: Is there a way to show a sequence from $S$ have a convergent subsequence? $$$$
If not how to proof $S$ is closed and bounded?

A: Suppose we have a sequence in S with no convergent subsequence in S. Then for each x in S there is a open neighborhood containing no points in the sequence except x. S is in the union of all these open neighborhoods. Because of S being compact, there exists a finite subcover. However at least one of these finite sets covering S has to contain infinite elements of the sequence in contradiction to our choice of the open neighborhoods.


Q: PBW theorem for Poisson algebras In general case the validity of an analogue of the Poincare-Birkhoff-Witt theorem for poisson algebras is open. For which class of Poisson algebras PBW theroem is valid?

A: A good reference for this question is the recent paper
Poisson enveloping algebras and the Poincaré–Birkhoff–Witt theorem
by Thierry Lambre, Cyrille Ospel and Pol Vanhaecke.
In particualr it is shown that for an important class of singular Poisson algebras, the PBW theorem still holds.


Q: How can I change this code to show a hidden form with a menu drop down instead of a checkbox? This code is working great, but I'd like to change it so it uses a drop-down menu choice instead of a checkbox.  For example, the Dropdown menu choices for "More?" would be "yes" or "no".  If "yes" is selected in the menu, I then want the hidden div to show just like it does when one checks the checkbox in the current code.
The javascript:

And this is the HTML:
 <form name='frm' action='nextpage.asp'>
  <input type="checkbox" name="chkbox" onclick="showhidefield()">
  Check/uncheck here to show/hide the other form fields

    <input type='text'>

    <input type='submit'>

  This is a text line below the hideable form fields.

</form>

Thank you.

A: Replace your checkbox with
<select name="more" onchange="showhidefield()">
  <option value="yes">Yes</option>
  <option value="yes">Yes</option>
</select>

And replace the
if (document.frm.chkbox.checked)

in your showhidefield() function with
if (document.frm.more.value == 'yes')

A: <form name='frm' action='nextpage.asp'>
  <select name="chkbox" onChange="showhidefield(this)">
     <option value="0" selected="true">-Select-</option>
    <option value="1">Yes</option>
    <option value="2">No</option>
  </select>
  Check/uncheck here to show/hide the other form fields

    <input type='text'>

    <input type='submit'>

  This is a text line below the hideable form fields.

</form>

And javascript code is:


Q: Xbee compatibility Xbee-PRO is XBee-PRO 900 compatible with XBee-PRO 900HP (S3B) 10K?
Are in general Xbee modules compatible between families?
I tried to change firmware but it didn't help.

A: Unfortunately they are not compatible with each other if they have different firmware. The XBP9B-DP 10K is going to speak a different over the air language than the XBP09-DP.
However, I have had success loading matching firmware into two different Xbees. In my case, the XBPB9B-XCWT and XBP9B-DMWT both loaded as XBP9B-DMWT. You may have to use the recovery procedure of the XCTU software to do this. Click the wrench icon (tools) and select 'Xbee recovery' from the drop down.


Q: ^ and $ expressed in fundamental operations in regular expressions I've read a book where it states that all fundamental operations in regular expressions are concatatenation, or(|), closure(*) and parenthesis to override default precedence. Every other operation is just a shortcut for one or more fundamental operations.
For example, (AB)+ shortcut is expanded to (AB)(AB)* and (AB)? to (ε | AB) where ε is empty string. First of all, I looked up ASCII table and I am not sure which charcode is designated to empty string. Is it ASCII 0?
I'd like to figure out how to express the shortcuts ^ and $ as in ^AB or AB$ expression in the fundamental operations, but I am not sure how to do this. Can you help me out how this is expressed in fundamentals?

A: Regular expressions, the way they are defined in mathematics, are actually string generators, not search patterns. They are used as a convenient notation for a certain class of sets of strings. (Those sets can contain an infinite number of strings, so enumerating all elements is not practical.)
In a programming context, regexes are usually used as flexible search patterns. In mathematical terms we're saying, "find a substring of the target string S that is an element of the set generated by regex R". This substring search is not part of the regex proper; it's like there's a loop around the actual regex engine that tries to match every possible substring against the regex (and stops when it finds a match).
In fundamental regex terms, it's like there's an implicit .* added before and after your pattern. When you look at it this way, ^ and $ simply prevent .* from being added at the beginning/end of the regex.
As an aside, regexes (as commonly used in programming) are not actually "regular" in the mathematical sense; i.e. there are many constructs that cannot be translated to the fundamental operations listed above. These include backreferences (\1, \2, ...), word boundaries (\b, \<, \>), look-ahead/look-behind assertions ((?= ), (?! ), (?<= ), (?<! )), and others.
As for ε: It has no character code because the empty string is a string, not a character. Specifically, a string is a sequence of characters, and the empty string contains no characters.

A: ^AB can be expressed as (εAB) ie an empty string followed by AB and AB$ can be expressed as (ABε) that's AB followed by an empty string.
The empty string is actually defined as '', that's a string of 0 length, so has no value in the ASCII table. However the C programming language terminates all strings with the ASCII NULL character, although this is not counted in the length of the string it still must be accounted for when allocating memory.
EDIT
As @melpomene pointed out in their comment εAB is equivalent to AB which makes the above invalid. Having talked to a work college I'm no longer sure how to do this or even if it's possible. Hopefully someone can come up with an answer.


Q: How to create JSONObject from ArrayList to make post request? I am trying to post data into server using JSONObject as request. And I dont know how to create JSONObject from ArrayList with following type of data.
{"AnswersList":[
{
    "questionID": 1,
    "question": "What is yout name?",
    "questionType": "STRI",
    "questionOrder": 1,
    "answer":"Avishek",
    "choiceList": []
},
{
    "questionID": 2,
    "question": "Sports?",
    "questionType": "MULT",
    "questionOrder": 2,
     "answer":"1,2",
    "choiceList": [
        {
            "choiceID": 1,
            "choiceName": "Football",
            "choiceOrder": 1
        },
        {
            "choiceID": 2,
            "choiceName": "Basketball",
            "choiceOrder": 2
        }
    ]
}]}

Can anyone please help me to solve this problem.
I have create two model classes for handling the JSON. First one is Question.java for second is Choice.java
Model classes are:
Question.java
public class Question {

@SerializedName("questionID")
public String questionID;
@SerializedName("question")
public String question;
@SerializedName("questionType")
public String questionType;
@SerializedName("questionOrder")
public String questionOrder;
@SerializedName("answer")
public String answer;
@SerializedName("choiceList")
public ArrayList<Choice> choices = new ArrayList<>();
@SerializedName("isRequired")
public boolean isRequired;

//getter and setter methods
}

Choice.java
public class Choice {

@SerializedName("choiceID")
private String choiceID;

@SerializedName("choiceName")
private String choiceName;

@SerializedName("choiceOrder")
private String choiceOrder;

//getter and setter method
}

I've tried this code but did not work
    DatabaseHelper databaseHelper = new DatabaseHelper(mContext);
    ArrayList<Question> questionsAnswer = new ArrayList<>();
    questionsAnswer.addAll(databaseHelper.getQuestionList());

    Log.v(TAG, "size of question answer list : " + questionsAnswer.size());

    Map<String, Object> jsonParams = new ArrayMap<>();
    //put something inside the map, could be null
    JSONArray jsArray = new JSONArray(questionsAnswer);
    jsonParams.put("AnswersList", jsArray);

A: First of all, I'll suggest to use Retrofit library for requests (https://square.github.io/retrofit/)
For creating a json String from your object you can use Gson library
Gson gson = new Gson();
String jsonInString = gson.toJson(obj);

Update
don't forget to add Gson dependency on your gradle file
dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

A: Parsing JSON Objects & Arrays on Java we should use GSON Library
Add gradle File:
implementation 'com.google.code.gson:gson:2.8.2'


Q: Marshalling LPWSTR * from a C function I have a sample function from a native code
HRESULT getSampleFunctionValue(_Out_ LPWSTR * argument)

This function outputs the value in argument. I need to call it from the Managed code
[DllImport("MyDLL.dll", EntryPoint = "getSampleFunctionValue", CharSet = CharSet.Unicode)]
static extern uint getSampleFunctionValue([MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder  argument);

This returns garbage value. AFAIK the original C function does not create string using CoTaskMemAlloc. What is the correct call?
Any help will be appreciated.

A: You need the C# code to receive a pointer. Like this:
[DllImport("MyDLL.dll")]
static extern uint getSampleFunctionValue(out IntPtr argument);

Call it like this:
IntPtr argument;
uint retval = getSampleFunctionValue(out argument);
// add a check of retval here
string argstr = Marshal.PtrToStringUni(argument);

And you'll also presumably need to then call the native function that deallocates the memory that it allocated. You can do that immediately after the call to Marshal.PtrToStringUni because at that point you no longer need the pointer. Or perhaps the string that is returned is statically allocated, I can't be sure. In any case, the docs for the native library will explain what's needed.
You may also need to specify a calling convention. As written, the native function looks like it would use __cdecl. However, perhaps you didn't include the specification of __stdcall in the question. Again, consult the native header file to be sure.


Q: Assign var as a selector I have a var named as sliceText which contains a text which is collected whenever user hover over the section of a visualforce chart. I'm trying to increase the size of this text with a value which gets calculated at run time and newSize var hold the same. But using jquery following syntax is not working and I'm not able change the font size.
var sliceText = j$(this).text();
j$(sliceText).css('font-size', newSize);

How can I assign a var as a selector using jquery? I want following solution work for me but its NOT when I tried to!! https://docs.acquia.com/articles/increase-text-size-jquery

A: You need to apply css to the DOM object containing the text no the text
j$('path, tspan').mouseover(function(e) {
j$(this).children().css('font-size', 15);//reset to default size font
j$(e.target).css('font-size', newSize);
});

A: You didn't mentioned whether the dom is an id or a class
    var sliceText = j$(this).text();
    j$("#"+sliceText).css('font-size', newSize); --- if the dom element is an id

    j$("."+sliceText).css('font-size', newSize);  --- if the dom element is  a class

A:

var newSize = '30px';

var originalSize = '14px';

$("span").hover(function(){
        $(this).css('font-size', newSize);
        }, function(){
        $(this).css('font-size', originalSize);
    });

 Jan

Feb

March

A: As i understand you want to change the font size of hover element
so  try this one
function funtest()
{
    var oldSize = parseFloat(j$('text').css('font-size'));
    var newSize = oldSize * 2;
    j$('path, tspan').mouseover(function () {
        j$(this).css('font-size', newSize);
    });
}


Q: Large react-redux form app I've been working on rewriting one of the modules in my company using react, the module is a single page composable of 4-5 different forms, selections made in each form are then determine the appeareance of the next form step.
There are a lot of "static" input fields which not affecting the visual ui state of the app, but are required to send to the server, other inputs are changing the ui state.
I'm looking for the right approach for this type of apps, since it seems attaching onChange event to every single input (there are more than 100 inputs total in the whole page). I've used react-redux-forms plugin, but it is too much of a blockbox for me, since I need to have direct access to the state and make decision based on it. I would preferer hacing more control over the state.
Is the right solution to bind onChange event for every input? Or is there a better approach.

A: We do this with redux-form quite easily. Because everything's maintained in the fields prop, you could do something like this:
const Form = ({
  fields,
  handleSubmit,
  saveForm
}) => (
  <form onSubmit={handleSubmit(saveForm)}>
    <fieldset>
      <input type="text" {...fields.hasAlternativeDelivery} />
    </fieldset>
    {fields.hasAlternativeDelivery.value === true &&
      <fieldset>
        {/* more fields go here */}
      </fieldset>
    }
  </form>
);

We then conditionally validate certain fieldsets like this.
So, to answer your question: you shouldn't rely on change events to hide / show certain fields, this goes against the very nature of React (React is declarative, what you're describing is an imperative way of doing things). Instead, figure out what state (/props) should lead to which UI.


Q: JQuery effect continues to iterate I have a div within a parent div, that is normally hidden. When you hover over the parent div the child is then visible. I am using JQuery .toggle() to get this effect. The problem is that if you MouseIn and MouseOut really fast, repeatedly over the parent, the child div is toggled that many times. Is there a way to prevent this from happening, it is slowing down my page?
JSFIDDLE: http://jsfiddle.net/vY59g/1/
My JQuery:
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").toggle("slow");
    });
});

A: It is because the queuing nature of animations, every mouser enter and mouse leave operation queues a toggle operation. So if there are quick movement of mouse triggering the enter and leave events then even after the events are over the animations will keep happening.
The solution is to stop and clear previous animations before the toggle is called using .stop()
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true, true).toggle("slow");
    });
});

Demo: Fiddle

A: If you want to make things better, just put div:.result-user-facts into an Variable if there only has one. Like this:
$(function (){
    var container = $(".result");
    var item = container.find(".result-user-facts").eq(0);
    $(".result").hover(function (){
        item.stop().toggle("slow");
    });
});

A: Use .stop(true,true)

Stop the currently-running animation on the matched elements.

Fiddle DEMO
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true,true).toggle("slow");
    });
});


Q: what port tomcat7 use? how do I set AWS Security group? I run a tomcat7 in ubuntu in aws. not use apache.
and my site use default tomcat port 8080.
I don't want to open port except 8080 so I'm setting in aws security group.
inbound
8080 TCP anywhere
and outbound allTraffic.
but I try to rest call to
http://my_aws_ip:8080/test.do

but it doesn't work.
What should I open the port?
Does tomcat7 use a some port?

A: Tomcat uses whatever port or ports and protocols you configure it to use.  By default it listens for HTTP requests on tcp/8080, AJP requests on tcp/8009, and service management requests on tcp/8005.
This is configured in Connector elements in $CATALINA_HOME/conf/server.xml:
https://tomcat.apache.org/tomcat-7.0-doc/config/http.html
You should reconfigure Tomcat to listen on standard ports like tcp/80 for HTTP and tcp/443 for HTTPS.  Non-standard ports are a ready indication of a novice deployment.
The AWS Security Group should be configured to allow HTTP, HTTPS, pr both depending on your need.  I highly recommend using HTTPS unless the information being transferred is public domain or has no value.
You can check what ports Tomcat is using on your EC2 instance with netstat -anpt.  It will show all active and listen ports and the programs that have bound them (including java or tomcat for your Tomcat ports).
Unless you really need root access to the OS, you might want to consider using Amazon Elastic Beanstalk as it manages all that cruft for you.


Q: How to output only given chars? How can I crop unneeded chars, and only output what I need? For example:
input:
    ASDFQWER

output:
    DFQ

I mean in this case I need only the 3.-4.-5. chars of the string. How do I do that?

A: Use
echo "${string:index:length}"

for your example
x="ASDFQWER"
echo "${x:2:3}"

A: cut is the simplest program I know which is able to do that.
example:
echo ASDFQWER | cut -c3,4,5


Q: Setting size of inner region of Java SWT shell window In a Java SWT shell window, how do I set its inner size than its whole window frame size?
For instance, if I use shell.setSize(300, 250) this would make the whole window appearing as exactly 300x250. This 300x250 includes the size of the window frame.
How can I set the inner size, that is the content display region of the shell window to 300x250 instead? That's this 300x250 excludes the width of the window frame.
I tried to minus some offset values but the thing is different Operating Systems have different window frame sizes. So having a constant offset would not be accurate.
Thanks.

A: From your question what I understood is that you want to set the dimension of the Client Area. And in SWT lingo it is defined as a rectangle which describes the area of the receiver which is capable of displaying data (that is, not covered by the "trimmings").
You cannot directly set the dimension of Client Area because there is no API for it. Although you can achieve this by a little hack. In the below sample code I want my client area to be 300 by 250.  To achieve this I have used the shell.addShellListener() event listener. When the shell is completely active (see the public void shellActivated(ShellEvent e)) then I calculate the different margins and again set the size of my shell. The calculation and resetting of the shell size gives me the desired shell size.
>>Code:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;

public class MenuTest {

    public static void main (String [] args)
    {
        Display display = new Display ();
        final Shell shell = new Shell (display);

        GridLayout layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.horizontalSpacing = 0;
        layout.verticalSpacing = 0;
        layout.numColumns = 1;
        shell.setLayout(layout);
        shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,true));
        final Menu bar = new Menu (shell, SWT.BAR);
        shell.setMenuBar (bar);

        shell.addShellListener(new ShellListener() {

            public void shellIconified(ShellEvent e) {
            }
            public void shellDeiconified(ShellEvent e) {
            }
            public void shellDeactivated(ShellEvent e) {
            }
            public void shellClosed(ShellEvent e) {
                System.out.println("Client Area: " + shell.getClientArea());
            }
            public void shellActivated(ShellEvent e) {
                int frameX = shell.getSize().x - shell.getClientArea().width;
                int frameY = shell.getSize().y - shell.getClientArea().height;
                shell.setSize(300 + frameX, 250 + frameY);
            }
        });

        shell.open ();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
}

A: If I get you right you should set the size of the inner component to the needed size and use the method pack() (of the frame).

A: import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;

public class SWTClientAreaTest
{
    Display display;
    Shell shell;
    final int DESIRED_CLIENT_AREA_WIDTH = 300;
    final int DESIRED_CLIENT_AREA_HEIGHT = 200;

    void render()
    {
        display = Display.getDefault();
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        Point shell_size = shell.getSize();
        Rectangle client_area = shell.getClientArea();

        shell.setSize
        (
            DESIRED_CLIENT_AREA_WIDTH + shell_size.x - client_area.width,
            DESIRED_CLIENT_AREA_HEIGHT + shell_size.y - client_area.height
        );

        shell.open();

        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }

        display.dispose();
    }

    public static void main(String[] args)
    {
        SWTClientAreaTest appl = new SWTClientAreaTest();
        appl.render();
    }
}

A: Use computeTrim to calculate the bounds that are necessary to display a given client area. The method returns a rectangle that describes the bounds that are needed to provide room for the client area specified in the arguments.
In this example the size of the shell is set so that it is capable to display a client area of 100 x 200 (width x height):
Rectangle bounds = shell.computeTrim(0, 0, 100, 200);
shell.setSize(bounds.width, bounds.height);

This article describes the terms used by SWT for widget dimensions:
https://www.eclipse.org/articles/Article-Understanding-Layouts/Understanding-Layouts.htm


Q: Android custom Drawable vs custom View I wanted to know what's the difference between creating a custom Drawable like in the Shelves project: http://code.google.com/p/shelves/ to creating a custom View?

A: Drawble only response for the draw operations, while view response for the draw and user interface like touch events and turning off screen and more.
View can contain many Drawbles.


Q: Otimização de Aplicações Hibridas posso durante um scroll de uma lista com muitos elementos, renderizar apenas os em tela, por intermédio de uma verificação do atual movimento de scroll que se cancela sozinha e criando uma div pai que tem seu height, setado manualmente com elementos de position absolute que tem sua altura setada manualmente, e intercalar entre display inline, inline-block, block contra o display none, dos que são renderizados ou não em tela e assim retirar o lag durante esses processos de scroll ?

A: Cara, a sua solução retiraria um pouco do "lag" (se tirar), pois mesmo essa solução precisa de otimização. Minha sugestão é usar (ou pesquisar um pouco sobre) o Lazy Load (veja esse JS que maravilha).
Agora, aqui vai uma dica pratica para criar apps de forma mais otimizadas desde o inicio:
O CSS nunca deve ser usado ao "dinamizar" algo com JS, a não ser que não haja outro jeito. A pesar do CSS3 estar bem "dinâmico" ele ainda é estático, dessa forma, para dinamizar uma aplicação (que é seu caso), use o máximo de JS e menos CSS que vc conseguir.
O conceito de StyleSheet é justamente padronizar o estilo para o JS dinamizar o padrão.


Q: Android Timer is firing twice I am trying to update TextView content every second using Timer Class. Given below is my code. The problem is that the value is increasing by 2 not by 1. Please tell me what the problem is.
public class MainActivity extends ActionBarActivity {

    public void onButtonClick (View view) {
        // calendar
        OnDateSetListener datelistener = new OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int Year, int monthOfYear, int dayOfMonth) {
                                ....
                reScheduleTimer(); // starting the timer
            }
        };
    }

    public void reScheduleTimer(){
        timer = new Timer();
        timerTask = new myTimerTask();
        timer.schedule(timerTask, 1000, 1000);
    }
    public class myTimerTask extends TimerTask{
        @Override
        public void run() {
            elapsed = elapsed + 1;

            runOnUiThread(new Runnable(){
             public void run() {
                    TextView seconds = (TextView) findViewById(R.id.seconds);
                    seconds.setText("seconds so far "+elapsed);
                }
            });
        }
    }
}

A: Wouldn't hurt to check if timerTask is null at the beginning of reScheduleTimer and cancel it if it is not null.
At the beginning of reScheduleTimer:
    if(timerTask != null) {
        timerTask.cancel();
    }

A: I still don't know how the variable is increasing by more than 1, but I solved the problem by reading the system clock on every invocation of the function and displaying it.


Q: Is it possible to auto-start a WCF for only specific projects? I have a WCF project which several other projects depend on, but others, like unit testing projects and other support utilities which don't need the service.  It contains the following XML in the .csproj file:
<ProjectExtensions>
  <VisualStudio>
    <FlavorProperties GUID="{3D9AD99F-2412-4246-B90B-4EAA41C64699}">
      <WcfProjectProperties>
        <AutoStart>True</AutoStart>
      </WcfProjectProperties>
    </FlavorProperties>
  </VisualStudio>
</ProjectExtensions>

Is there a way to get the "auto-start service with project" functionality to only apply to specific projects in the solution?  Or is it all or nothing?  Is there anything I could add to the other projects to tell them they depend on this service to make it auto-start in the debugging session?  Or add some condition to the service's .csproj that depends on which project is the current startup project?
I tried experimenting with Condition="'$(Configuration)' == 'Debug'" in various places, but I couldn't get it to behave an different based on that Configuration variable.

A: To make the client applications debugable, create a new tiny project and set both the service and the client application as dependencies.  The only file it should contain is Program.cs, and its only function should look like this:
[STAThread]
static void Main(string[] args)
{
    new System.ServiceModel.ServiceHost(typeof(MyServiceClass)).Open();
    MyClientApplication.Program.Main(args);
}

And then merge the app.config for both into a single app.config for this tiny application.  But now the service is hosted inside the same process as the client, and they can both be debugged interchangeably.
This allows removing the AutoStart feature from the service, but still run the client application together with the service.


Q: rails how to display data or retrieve values after find I did a find on some model and got the following
>> @addy
=> [#<Address id: 3, street: "Some Street", houseNumber: nil, created_at: "2010-01-20 06:09:52", updated_at: "2010-01-20 06:09:52", address_id: 16>]

Now how do I retrieve the values?  what if i want the street?
@addy.street does not work netiher does @addy[:street]
what if i had a list of @addy's and wanted to loop through them to show street for each?

A: @addy.first.street should work, as it is list of Adress classes containing only one member.
For displaying each street for more adresses in list:
@addy.each do |address|
  puts address.street
end

or
list_of_streets = @addy.map { |address| address.street }

Edit:
When you have problem identifying what class you have, always check object.class. When you just use object in IRB, then you see output from object.inspect, which doesn't have to show class name or even can spoof some informations. You can also call object.methods, object.public_methods.
And remember that in Ruby some class is also an instance (of Class class). You can call @addr.methods to get instance methods and @addr.class.methods to get class methods.
Edit2:
In Rails #find can take as first parameter symbol, and if you pass :first of :last, then you'll get only one object. Same if you pass one integer (id of retrieved object). In other cases you get list as result, even if it contains only one object.


Q: Unable to use ttyUSB0 as console I have a server (Ubuntu 20.04.1 Kernel 5.4.0-42-generic) that is meant to be headless and able to be remote rebooted (with encrypted root) I have a USB to Serial adapter in the machine and was wanting to use this as a console at boot time to enable headless/remote unlocking of the encrypted root.
I am able to successfully connect to the console once host is booted after enabling serial-getty@ttyUSB0.service so the adapter works and is cabled correctly.
I have added "console=tty0 console=ttyUSB0" to GRUB at boot time but this appears to be outright ignored by the kernel.
$ dmesg | grep tty
[    0.000000] Command line: BOOT_IMAGE=/vmlinuz-5.4.0-42-generic root=/dev/mapper/host--vg-host_root--lv ro ipv6.disable=1 console=tty0 console=ttyUSB0
[    0.056872] Kernel command line: BOOT_IMAGE=/vmlinuz-5.4.0-42-generic root=/dev/mapper/host--vg-host_root--lv ro ipv6.disable=1 console=tty0 console=ttyUSB0
[    0.115389] printk: console [tty0] enabled
[    0.458997] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
[   54.731750] usb 1-1.5: pl2303 converter now attached to ttyUSB0

I have tested using "console=tty0 console=ttyS0" which appears to work though I have no serial port connected to that interface so unable to verify and would prefer to have this working via USB rather than needing to source a port header
$ dmesg | grep tty
[    0.000000] Command line: BOOT_IMAGE=/vmlinuz-5.4.0-42-generic root=/dev/mapper/host--vg-host_root--lv ro ipv6.disable=1 console=ttyS0 console=tty0
[    0.056348] Kernel command line: BOOT_IMAGE=/vmlinuz-5.4.0-42-generic root=/dev/mapper/host--vg-host_root--lv ro ipv6.disable=1 console=ttyS0 console=tty0
[    0.115326] printk: console [tty0] enabled
[   26.469014] printk: console [ttyS0] enabled
[   40.385803] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
[   51.949414] tty tty40: hash matches
[   87.762789] systemd[1]: Created slice system-serial\x2dgetty.slice.
[   91.428703] usb 1-1.5: pl2303 converter now attached to ttyUSB0

My current theory is that the kernel has not been compiled with CONFIG_USB_SERIAL_CONSOLE enabled.
So my questions...

*

*Is my theory correct and I am unable to do this with current kernel build?
1a) If so is there any way to request this be added in future kernel builds?

*Is there something I am missing that would get this to work?

Any assistance would be appreciated.
Cheers

A: I have exactly the same problem. Also the getty works when starting this 'manually' by systemctl.
marc@thirdworld:/var/log$ dmesg | grep -Ei 'console|ttyUSB'
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-5.4.0-135-generic root=UUID=0787120b-7858-4ca3-a7aa-b04533fc707e ro ipv6.disable=1 console=tty0 console=ttyUSB0,115200n8 splash quiet ipv6.disable=1 vt.handoff=7
[    0.030445] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-5.4.0-135-generic root=UUID=0787120b-7858-4ca3-a7aa-b04533fc707e ro ipv6.disable=1 console=tty0 console=ttyUSB0,115200n8 splash quiet ipv6.disable=1 vt.handoff=7
[    0.076533] Console: colour dummy device 80x25
[    0.076537] printk: console [tty0] enabled
[    1.582709] i915 0000:00:02.0: vgaarb: deactivate vga console
[    2.526967] usb 3-1.2: FTDI USB Serial Device converter now attached to ttyUSB0
[    4.010005] usb 3-1.4.3: FTDI USB Serial Device converter now attached to ttyUSB1
[    4.838555] systemd[1]: Starting Set the console keyboard layout...

Looks like the device module ('... attached to ttyUSB0...) is loaded after the console is enabled.
I have already added the modules for the usb to serial converter to /etc/initramfs-tools/modules and updated the initramfs.
I hope someone will have an answer...


Q: How do I get the current size of the heap memory of a process in Linux using C/C++ system calls? I am working on a software library, which can constantly keep track of the size of the heap memory of programs written in C/C++.
What I would like to do is as follows.
void check_memory(){

  heap_size = get_process_heap_size(.....);

  if(heap_size>=upper_bound){

    //do something to reduce the heap size

    heap_size = get_process_heap_size(.....);
  }
}

Is there any system call in C/C++ that is equivalent to get_process_heap_size() in the code above?

A: I dont know if there is any direct system call that gives you memory details, but if you are on linux you can read and parse /proc/(pid of your process)/status file to get the needed memory usage counts


Q: JAVA HOME PATH correctly set in Environment but wrong when compiling via Node.js I received this isue: com.sun.tools.javac.Main is not on the classpath. Oerhaps JAVA_HOME does not point to the JDK. It is currently set to "C:\Program Files\Java\jre7"
However, my JAVA HOME is set as follows:
C:\Program Files\Java\jdk1.7.0_51

With PATH
C:\Program Files\Java\jdk1.7.0_51

Any recommendations?

A: When node.js spawns a forked environment, it doesn't copy over your user's environment variables. You will need to do that manually.
You will need to get JAVA_HOME from process.env and set it in your exec() call.
Something like this should work:
var config = {
    env: process.env
};
exec('javacmd', config,
    function() {
        console.log(arguments);
});

Or if you wanted to be more explicit, you could extract only the variables you needed (JAVA_HOME, etc) from process.env
See here for more details:
How to exec in NodeJS using the user's environment?

A: Just uninstall node js and re install node js. Its solve my problem.


Q: forcing overflow-x using percentage and float I have a small structure of
 inside a container and what i'm trying to make is to force the overflow-x appear instead of overflow-y, but i can't achieve this, i presume it is beacuse of properties float and the percentage that i'm using.
is there i way where i can reach this result ? show only the horizontal overflow ?
here is the code:
html

Box 1

Box 2

Box 3

Box 4

Box 5

Box 6

Box 7

and css
#CockpitCenter {
   height: 500px; /* set only here in jsFiddle */
   position: fixed;
   left: 0;
   border: solid 2px #ccc;
   border-bottom: none;
   overflow: auto;
}

div#CockpitCenter ul.CockpitContainerResult {
   float: left;
   width: 100%;
}

ul.CockpitContainerResult li {
   margin: 5px 0;
   height: 150px;
   width: 50%;
   float: left;
}

ul.CockpitContainerResult li:nth-child(even) {
    float: right;
}

ul.CockpitContainerResult li div.box {
    border: solid 1px #ccc;
    margin: 15px;
    border-radius: 20px;
    height: 150px;
    text-align: center;
}

here is a demo

A: Sounds like you are trying to make a carousel, which there are many handy jquery plugins for. Regardless, you cannot do this using percentages for widths, you have to give your main container a fixed width, then give the inner one (your ul) whatever larger width you want. You must force a width on the UL otherwise the LI elements will just wrap. Once thats done just add an 'overflow-x: auto' to the main container and you should be on your way.
Quick example, http://jsfiddle.net/ybJ6C/8/
I'm using my ipad right now, and didn't see the scroll bar but it does indeed scroll. You'll notice that the scroll continues well past the end, you can adjust that with the width if you know what you want. If its dynamic then you would need js to adjust the width for you based on the elements within. I also don't have the height correct, but its enough to get the idea. (again doing this from my ipad, coding ain't the greatest)


Q: disable rsh on ubuntu server I installed rsh-server in my system for test purposes, but now I want to disable it without removing its package. I don't know how I can check rsh status. I can not see it with:

sudo service rshd status

Noted that, I don't install rsh under xinetd.

A: I don't have an Ubuntu system on my hands, but I believe its started by xinetd:
Edit /etc/xinetd.d/rsh and set disable=yes.
You need to restart the xinetd service once you're done.


Q: remove all styles based on browser version I would like to know how i can remove all css styles based on checking if the browser is less than IE8.
So if it detects IE7 then remove all styles? I wonder if this is possible via some jquery?
Will this fix most IE7 issues:
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script>
<![endif]-->

A: I don't know why you want to remove all styles for a browser version. I suppose that you have some CSS problems with IE7, and often a good way of fixing it, rather than deleting all your CSS, is to use ie7.js: http://code.google.com/p/ie7-js/.
Here is a demo of what it can do.
Also, this script has a version for IE8 and IE9.

A: <!--[if lt IE 8]>
    <body class='oldIE'>
<![endif]-->
<!--[if gte IE 8]>
    <body class='ok'>
<![endif]-->
<!--[if !IE]>
    <body class='ok'>
<![endif]-->

here you would need to prefix all the styles you don't IE7 to apply with .ok
another method would be
<!--[if lt IE 8]>
    //include an old IE specific stylesheet or none at all
<![endif]-->
<!--[if gte IE 8]>
    //include your stylesheets
<![endif]-->
<!--[if !IE]>
    //include your stylesheets
<![endif]-->

A: The best solution is to remove a specific class name rather than wiping the entire CSS for an element:
// Identity browser and browser version

if($.browser.msie && parseInt($.browser.version) == 7) {

   // Remove class name
   $('.class').removeClass('class');

   // Or unset each CSS selectively
   $('.class').css({
      'background-color': '',
      'font-weight': ''
   });

}


Q: Why is a foreach data binding not creating a $parent context? In the following code, why is the remove handler accessible without $parent?
If I use data-bind="click: $parent.remove" I get an error saying that property remove of undefined doesn't exists, but being inside a foreach loop, shouldn't I get a $parent context?
Template:

 <button data-bind="click: remove">x</button>

ViewModel:
function ViewModel() {

    var self = this;

    this.list = ko.observableArray(['asd', 'lol', 'rofl']);

    this.remove = function(index){
        console.log('Clicked ' + index);
        self.list.splice(index, 1);
    };

};

ko.applyBindings(ViewModel);

https://jsfiddle.net/3d7nfbr3/3/

A: You are missing the new, when creating your viewmodel.
Your code should look like this:
ko.applyBindings(new ViewModel());

Without the new the this refers to the global window object so your remove function is declared globally, that is why the $parent is not working.
Demo JsFiddle.


Q: Want to update my old html css ,js site with React , $('some').owlCarousel, throws an error Type error , owlCarousel is not a function Want to update my old HTML, CSS ,js site with React.
I make the components for HTML and integrate js also, but when I am trying to import and run owl carousel in jquery, like $('some').owlCarousel, throws an error Type error,

owlCarousel is not a function


Q: How count objects with element value? I need your help.
I have for example such array:
  var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];

How i can count them by year and get something like this:
2010 = 2 times;
2005 = 2 times;
2008 = 1 time;

Thank you

A: check this fiddle
var countObj = {};
for( var counter = 0; counter < array.length; counter++ )
{
   var yearValue = array [ counter ].year;
   if ( !countObj[ yearValue ] )
   {
      countObj[ yearValue ] = 0;
   }
   countObj[ yearValue ] ++;
}
console.log( countObj );

A: Try this:
var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];
var map={}
for (var i = 0; i<array.length;i++){
   if ( !map[ array [ i ].year ] ){
      map[ array [ i ].year ] = 0;
   }
   map[ array [ i ].year] ++;
}
console.log( map );

Fiddle

A: Here arrange uses reduce to build an object using the years as keys. It accepts a prop argument so that you can build the object as you see fit.
function arrange(arr, prop) {
  return arr.reduce(function(p, c) {
    var key = c[prop];
    p[key] = p[key] || 0;
    p[key]++;
    return p;
  }, {});
}

You can then iterate over the key/values of that object and print out the results for year:
var obj = arrange(array, 'year');
for (var p in obj) {
  console.log(p + ' = ' + obj[p] + ' times');
}

Or even by name:
var obj = arrange(array, 'name');

DEMO

A: You are trying to re-invent the wheel.
This and many more methods are exposed by a third-party JS library, called "lodash"; old name was "underscore". All its methods or most of them are exposed like
_.methodName(listName, iteratorFunction)

You can download it at: https://lodash.com/
Once you download and include lodash your script in your html, go to your function and do:
_.groupBy(yourArrayVariable, function(item){
    return item.year;
});

WARNING
This method will not return an array. It will return a JSON, in which the keys are represented by the "item.year" through the whole original array, and the values will be an array for each year listed. Every such array is a list of objects having the same "year" value:
{
   "2010" : [
        { "name" : "Tony", "year" : "2010" },
        { "name" : "Helen", "year" : "2010" }
   ],
   "2011" : [ ..... ]
}

Lodash has lots of useful methods anyway.

A:

var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];

var result = {};
array.forEach(function(data) {
    console.log(data.year);
    result[data.year] = result[data.year] ? ++result[data.year] : 1;
});

document.write(JSON.stringify(result));


Q: Split list of student according to their mark - haskell There is a list of students where
data Student = Student {
   name :: String,
   mark :: Mark
} deriving Show

data Mark = F|E|D|C|B|A deriving (Show, Eq, Ord)

I need to split it like that [(mark,[students with this mark])]
I made something like this:
splitToGroups :: [Student] -> [(Mark, [String])]
splitToGroups [] = []
splitToGroups students = foldr funct [] students where
    funct student [] = [(mark student,[name student])]
    funct student ((x,xs):xss) | mark student == x = ((x,(name student):xs):xss)
                               | otherwise = (mark student,[name student]):(x,xs):xss

but it works incorectly. Maybe someone knows how it could be done..

A: Don't manually recurse if you can use standard tools. You can do this with sorting and grouping, but IMO preferrable is to use the types to express that you're building an associative result, i.e. a map from marks to students.
import qualified Data.Map as Map

splitToGroups :: [Student] -> Map.Map Mark [String]
splitToGroups students = Map.fromListWith (<>)
     [ (sMark, [sName])
     | Student sName sMark <- students ]

(If you want a list in the end, just use Map.toList.)

A: If you view Student as a tupple, your function has this type: splitToGroups :: [(Mark,String)] -> [(Mark, [String])].
So you need a function with type: [(a,b)] -> [(a,[b])].
Using Hoogle: search results
I get the following functions:
groupSort :: Ord k => [(k, v)] -> [(k, [v])]
collectSndByFst :: Ord a => [(a, b)] -> [(a, [b])]
They should solve your problem, remember to import the modules listed in the link to make them work. You should make a funtion that maps from Student -> (Mark, String) first.


Q: Passing data to collectionViewCell I'm want to use some custom struct in my collection view cell. I get the data from my API service and trying to pass it to my custom collection view cell.
I found couple answers but I still couldn't figure out how to do
Here is where I get the actual data:
    func FetchFormData(linkUrl: String) {

    let parameters: [String: AnyObject] = [:]

    let postString = (parameters.flatMap({ (key, value) -> String in
        return "\(key)=\(value)"
    }) as Array).joined(separator: "&")

    let url = URL(string: linkUrl)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)

        let contentData = responseString?.data(using: .utf8)
        do {
            let decoder = JSONDecoder()
            self.formData = try decoder.decode(FormModel.self, from: contentData!)

        } catch let err {
            print("Err", err)
        }

        DispatchQueue.main.async {
            //here is the where I reload Collection View
            self.collectionView.reloadData()
        }

    }
    task.resume()
}

Also here I'm trying to pass data to the cell:
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BaseFormCollectionViewCell

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!

    return cell
}

The actual problem is starting into my cell class
class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

}

}
As you guys can see in the code It's going well until my collection view cell.
It should be a lot more simple but I couldn't figure out what's going on and Why its happening.

A: Modify your cell class as
class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //this is unnecessary. You can achieve what u want with a bit more cleaner way using configure function as shown below
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
 }

 override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

 }

 func configure() {
    //configure your UI of cell using self.formComponent here
 }
}

finally
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BaseFormCollectionViewCell

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!
    (cell as! BaseFormCollectionViewCell).configure()
    return cell
}

Look for (cell as! BaseFormCollectionViewCell).configure() in cellForItemAt thats how u trigger the UI configuration of cell after passing data to cell in statement above it.
Quite frankly u can get rid of didSet and relay on configure as shown
Hope it helps


Q: android - rendering bitmaps from native code - nativeCreate bitmaps are not cleanedup from memory I am streaming a video in android and I decode frames in native code and then copy the pixels to a bitmap, then display the bitmap in Java using canvas.unlockandpost with a while loop for all the bitmaps.
Everything is fine, but the streaming of bitmaps is very slow and causes a crash. I only see a message on logcat saying that "low memory no more background processes".
I see on the allocation table from eclipse, that the bitmaps that I created are not getting deleted from memory, even though, I am overwritng the pixels everytime. Is there any way I can clean up the memory it is keeping.
My code is as follows.
C Code :
AndroidBitmapInfo  info;
void*              pixels;
int                ret;

if ((ret =AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
}

memcpy(pixels, pictureRGB, 480*320);

AndroidBitmap_unlockPixels(env, bitmap);

Java Code
     Bitmap mBitmap = Bitmap.createBitmap(480, 320, Bitmap.Config.RGB_565);
     renderbitmap(mBitmap, 0);
     canvas.drawBitmap(mBitmap, 0, 0, null);

A: The code shown in your question is missing some critical parts to fully understand your problem, but it sounds like you're creating a new bitmap for every frame.  Since Android only allows for about 16MB of allocations for each Java VM, your app will get killed after about 52 frames.  You can create a bitmap once and re-use it many times.  To be more precise, you are creating a bitmap (Bitmap.CreateBitmap), but not destroying it (Bitmap.recycle).  That would solve your memory leak, but still would not be the best way to handle it.  Since the bitmap size doesn't change, create it once when your activity starts and re-use it throughout the life of your activity.


Q: Как безопасно передать данные от сервера клиенту? Всем добрый день. Столкнулся с такой проблемой: я создал Android приложение, которое будет получать данные из интернета. Сначала думал организовать парсинг из JSON, который лежит на сайте, но подумав понял, что будут передаваться конфеденциальные данные, а к json файлу может получить доступ любой, кто знает адрес. Так вот вопрос: как безопасно передать данные от сервера клиенту(Android приложению)?

A: Логично обеспечить end-to-end шифрование. Посмотрите в сторону openSSL, wolfSSL или более специализированных под android библиотек шифрования. Обычно используется связка из обмена ключами RSA и блочным шифрованием AES 128. Конечно, можете использовать и ГОСТ шифрования, например ГОСТ 28147-89, но это сложней реализовать и почти необоснованно. Конечно, если вы не собрались проходить аттестацию приложения гос. структурами. Универсальный совет, ищите готовые реализации, они существуют в изобилии.
P.S. Не силён в специфике андроид разработки.

A: можно использовать шифрованный websocket - wss. для начала требуется определиться с уровнем защиты, как правило от терморектального взлома защиты нет.


Q: ASP.NET web pages code behind So does the new ASP.NET web pages (also called razor pages) framework using the Razor view engine (referring to this: http://www.asp.net/webmatrix/tutorials/1-getting-started-with-webmatrix-and-asp-net-web-pages) not actually have any code-behind file?  I looked on the samples and couldn't find an example.  I assume no, but maybe there is a header reference where you can link it that I might be missing?
Can anyone confirm?
Thanks.

A: According to this blog you can easily have code-behind. http://www.compiledthoughts.com/2011/01/aspnet-mvc3-creating-razor-view-engine.html
Do you need it or not this is for you to decide. I strongly resent answers which starts with "you dont need it..".
Every person in the world must have a choice whether to shoot for a moon or shoot himself in the foot. Thats what I think is right.

A: There are no code behind files for Razor Views because you don't need them. You are writing the presentation logic using the Razor syntax on the view itself.
Razor views simplifies the mixing of raw HTML with dynamic content rendered using Razor syntax so you don't need a separate file. Furthermore there are no such things as Controls or Components in razor views so you don't need to configure them in a separate file.


Q: Populate a JComboBox with file names of a specific directory I want to populate a JComboBox with file names of a directory. Then, if selected, each field has to show a JList. How can i implement this?
Thanks

A: You can use File>>listFiles()

http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html

to get the array of Files in a particular directory (the one you initialized the File-object with).
You can then use the individual File's getName() method to get the names, then use JComboBox's addItem() method to add those names:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComboBox.html

Finally, to do something when the user clicks one of those names you have to install an item-listener using the JComboBox's addItemListener()-method. There are tutorials on how to do this last part and in general it just calls your ItemListener, giving it an ItemEvent, which you can then use to check which name was clicked.


Q: Specflow 2.0.0 What is the alternative to using ScenarioContext.Current? I have upgraded to Specflow 2.0.0. with NUnit 3 (also tried with XUnit) and I want to be able to execute test cases in parallel in an attempt to reduce the elapsed time it takes to run the tests.
On attempting to execute the tests in parallel an error is returned stating that I cannot use FeatureContext.Current and ScenarioContext.Current.
The tests use these to extract the names of the feature and scenario for the additional logging.
The tests also use the tags to be able to control the tests.
For Example:
I am aware that it is possible to put the tags in the attributes
[Binding]
public class SpecFlowHooks
{
    public ScenarioContext context;

    public SpecFlowHooks(ScenarioContext scenarioContext)
    {
        context = scenarioContext;
    }

    [BeforeScenario("SpecialCase")]
    public void BeforeScenario_SpecialCase() {
        do some stuff
    }

    [BeforeScenario]
    public void BeforeScenario() {
        do different stuff
    }
}

The problem with this is that BeforeScenario always runs.  I do not want it to run if the tag "SpecialCase"  is not present as the application will not be in the correct state.  I therefore extract the tags and do something different if the tag "SpecialCase" is present.
How can I find the list of tags without using
List<String> tags = ScenarioContext.Current.ScenarioInfo.Tags.ToList();

A: The alternative for parallel execution is to allow the dependency injection system which specflow uses to provide you with the ScenarioContext instance. To do that have your steps class accept an instance of the ScenarioContext and store it in a field:
[Binding]
public class StepsWithScenarioContext
{
    private readonly ScenarioContext scenarioContext;

    public StepsWithScenarioContext(ScenarioContext scenarioContext)
    {
        if (scenarioContext == null) throw new ArgumentNullException("scenarioContext");
        this.scenarioContext = scenarioContext;
    }

    [Given(@"I put something into the context")]
    public void GivenIPutSomethingIntoTheContext()
    {
        scenarioContext.Set("test-value", "test-key");
    }
}

A fuller explanation of how to use parallel execution can be found here
A similar approach needs to be taken to get the tags. Again add a constructor which takes a ScenarioContext to your class which holds your [BeforeScenario] method, and save the ScenarioContext in a field and use this filed instead of the ScenarioContext.Current


Q: SalesForce REST API INVALID_SESSION_ID error using v38.0 I am using SalesForce REST API For my PHP Application
But, when I send request at "instance_url/services/data/v38.0" along with the access token , I get this error:
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

I have a developer salesforce account and have API enabled true for every profile.
This is my Headers:
$headers = array(
          "Content-Type: application/x-www-form-urlencoded",
          "Accept:application/json",
          "Authorization: Bearer ".$access_token
          );

Used in CURL.