text:
Q: Hive Error : FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask I have got twitter data using flume on HDFS. Have 3 node cluster and MySQL Metastore for hive.
When i execute below query
select user_name.screen_name, user_name.followers_count from BBMP_election_tweets limit 10;

It is giving proper results.
But if i run below query
select user_name.screen_name, user_name.followers_count c from BBMP_election_tweets order by c desc;

It throws below error

Query ID = hduser_20150827102628_15a405ae-59a4-4c90-aa47-045d58c62f02
  Total jobs = 1 Launching Job 1 out of 1 Number of reduce tasks
  determined at compile time: 1 In order to change the average load for
  a reducer (in bytes):   set
  hive.exec.reducers.bytes.per.reducer= In order to limit the
  maximum number of reducers:   set hive.exec.reducers.max= In
  order to set a constant number of reducers:   set
  mapreduce.job.reduces= Starting Job = job_1439458788229_0016,
  Tracking URL =
  http://hdmaster:8088/proxy/application_1439458788229_0016/ Kill
  Command = /usr/local/hadoop/bin/hadoop job  -kill
  job_1439458788229_0016 Hadoop job information for Stage-1: number of
  mappers: 2; number of reducers: 1 2015-08-27 10:27:33,567 Stage-1 map
  = 0%,  reduce = 0% 2015-08-27 10:27:43,908 Stage-1 map = 50%,  reduce = 0% 2015-08-27 10:27:45,015 Stage-1 map = 0%,  reduce = 0% 2015-08-27 10:28:31,011 Stage-1 map = 100%,  reduce = 100% Ended Job =
  job_1439458788229_0016 with errors Error during job, obtaining
  debugging information... Examining task ID:
  task_1439458788229_0016_m_000001 (and more) from job
  job_1439458788229_0016
Task with the most failures(4):
  ----- Task ID:   task_1439458788229_0016_m_000001
URL:
http://hdmaster:8088/taskdetails.jsp?jobid=job_1439458788229_0016&tipid=task_1439458788229_0016_m_000001
  ----- Diagnostic Messages for this Task: Error: java.lang.RuntimeException: Error in configuring object
          at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
          at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
          at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
          at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:446)
          at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
          at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
          at java.security.AccessController.doPrivileged(Native Method)
          at javax.security.auth.Subject.doAs(Subject.java:415)
          at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
          at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused by: java.lang.reflect.InvocationTargetException
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:606)
          at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
          ... 9 more Caused by: java.lang.RuntimeException: Error in configuring object
          at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
          at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
          at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
          at org.apache.hadoop.mapred.MapRunner.configure(MapRunner.java:38)
          ... 14 more Caused by: java.lang.reflect.InvocationTargetException
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:606)
          at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
          ... 17 more Caused by: java.lang.RuntimeException: Map operator initialization failed
          at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.configure(ExecMapper.java:140)
          ... 22 more Caused by: org.apache.hadoop.hive.ql.metadata.HiveException:
  java.lang.ClassNotFoundException: Class
  com.cloudera.hive.serde.JSONSerDe not found
          at org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:328)
          at org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:338)
          at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.configure(ExecMapper.java:109)
          ... 22 more Caused by: java.lang.ClassNotFoundException: Class com.cloudera.hive.serde.JSONSerDe not found
          at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1980)
          at org.apache.hadoop.hive.ql.plan.PartitionDesc.getDeserializer(PartitionDesc.java:141)
          at org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:302)
          ... 24 more
FAILED: Execution Error, return code 2 from
  org.apache.hadoop.hive.ql.exec.mr.MapRedTask MapReduce Jobs Launched:
  Stage-Stage-1: Map: 2  Reduce: 1   HDFS Read: 0 HDFS Write: 0 FAIL
  Total MapReduce CPU Time Spent: 0 msec

When checked the logs created. It gives below message

2015-08-27 10:28:48,852 INFO [main]
  org.apache.hadoop.mapred.YarnChild: Kind: mapreduce.job, Service:
  job_1439458788229_0016, Ident:
  (org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier@988145f)
  2015-08-27 10:28:49,023 INFO [main]
  org.apache.hadoop.mapred.YarnChild: Sleeping for 0ms before retrying
  again. Got null now. 2015-08-27 10:28:49,627 INFO [main]
  org.apache.hadoop.mapred.YarnChild: mapreduce.cluster.local.dir for
  child:
  /tmp/hadoop-hduser/nm-local-dir/usercache/hduser/appcache/application_1439458788229_0016
  2015-08-27 10:28:50,363 INFO [main]
  org.apache.hadoop.conf.Configuration.deprecation: session.id is
  deprecated. Instead, use dfs.metrics.session-id 2015-08-27
  10:28:51,186 INFO [main] org.apache.hadoop.mapred.Task:  Using
  ResourceCalculatorProcessTree : [ ] 2015-08-27 10:28:51,534 INFO
  [main] org.apache.hadoop.mapred.MapTask: Processing split:
  Paths:/user/flume/tweets/BBMP_elections/2015/08/25/11/FlumeData.1440484157685:0+52974,/user/flume/tweets/BBMP_elections/2015/08/25/11/FlumeData.1440484188899:0+20119InputFormatClass:
  org.apache.hadoop.mapred.TextInputFormat
2015-08-27 10:28:51,701 INFO [main]
  org.apache.hadoop.hive.ql.exec.Utilities: PLAN PATH =
  hdfs://hdmaster:8020/tmp/hive/hduser/55daf291-b44e-414b-b3a5-e326134f9f24/hive_2015-08-27_10-26-28_312_5076847637673296334-1/-mr-10004/6e310852-ea63-4789-93f1-754147923e7f/map.xml
  2015-08-27 10:28:51,701 INFO [main]
  org.apache.hadoop.hive.ql.exec.Utilities: ***************non-local
  mode*************** 2015-08-27 10:28:51,701 INFO [main]
  org.apache.hadoop.hive.ql.exec.Utilities: local path =
  hdfs://hdmaster:8020/tmp/hive/hduser/55daf291-b44e-414b-b3a5-e326134f9f24/hive_2015-08-27_10-26-28_312_5076847637673296334-1/-mr-10004/6e310852-ea63-4789-93f1-754147923e7f/map.xml
  2015-08-27 10:28:51,701 INFO [main]
  org.apache.hadoop.hive.ql.exec.Utilities: Open file to read in plan:
  hdfs://hdmaster:8020/tmp/hive/hduser/55daf291-b44e-414b-b3a5-e326134f9f24/hive_2015-08-27_10-26-28_312_5076847637673296334-1/-mr-10004/6e310852-ea63-4789-93f1-754147923e7f/map.xml
  2015-08-27 10:28:51,719 INFO [main]
  org.apache.hadoop.hive.ql.log.PerfLogger:
  2015-08-27 10:28:51,720 INFO [main]
  org.apache.hadoop.hive.ql.exec.Utilities: Deserializing MapWork via
  kryo 2015-08-27 10:28:52,043 INFO [main]
  org.apache.hadoop.hive.ql.log.PerfLogger:  2015-08-27
  10:28:52,080 INFO [main]
  org.apache.hadoop.hive.ql.io.HiveContextAwareRecordReader: Processing
  file
  hdfs://hdmaster:8020/user/flume/tweets/BBMP_elections/2015/08/25/11/FlumeData.1440484157685
  2015-08-27 10:28:52,080 INFO [main]
  org.apache.hadoop.conf.Configuration.deprecation: map.input.file is
  deprecated. Instead, use mapreduce.map.input.file 2015-08-27
  10:28:52,080 INFO [main]
  org.apache.hadoop.conf.Configuration.deprecation: map.input.start is
  deprecated. Instead, use mapreduce.map.input.start 2015-08-27
  10:28:52,080 INFO [main]
  org.apache.hadoop.conf.Configuration.deprecation: map.input.length is
  deprecated. Instead, use mapreduce.map.input.length 2015-08-27
  10:28:52,080 INFO [main] org.apache.hadoop.mapred.MapTask:
  numReduceTasks: 1 2015-08-27 10:28:52,228 INFO [main]
  org.apache.hadoop.mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
  2015-08-27 10:28:52,228 INFO [main] org.apache.hadoop.mapred.MapTask:
  mapreduce.task.io.sort.mb: 100 2015-08-27 10:28:52,228 INFO [main]
  org.apache.hadoop.mapred.MapTask: soft limit at 83886080 2015-08-27
  10:28:52,228 INFO [main] org.apache.hadoop.mapred.MapTask: bufstart =
  0; bufvoid = 104857600 2015-08-27 10:28:52,228 INFO [main]
  org.apache.hadoop.mapred.MapTask: kvstart = 26214396; length = 6553600
2015-08-27 10:28:52,243 INFO [main]
  org.apache.hadoop.hive.ql.exec.MapOperator: Initializing operator
  MAP[3] 2015-08-27 10:28:52,243 INFO [main]
  org.apache.hadoop.hive.ql.exec.MapOperator: Initialization Done 3 MAP
  2015-08-27 10:28:52,243 INFO [main]
  org.apache.hadoop.hive.ql.exec.MapOperator: Operator 3 MAP initialized
  2015-08-27 10:28:52,262 WARN [main]
  org.apache.hadoop.mapred.YarnChild: Exception running child :
  java.lang.RuntimeException: Error in configuring object   at
  org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
    at
  org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
    at
  org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:446)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)   at
  org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)  at
  java.security.AccessController.doPrivileged(Native Method)    at
  javax.security.auth.Subject.doAs(Subject.java:415)    at
  org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused
  by: java.lang.reflect.InvocationTargetException   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
    ... 9 more Caused by: java.lang.RuntimeException: Error in
  configuring object    at
  org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
    at
  org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:75)
    at
  org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
    at org.apache.hadoop.mapred.MapRunner.configure(MapRunner.java:38)
    ... 14 more Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:106)
    ... 17 more Caused by: java.lang.RuntimeException: Map operator
  initialization failed     at
  org.apache.hadoop.hive.ql.exec.mr.ExecMapper.configure(ExecMapper.java:140)
    ... 22 more Caused by:
  org.apache.hadoop.hive.ql.metadata.HiveException:
  java.lang.ClassNotFoundException: Class
  com.cloudera.hive.serde.JSONSerDe not found   at
  org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:328)
    at
  org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:338)
    at
  org.apache.hadoop.hive.ql.exec.mr.ExecMapper.configure(ExecMapper.java:109)
    ... 22 more Caused by: java.lang.ClassNotFoundException: Class
  com.cloudera.hive.serde.JSONSerDe not found   at
  org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1980)
    at
  org.apache.hadoop.hive.ql.plan.PartitionDesc.getDeserializer(PartitionDesc.java:141)
    at
  org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:302)
    ... 24 more
2015-08-27 10:28:52,269 INFO [main] org.apache.hadoop.mapred.Task:
  Runnning cleanup for the task 2015-08-27 10:28:52,278 INFO [main]
  org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Stopping MapTask
  metrics system... 2015-08-27 10:28:52,278 INFO [main]
  org.apache.hadoop.metrics2.impl.MetricsSystemImpl: MapTask metrics
  system stopped. 2015-08-27 10:28:52,279 INFO [main]
  org.apache.hadoop.metrics2.impl.MetricsSystemImpl: MapTask metrics
  system shutdown complete.

Please suggest. How can this issue be resolved. and why is it occuring.
Thanks

A: It is a classpath problem
Root cause is java.lang.ClassNotFoundException: Class com.cloudera.hive.serde.JSONSerDe
you can have a look here to add hive-serdes: https://github.com/cloudera/cdh-twitter-example


text:
Q: Looping through TextView and setting the text I have exactly 20 TextView and their id is in sequence, i.e. :
R.id.textView1, R.id.textView2, R.id.textView3 ...

I have a for loop:
for (int i = 1; i < 21; i++) {
    TextView textView = (TextView) findViewById(R.id.textView ...);//
    textView.setText("...");

is there a way to get TextView using this for loop and set their text?

A: if you gave to your TextView  as id R.id.textView1.. R.id.textView21, you ca use getIdentifier to retrieve the TextViews id from its name
for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
 if (id != 0) {
     TextView textView = (TextView) findViewById(id);
  }
}

A: The more efficient way would be creating an array of integers and iterate through it:
int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };

for(int i=0; i < textViewIDs.length; i++) {
    TextView tv = (TextView ) findViewById(textViewIDs[i]);
    tv.setText("...");
}

A: This thread is very hold, but I faced the same sort of need : iterate through my layout structure and do something on each TextView. After having googlized it in many way, I finally decided to write my own implementation. You can find it here:
/*  Iterates through the given Layout, looking for TextView
    ---------------------------------
    Author : Philippe Bartolini (PhB-fr @ GitHub)
    Yes another iterator ;) I think it is very adaptable
*/

public void MyIterator(View thisView){
    ViewGroup thisViewGroup = null;
    boolean isTextView = false;
    int childrenCount = 0;

    try {
        thisViewGroup = (ViewGroup) thisView;
        childrenCount = thisViewGroup.getChildCount();
    }
    catch (Exception e){

    }

    if(childrenCount == 0){
        try {
            isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
        }
        catch (Exception e){

        }

        if(isTextView){
            // do something
        }
    }
    else {
        for(int i = 0; i < childrenCount; i++){
            MyIterator(thisViewGroup.getChildAt(i));
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to determine the order of a differential equation when it's solution is given We know how to find the solution of a given Homogeneous linear equations with constant coefficients.
In assignment I have to find the minimum possible order of a Homogeneous linear equations with constant coefficients having $x^2 sin x$ as a solution. I am really blank and have no idea how to proceed. Kindly help me. Any hint or solution will be helpful to me. Thanks a lot for the help.

A: Here is another way to look at the problem.
Take the homogeneous linear differential equation $L(y)=0$ where $L$ has degree $n$ and real coefficients. The standard test solution for this is $y=e^{ax}$ giving a polynomial equation of $P(a)=0$ degree $n$ for $a$ with the same coefficients as $L$.
If all the roots of $P$ are simple roots then $y$ is a linear combination of simple exponentials. If the roots are not real, then they come in conjugate pairs $c+di, c-di$ and combining them gives terms involving $e^{cx}\sin dx$ and $e^{cx}\cos dx$.
If there is a double root $b$, the solution may involve a term of the form $(rx+s)e^{bx}$ and for a triple root you get a quadratic coefficient.
So you need your auxiliary equation to have the right triple root, which should be enough, with some thought, to solve the problem. In fact it gives a quicker and cleaner solution than taking the derivatives and eliminating by hand, though you might want to check that the solution you get by this means does work.

A: If $f(x) = x^2\sin x$ is the solution of a linear ODE with constant coefficiencts, then for some $a_1,\ldots,a_n$ you have ($.^{(n)}$ means $n$-th derivative here) $$
  a_1\cdot f^{(1)} + \ldots + a_n f^{(n)} = f.
$$
Now in your case $f^{(1)} = x^2\cos x + 2x\sin x$. Is there an $a_1$ such that $$
  a_1 x^2\cos x + a_12x\sin x = x^2\sin x  \quad ?
$$
If not, try $n=2,3,\ldots$ until you succeed.

A: If $$y=x^2\sin x$$ you then have $$y'=x^2\cos x+2x\sin x$$$$y''=-x^2\sin x+4x\cos x+2\sin x$$
Now you see that you will be getting terms $p(x)\cos x+q(x)\sin x$ where $p(x), q(x)$ are quadratic in $x$. You can see that you can use $z=y''+y$ to eliminate the term in $x^2\sin x$ (and there is no term in $x^2\cos x$*). But it is a question of how to eliminate the remaining terms. You need more derivatives.
*It is useful to note that $y$ and $z$ are odd functions of $x$, so first derivatives won't help, because the first derivatives will be even functions. This simplifies the work considerably.

A: I think we can approach this way.
Think when we have term $sin x$ in solution of D.E. Yes,when we have complex pair of roots and solution looks like $e^{\alpha x}(C_1cos(\beta x)+C_2sin(\beta x))$.And,in this case order of D.E.is $2$.But we want $x^2 sinx$ to be present.
Now,suppose we have repeated pair of complex root.This means our solution will look like$e^{\alpha x}((C_1 + C_2 x)cos(\beta x)+(C_3 + C_4 x)sin(\beta x))$.Look we got term which looks like $xsinx$ in our solution. In this case since there are four constants order is $4$.
Now,suppose we have complex root repeated thrice.Then,our solution will look like$e^{\alpha x}((C_1 + C_2 x +C_3 x^2)cos(\beta x)+(C_4 + C_5 x + C_6 x^2)sin(\beta x))$.Yeah,we got term $x^2sinx$ in solution.
And since there are $6$ constants present,answer is $\color\red 6$.


text:
Q: Netty 3.4.1.Final does not work on Android Yesterday I tried to upgrade from 3.3.2.Final-SNAPSHOT to latest release. However, it fails on Android due to the following error:

*

*/AndroidRuntime( 720): FATAL EXCEPTION: main
E/AndroidRuntime( 720): java.lang.NoClassDefFoundError: java.util.concurrent.LinkedTransferQueue
E/AndroidRuntime( 720): at org.jboss.netty.util.internal.QueueFactory.createQueue(QueueFactory.java:48)

It turns out that on Android (this is 2.3), DetecationUtil.javaVersion() returns 7 since the Deflater class contains the field SYNC_FLUSH. Below are all fields Deflater.getDeclaredFields().
04-25 08:08:51.305: I/System.out(25674): [public static final int java.util.zip.Deflater.BEST_COMPRESSION, public static final int java.util.zip.Deflater.BEST_SPEED, public static final int java.util.zip.Deflater.DEFAULT_COMPRESSION, public static final int java.util.zip.Deflater.DEFAULT_STRATEGY, public static final int java.util.zip.Deflater.DEFLATED, public static final int java.util.zip.Deflater.FILTERED, private static final int java.util.zip.Deflater.FINISH, public static final int java.util.zip.Deflater.FULL_FLUSH, public static final int java.util.zip.Deflater.HUFFMAN_ONLY, public static final int java.util.zip.Deflater.NO_COMPRESSION, public static final int java.util.zip.Deflater.NO_FLUSH, private static final [B java.util.zip.Deflater.STUB_INPUT_BUFFER, public static final int java.util.zip.Deflater.SYNC_FLUSH, private [B java.util.zip.Deflater.inputBuffer, private boolean java.util.zip.Deflater.finished, private long java.util.zip.Deflater.streamHandle, private int java.util.zip.Deflater.inLength, private int java.util.zip.Deflater.inRead, private int java.util.zip.Deflater.compressLevel, private int java.util.zip.Deflater.strategy, private int java.util.zip.Deflater.flushParm]
Is there any other way that this could be solved so it can work on Android platform? I have not looked into that (yet...). IF android is a platform that should be supported maybe we could also check for android specific classes?
Something like this could be added to int javaVersion0() in DetectionUtil:
try {
        Class.forName("android.app.Application");
        return 5;
    } catch (ClassNotFoundException e) {
        //Ignore
    }

Kind regards /Johan Rask

A: Please open a issue in the issue tracker of netty. I will make sure we handle it in the next release which should be out next week.
See issue tracker is here [1].
[1] https://github.com/netty/netty/issues


text:
Q: Unable to use pair of items within a function when I go for concurrent.futures I'm trying to make use of concurrent.futures within my script below. There are two functions make_requests() and get_info() within it. When make_requests() function yields links and proxy_list, I intend to pass them within get_info() function.
Usually this is how it works:
if __name__ == '__main__':
    # "proxy_lists" is the holder of different proxies
    proxies = [proxy_lists]

    # make_requests() function yields "links" and "proxy_list"
    for item,elem in make_requests(url,proxies):

        # pass "links" and "proxy_list" to get_info() function
        get_info(item,elem)

I don't find any idea to do the same using concurrent.futures as it requires a paired loop to produce two type of elements by this make_requests() function and then pass the two type of elements within get_info() function like I did above:
import concurrent.futures

if __name__ == '__main__':
    proxies = [proxy_lists]

    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        future_to_url = {executor.submit(get_info,link): link for link in make_requests(url,proxies)}
        concurrent.futures.as_completed(future_to_url)

How can I pass pair of items within get_info() function when I use concurrent.futures?

A: I think you just want to do: executor.submit(get_info, *link)
this is because Executor.submit() is documented as:

submit(fn, *args, **kwargs)
Schedules the callable, fn, to be executed as fn(*args **kwargs)

this uses standard arbitrary argument handling to make sure that everything goes through to fn
the *link treats link as a sequence, unpacking it as arguments to submit, which in turn does then same when it eventually invokes fn


text:
Q: How does one execute a for loop inside of a function (on a function)? I'm working on creating a generic "lorem ipsum" generator in pure JavaScript. I've managed to get it working to a point where it'll pull from an array of lower-case strings in an array, joining them with a space, capitalizing the first one and putting a period a the end.
I also have it set up to a point where these sentences get pushed to a larger array and joined into a paragraph. However, I can't get the sentence generation and array push to loop any more than once inside of the function. Multiple calls to the global function will result in an appending the last sentence generated to the paragraph, however I'd like to be able to generate a random number of sentences and push them to the array on each subsequent call to the global function (and in the future, use this same pattern to generate a random number of paragraphs).
Perhaps its obvious what I'm doing wrong, but I thought calling a for-loop inside of the global function on the sentence generating function would work.
<!DOCTYPE html>

    <title>Generic Ipusm</title>

<input type="button" id="make" value="Make" onclick="makeParagraphs();" />

Click to generate!

Here's my JavaScript:
function capitalize(string) {
  return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
var arr = [];
var arr = ["this","array","of","random","words"];
var paragraph = [];

function makeParagraphs() {

  var message = [];
  var sentence;

  var paragrapher = paragraph.join(" ");
  console.log("p: " + paragrapher);
  var makeSentences = function() {

    r = Math.floor(Math.random() * 10) + 5; // Words in sentence range
    for (i=1; i<=r; i++) {

      var random = arr[Math.floor(Math.random() * arr.length)];
      message.push(random);
      var words = message.join(" ") + ".";
      var sentencer = capitalize(words);
      document.getElementById("message").innerHTML = sentencer;

    }
    var sentence = sentencer;
    console.log("s: " + sentence);
    paragraph.push(sentence);

  }
  for (i=1; i<=4; i++) {
    makeSentences();
  }
}

The last call in the loop was my attempt to generate and push 4 sentences to the paragraph. Is there a limitation in the language preventing me from calling a function multiple times like so?
Here's a fiddle (Bear in mind I'm logging the paragraph result to the console, the only text appearing in the DOM itself is the result of the last sentence generated):
http://jsfiddle.net/kmblackwood/8dvNc/

A:
Is there a limitation in the language preventing me from calling a function multiple times like so?

No. The problem is that you're falling prey to The Horror of Implicit Globals. You need to declare i. Right now, the i in your makeSentences is an implicit global, and so your loop at the end is being affected by it. That is, the i in your for loop at the end and the i in your for loop within makeSentences end up being the same (global) variable, i. So when your for loop at the end calls makeSentences the first time, makeSentences changes i to a value greater than 4 and your for loop at the end terminates. (You're missing a declaration for r, too.)
You might also consider using "strict mode" so that any decent JavaScript engine (like that in any modern browser) would tell you about the implicit global. Strict mode tells the engine that writing to an undefined symbol should be an error, not create an implicit global.
You enable strict mode by putting this:
 "use strict";

...at the top of a file or script block. It applies to everything within that file or script block.

A: The problem is that you are not doing var i; in your makeSentences function, so it's polluting the parent scope and corrupting your other loop.


text:
Q: How to check if a string contains characters or numbers C++ and C# I have probable variable value as follows "Name_1" and "1535".
I want a library function either in C++ or C# to determine if the variable value is "1535" (it is numeric) or if it is "Name_1" (it is a name).
Let me know what available functions there are?

A: Assuming that it is ok to regard any non-integer string as "character":
Int32.TryParse:
String variable = "1234";
Integer dummyresult
if Int32.TryParse(variable,dummyresult)
{
    // variable is numeric
}
else
{
    // variable is not numeric
}

A: string s = "1235";

Console.WriteLine("String is numeric: " + Regex.IsMatch(s, "^[0-9]+$"));

A: In C++, boost::lexical_cast comes in handy for this:
#include <boost/lexical_cast.hpp>
#include <iostream>

bool IsNumber(const char *s) {
  using boost::lexical_cast;

  try {
    boost::lexical_cast<int>(s);
    return true;
  } catch (std::bad_cast&) {
    return false;
  }
}

int main(int ac, char **av) {
  std::cout << av[1] << ": " << std::boolalpha << IsNumber(av[1]) << "\n";
}

EDIT: If Boost isn't available to you, try this:

bool IsNumber2(const char *s) {

  std::istringstream stream(s);
  stream.unsetf(std::ios::skipws);

  int i;
  if( (stream >> i) && stream.eof() )
    return true;
  return false;
}


text:
Q: Does my prediction model predict the right thing? Situation: students take tests that have different characteristics (length of text, number of difficult words, they may or may not contain pictures etc.). The tests can be either "Hard" or "Easy". To predict whether they ae hard or easy, I used all these features and created several accurate models (with XGBoost for example).
Now: students can either fail (0) or pass (1) a test and I want to predict whether they would fail or pass. This is similar to a recommendation system, where users like or dislike items. That's why I could apply a collaborative-filtering system that works well but obviously we need lots of data for that.
Problem: I want to use the characteristics of the tests to predict whether they would fail or pass. But if I have a dataframe like this:
studentId          testId        Length        Words      picture      result
       s1              t1            10         8.50           0            0
       s1              t2            11         9.80           1            0
       s1              t3            11        10.40           1            1
       s2              t2            11         9.80           1            0
       s2              t4            60         9.99           0            1
       s3              t7            40         6.45           0            1

And I just do (obviously with the necessary imports):
cols_to_drop = ['testId', 'studentId']
df.drop(cols_to_drop, axis=1, inplace=True)
X = df.drop('result', axis=1)
y = df['result']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=5)
model = XGBClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

Does it really answer the question? ("Would student s3 fail or pass the test t7?"). I feel like this is really just what I did for predicting whether a test is hard or easy, but this time it's "hard" or "easy" from the student's perspective.
I looked into content-based filtering and it seems so different from what I am doing here and that's why I'm worried.

A: There is a missing feature about the dataset, you need at least the grade of student. Students with higher grade generally will pass and students with lower grade generally would fail given the same test number.
Your model depends on your training datasets. You can then measure the accuracy of the model by using your test datasets. If the model gets an accuracy of 100% on the test then the model is doing the right thing.


text:
Q: Kendo UI Web grid read fails after pagination I am using Kendo UI web Grid on ASP.NET MVC 4 Application.
I noticed a strange problem in it.
I have a grid with about 72 records, which will show only 20 records per page size.
you can click on pagination to see next 20 records.
after you click on next page 2 you can see next 20 records of 72.
Here I have a jQuery call to refresh grid.
var grid = $("#myGrid").data("kendoGrid");
        grid.dataSource.read();

I noticed the problem is, when I use jQuery to read the grid again.
It is not resetting [DataSourceRequest] DataSourceRequest request and that is creating the problem.
How can i fix this.
Solution
following @paris below code resolved the issue.
var grid = $("#myGrid").data("kendoGrid");
grid.dataSource.page(1);
        grid.dataSource.read();

A: Try putting grid.dataSource.page(1); before the read() call if you don't mind refreshing the grid back to page one.


text:
Q: Ubuntu 17.04 will not boot after installing on UEFI laptop I wanted to wipe Windows 10 off my laptop and just have Ubuntu on it. I had heard that it was safe to install it on UEFI hardware so I just went through the standard install and told Ubuntu to erase everything and install Ubuntu. Once it successfully installed and I rebooted I got a screen telling me to
"reboot and select proper Boot device or insert boot media in selected Boot device and press a key"
The hard drive is selected to be the #1 boot device and there is no drive in the computer when I boot it. I've tried turning off secure boot and using CSM instead of UEFI but it still won't boot. Can someone tell me what to do?

A: I had the same problem with a toshiba computer. after many attempts at reformatting and partitioning the drive. It turned out that the system requires a 1 GB recovery partition at the beginning of the internal drive.
my fix was to use the windows recovery CD's I had made to partition the disk.
don't install windows, just set disk up.then remove all partitions except the first.(it is usually flagged as hidden system, or hidden recovery).
then install ubuntu using the free space.


text:
Q: Python - Nested if statement - else go back to original if statement I am a total noob. I am trying to loop back to the original raw_input when inside the second if statement. i want to loop the nested if statement with an option to go back to the original raw_input. hope this makes sense. Thanks
import os
os.system("clear")
start= raw_input("SUP?\n\n1: Repo\n2: Installed\n...")
if int(start)== 1:
    os.system("clear")
    while True:
        repo= raw_input("\n1: Search repo\n2: Install\n3: Back\n...")
        if int(repo)== 1:
            os.system("clear")
            search= raw_input("What are you trying to search?\n")
            os.system("apt-cache search " + search)
        if int(repo)== 2:
            os.system("clear")
            inst= raw_input("What would you like to install?\n")
            os.system("sudo apt-get install " + inst)
        else???
if int(start)==2:
    os.system("clear")
    ins=raw_input("\n1: Search Installed\n2: Delete installed\n...")

A: Put all your code inside a function and call the function again.
Now since you are new to python, function helps in breaking up your code into functional parts. Read more about them here and here
A function calling itself is called Recursion. This is an important concept and will come handy. You can read about recursion here.
def myFunc():
    start=raw_input("blah blah...")
    '''Your conditions and statements'''
    if #condition:
        #loop back to raw_input()
        myFunc()
    else:
        #your statements


text:
Q: How does CI determine it should run build? How does the TFS server (or other CI tools) determine it needs to run a build when the build trigger is set to CI? I've looked for documentation but all I could find was a vague "when a developer submits changes" or similar.
We have several solutions living in the same directory. These solutions are reusing some of the same projects:
Solution1

*

*projectA

*projectB

Solution2

*

*projectA

*projectC

If I set up builds pointing to Solution1 and Solution2 and then make changes in projectA, will TFS trigger builds for both solutions?
I know I can test this and see what happens. This is to illustrate the background of my question which actually is: how does TFS (or other CI tools) determine they need to run a build?
What if submitted changes are to files that are not in a solution? eg. build scripts.

A: If you select the Builds to run as CI Build, when TFS will trigger the build will be determined by the folders you add to your mappings on the trigger option.
Whichever source control folder you include in the Path filters under the Triggers Tab, any changes made on those folders will cause the build to run.
If you don't want the build to trigger when checkin is made in the build script file, it is better and recommended to place them in a different folder.
Thanks, let me know if it helped or not.


text:
Q: Ayuda con: almacenar en un arreglo String palabras hasta que encuentre un espacio. (Java) Mi pregunta es acerca de:
De acuerdo a la cadena que ingreso, cada vez que encuentra un espacio, que almacene la palabra en un arreglo String, es un ejercicio en en java.

Este es el codigo que solo me imprime con un salto de línea cada que encuentra un espacio
public static void escribir() {
    System.out.print("Ingrese una cadena: ");
    cadena = sc.nextLine();
}

public static void imprimir() {
    for (int i = 0; i < cadena.length(); i++) {
        letra[i] = cadena.charAt(i);
        if (letra[i] == ' ') {
            System.out.print("\n");
        }
        System.out.print(letra[i]);;
    }
}

public static void main(String[] args) {
    escribir();
    imprimir();
    sc.close();
}

}

A: En este caso puedes usar el método split() para crear un array de elementos a partir del token de separación de los mismos que en este caso sería el espacio en blanco, para esto puedes usar la como REGEX "\s+".
public static void imprimir() {

    //separa por espacios y crea array
    String palabras[] = cadena.split("\\s+");

    //Imprime elementos en array

     for (String palabra : palabras){
        System.out.print(palabra+"\n");
     }

}

De esta forma imprimirá:
Somos
libres,
seamoslo
siempre


text:
Q: run iperf broadcast traffic on linux I am in the domain 192.168.1.xxx. I need to send broadcast traffic from a pc connected to a accesspoint to the android device wirelessly after connecting with a network through WiFi.
running iperf command iperf -c 192.168.1.255 -i 2 -t 60 -b 10000 -u on a Ubuntu 12.04 machine and running the command iperf -s -i 2 -u in adb shell.
But the client is unable to get the broadcast traffic and gives error as :
 read failed : connection refused.

A: you cannot use iperf in broadcast mode.
if you are just testing whether broadcast works, you could try something like
# server
netcat -l -u -p 54321

# host
echo "foo" | netcat -ub 192.168.1.255 54321

note however, that on some systems, netcat might not be able to go into broadcast mode, so you might end up writing your own networking code.

A: You can't do iperf broadcast on linux.

A: Connection refused generally happens when the server and client are not on the same network or make sure the server IP address that you are specifying in the client is correct.

A: You can leverage DHCP's properties, DHCP is advertised with a broadcast DISCORVERY package, so by putting a DHCP-server and a DHCP-client (normal host) at the ends of your network you can test broadcast traffic within it.
If you get an address -> you're OK
If you keep waiting and nothing happens -> something went wrong
Hope this helps you ;)


text:
Q: How to show my child widget on top of all other child widgets and the parent window of my app? I searched this everywhere, but couldn't find a solution that works. Basically I want to be able to have my child widget to show on top of the parent window, which already works by default. But there are other child widgets in this app.
I want my child widget to be on top of all of these widgets. I can't use WindowStaysOnTopHint because that makes my widget on top of every window outside the scope of the parent window.
I want to be limited by the parent window, where other applications can still be on top of my child widget, but within my app, I want my child widget to be the topmost.
How can I achieve this?


text:
Q: org.h2.jdbc.JdbcSQLException: The object is already closed For the life of me I cannot see how it "is already closed"
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RsetTest2 {

    public static void main(String[] args) throws Exception {
        String dbpath = "jdbc:h2:c:/mydb;IFEXISTS=TRUE;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE";

        Connection conn = null;
        System.setProperty("h2.bindAddress", "127.0.0.1");
        Class.forName("org.h2.Driver");
        conn = DriverManager.getConnection(dbpath, "sa", "sa");
        conn.setAutoCommit(false);
        System.out.println("success.  querying database for latest values...");

        Statement qry = conn.createStatement();
        String sql = "select id from CONSTITUENTS where manager = 'abc' limit 1";
        ResultSet rset = qry.executeQuery(sql);
        while (rset.next()) {
            int id = rset.getInt("id");
            System.out.println(id);
            qry.executeUpdate("insert into PAYREQUESTS (constituent, inblock) values (" + id + ", 238)");
        }
        rset.close();
        qry.close();
    }
}

here is the output:
success.  querying database for latest values...
103
Exception in thread "main" org.h2.jdbc.JdbcSQLException: The object is already closed [90007-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.message.DbException.get(DbException.java:144)
    at org.h2.jdbc.JdbcResultSet.checkClosed(JdbcResultSet.java:3208)
    at org.h2.jdbc.JdbcResultSet.next(JdbcResultSet.java:130)
    at RsetTest2.main(RsetTest2.java:22)

where 22 corresponds to the "while (rset.next()) {" line
the DB is returning values, see that println statement that gives us 103.
and even weirder, if I // comment out the executeUpdate line, it all completes normally

A:
Exception in thread "main" org.h2.jdbc.JdbcSQLException: The object is already closed [90007-196]

Your problem is that you are reusing the SQL Statement inside of your while loop.  As soon as you call the qry.executeUpdate(...) method in the loop, the ResultSet rset associated with the previous statement is closed, hence the error.   It is the while(rset.next()) statement that is called after the first executeUpdate(...) in the loop that fails.
If you use a new statement in the loop then it should work.
Statement qry = conn.createStatement();
String sql = "select id from CONSTITUENTS where manager = 'abc' limit 1";
ResultSet rset = qry.executeQuery(sql);
while (rset.next()) {
    int id = rset.getInt("id");
    System.out.println(id);
    // we can't reuse the same Statement here so we need to create a new one
    conn.createStatement().executeUpdate("insert into PAYREQUESTS ...");
}

You might consider keeping a collection of necessary updates and then issue the updates at the end of the loop.

and even weirder, if I // comment out the executeUpdate line, it all completes normally

Yep, that sounds right.  Not weird at all.  :-)

A: Also for simplifying your code you can use try-with-resources statement that utilizes
java.lang.AutoCloseable interface, thus you can get rid of lines:
    rset.close();
    qry.close();

The whole block can look somehow like this:
        try (ResultSet rset = conn.createStatement().executeQuery("select id from CONSTITUENTS where manager = 'abc' limit 1")) {
            String insertSQL = "insert into PAYREQUESTS (constituent, inblock) values ('%d', 238)";
            while (rset.next()) {
                int id = rset.getInt("id");
                Savepoint savePoint = conn.setSavepoint("beforeInsert");
                try {
                    conn.createStatement().executeUpdate(String.format(insertSQL, id));
                    conn.commit();
                } catch (SQLException ex) {
                    conn.rollback(savePoint);
                    //log exception
                }
            }
        } catch (SQLException e) {
            //log exception
        }

Since your connection has auto-commit mode equals false maybe it make sense to possible harmful action.


text:
Q: prove that MN is a characteristic subgroup Prove that M,N characteristic in G implies that MN is characteristic in G.
How do I prove this? Not sure where to start.

A: $$M,N\,\operatorname{char} G\Longrightarrow \phi(M)=M\,,\,\phi(N)=N\,\,\,\,\forall\,\phi\in\operatorname{Aut}(G)$$
so
$$\forall\,mn\in MN\,\,,\,\phi(mn)=\phi(m)\phi(n)\in MN\Longrightarrow \phi(MN)\subset MN$$
and this is enough (why?)

A: Here's a start: If $\phi$ is an automorphism of $G$, then for any $mn \in MN$ (where $m \in M$ and $n \in N$) we have $\phi(mn) = \phi(m)\phi(n)$. Try to show that $\phi(MN) = \phi(M)\phi(N)$ and use this to prove the result.


text:
Q: ambari + namenode HA and hdfs zkfc -formatZK we have production HDP cluster ,
HDP version - 2.6.5
Ambari version - 2.6.1

We are performing now the change hostname configuration according to the document - https://docs.cloudera.com/HDPDocuments/Ambari-2.7.0.0/administering-ambari/content/amb_changing_host_names.html
The last stage is talking about – in case NameNode HA enabled , then need to run the following command on one of the name node machines
hdfs zkfc -formatZK -force

since we have active name node and standby name node ,  we assume that our namenode is HA enable!

but we want to understand  what are the risks when doing the following cli on one of the namenode machines
hdfs zkfc -formatZK -force

is the below command is safety to run without risks ?


text:
Q: Hamiltonian Path Algorithm Time-Complexity I am writing a program searching for Hamiltonian Paths in a Graph. It works by searching all possible permutations between the vertices of the graph, and then by checking if there is an edge between all consecutive vertices in each permutation.
I calculated the time-complexity to be O(n)=n!*n^2.
To calculate the time-complexity I thought :
to calculate each permutation, I loop through the list of vertices. What's more there is n! permutations, and then for each permutation I loop again through the list of vertices to check if there is an edge between two consecutive vertices. So this makes O(n)=n!*n*n.
Did I make a mistake in this calculation ?
I think I made a mistake, because I measured the time for the program to execute for different sizes of graphs, and the complexity looks more like O(n)=n!

Here are some values of how much time the program took to execute, with n the number of vertices in the graph.
On a Machine with 3.5GHz i7 Processor and 16 GB RAM:
n=2 : 0.000025 s
n=3 : 0.000041 s
n=4 : 0.00013 s
n=5 : 0.00065 s
n=6 : 0.0045 s
n=7 : 0.039 s
n=8 : 0.31 s
n=9 : 3.2 s
n=10 : 36 s
n=11 : 455 s

Here is my code :
main
graph=Graph([[1,4],[0,2,3],[1,3],[1,2,4],[0,3]]) #n = 5 (number of nodes)
ham = hamiltonianPaths0(graph)

hamiltonianPaths0 function
def hamiltonianPaths0(graph, circuit=False):
    name = "circuit" if circuit else "path"
    f=0
    paths=[]
    for i in permutations(graph.vertices):
        k=1
        for j in range(len(i)-1+int(circuit)):
            if [i[j],i[(j+1)%len(i)]] in graph.edges:
                #print("Edge from {} to {}".format(i[j], i[(j+1)%len(i)]))
                k+=1
            if k==len(i)+int(circuit):
                print("{} is a hamiltonian {} !".format(i,name))
                f+=1
                paths.append(i)

    print("{} hamiltonian {}(s) found !".format(f,name))
    return paths

permutations function
def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

PS : the graph class makes a graph from a list specifying for each vertex with which other vertex it is linked. for example : Graph([[1],[0,2],[1]]) will produce a graph with 3 vertex (0,1,2) with 0 linked to 1, 1 linked to 0 and 2 and 2 linked to 1).
And Graph.vertices is a list containing all the vertices of a graph.

A: O(n!) and O(n! * n^2) are the same complexity.  Let's "overshoot" by a lower-order amount on the right side of this and reduce the expression.
n! * n * n <= n! * (n+1) * (n+2)
n! * n * n <= (n+2)!

However, O(n!) == O((n+2)!)
Q.E.D.


text:
Q: Converting string_view to null terminated c string How would you convert a std::string_view to a null-terminated c string? I've passed a string_view into a function, and need to pass that into another function, which takes a const char* parameter. However, looking at this documentation for string_view, it says

data() may return a pointer to a buffer that is not null-terminated. Therefore it is typically a mistake to pass data() to a routine that takes just a const CharT* and expects a null-terminated string.

Is there a way to properly get a null-terminated c string from a string_view?


text:
Q: twilio upload file in assets for manipulation I am trying to record multiple voicemail and append them in real time.For latency purpose ,planing to host the function in twilio function . I want to upload recording  file in asset from function,for cutting file.Is there any way to send recording file to asset from function  ?
I know how to retrieve mp3 uri of recording on call


text:
Q: How to view/download private blobs from blob URL? I have typescipt application which uploads the files to Azure blob storage(Private access).
Now I need to view the files in browser from the blob URL.
How can we view the private blob files from blob URL. I have SAS token associated to that storage account.
But appending the SAS token to the blob URL is not working.
Please suggest on the way to achieve this.
URL:
https://teststorage.blob.core.windows.net/container1/folder2/forest.jpg
URL with SAS token:
https://teststorage.blob.core.windows.net/container1/folder2/forest.jpg?

A: I guess the SAS token you got is wrong. You could try to generate the SAS token in Azure Portal(navigate to your blob -> Generate SAS), and get blob with GET https://<storage-name>.blob.core.windows.net/<container-name>/myblob.txt?<sas-token>.

The sample code using generateBlobSASQueryParameters to generate the container SAS token. If you want the blob SAS, add blobName to parameters.
var storage = require("@azure/storage-blob")

// Use StorageSharedKeyCredential with storage account and account key
const sharedKeyCredential = new storage.StorageSharedKeyCredential(account, accountKey);

var expiryDate = new Date();
startDate.setTime(startDate.getTime() - 5*60*1000);
expiryDate.setTime(expiryDate.getTime() + 24*60*60*1000);

const containerSAS = storage.generateBlobSASQueryParameters({
    expiresOn : expiryDate,
    permissions: storage.ContainerSASPermissions.parse("rwl"),
    protocol: storage.SASProtocol.Https,
    containerName: containerName,
    startsOn: startDate,
    version:"2018-03-28"
}, sharedKeyCredential).toString();

You could test your SAS token with AnonymousCredential in typescipt sample.


text:
Q: OBS Studio crashes when using NVENC Please correct me if I am posting on the wrong site (this seemed the best place to put it)
So I was setting up OBS studio for recording my gameplay of MC but when I pressed record it crashed. I tried QSV and x264 and they worked. So it was just NVENC. I have no idea what is going on but I really want to record, I heard NVENC is the best encoder. Here is my log:
pastebin.com


text:
Q: Want my Button to remain dark when clicked For the form on this page: http://16q.47c.myftpupload.com/get-a-quote/
I want to make the buttons "Round Trip" / "One Way", when clicked, keep their red background.
I used Gravity Forms to build the form and customized the CSS to make it look that way. Those 2 "buttons" are actually Radio Buttons.
I don't have access to the HTML so a CSS-only fix would be great (unless you know how to edit the HTML of a Gravity Form)!
Appreciate the help in advance :)

A: You just have to add :focus to whichever css class you have used for those radio buttons, follow the example given below,

.btnbtn{
background-color:blue;
}

.btnbtn:focus{
background-color:red;
}

<button class="btnbtn">abcd</button>

This should work Perfectly.

A: If you can have access to the CSS, try adding the radio button :checked option and have the background-color to red.
Just see the code snippet and try to do.

/*https://codepen.io/kevinfarrugia/pen/pJZezE*/

.hungry .selection {
  margin-bottom: 1em;
}

.hungry .selection label {
  display: inline-block;
  width:8em;
  background-color: #42b4d6;
  border-radius: 6px;
  color: #ffffff;
  padding: 0.5em;
  cursor: pointer;
}

.hungry .selection label:hover {
  background-color: #5fc0dc;
}

.hungry .selection input[type=radio] {
  display: none;
}

.hungry .selection input[type=radio]:checked ~ label {
  background-color: #f1592a;
}

    <input id="pizza" name="hungry" type="radio">
    Pizza

    <input id="burger" name="hungry" type="radio">
    Burger + Chips

    <input id="bread" name="hungry" type="radio">
    Hobz biz-zejt!

A: Since the radio button get selected when you click the button, you can use a checkbox hack(radio button hack)
input[name="input_11"]:checked + #label_2_11_0,
input[name="input_11"]:checked + #label_2_11_1 {
  background-color: #8d181b !important;
  color: white !important;
}

this will select the next sibling with label tag of a input with name="input_11" and change it's background color. I'm using name="input_11" because that's what the radio button had in your website.


text:
Q: What's the difference between grep "str" . and grep "str" * In grep "str" *
Does it mean grep everything where grep executed?
and what about  grep -r "str" . which has more results than the former one

A: When you run grep str *, the shell will expand the * to match all filenames in the current directory, unless they start with a dot, and will then pass that list of files to the grep command.
When you run grep -r str ., the shell has nothing to expand itself. The grep command, however, reacts to the -r option by going through its argument list and recursively descending into all directories.
So, there are at least three differences:

*

*grep -r will find hidden files

*grep -r will go through subdirectories

*grep -r also works in directories with lots of files. You may get an error message saying the command line gets too long for grep str * in that case.

A: grep

Will search for a pattern, the last argument is the files to search, so:
grep str *

Will search all files in the current directory(matched with * as a wildcard) for the pattern "str".
grep -r str .

Will search Recursively(so inside directories and such) for the pattern str starting with the current directory(the single dot is the current dir, two dots is the previous dir).

A: grep  "str" * # search a string str in all files in current directly but not sub directories
grep -r "str" . # search a string str recursively in cireent directory and in all sub directories in all file whose file name has a single character

A: bash always expand * ? [...] ..  if you did not set noglob
when you use "." , grep will search from current directory, but when you use one of
above symbols, bash expands your command, then call grep


text:
Q: How to declare repositories in Gradle generated POMs I am publishing an artifact A to a self maintained maven repository on GitHub. The project has several transitive dependencies B, C, D which are hosted in different repositories. The dependencies B, C, D are specified in the gradle generated pom.xml (uploadArchives) of A but not the paths to the repositories. Therefore, the transitive dependencies B, C, D are not downloaded when A is specified as a dependency in another project.
Is it possible to tell gradle to include the urls of the maven repositories of B, C, D in the pom.xml of A?

A: The way to do this is to customize the generated POM. Here is an example, assuming that the maven plugin is used for publishing:
uploadArchives {
    repositories {
        mavenDeployer {
            // add further information to the generated POM
            // syntax maps 1:1 to POM syntax
            pom.project {
                // could also generate this programmatically
                // based on the repos declared in the build
                repositories {
                    repository {
                        id 'myrepo'
                        url 'http//my.repo.com'
                    }
                }
            }
        }
    }
}

The new, incubating maven-publish plugin offers a similar hook.
Note that Gradle itself doesn't honor repositories declared in POMs when resolving dependencies, but only repositories declared by your build. Also check out http://www.sonatype.com/people/2009/02/why-putting-repositories-in-your-poms-is-a-bad-idea/.


text:
Q: List View Fragment Won't Display I am trying to display a list in my main activity using a ListFragment. The list is populated by my custom ArrayAdapter that uses a custom object. I am having trouble getting this list to show in the app. When I debug, it doesn't show any errors but the app immediately crashes.
Here is my fragment
Edit: I have tried several responses and have narrowed down the issue to the momentObjectListView.setAdapter(momentObjectAdapter) in the ListViewFragment. I cannot find a reason why the momentObjectAdapter would be null so it must be momentObjectListView however I cannot find where the issue stems. Any help would be much appreciated. My activity_main.xml, fragment, main activity, and adapter code are all included.
public class ListViewFragment extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    Activity myAct = getActivity();
    View view = inflater.inflate(R.layout.activity_main, container, false);
    ListView momentObjectListView = (ListView)view.findViewById(R.id.list_item);
    //ListView momentObjectListView = getListView();

    MomentObjectAdapter momentObjectAdapter = new MomentObjectAdapter(myAct, R.layout.moment_object_list_item);

    //momentObjectListView.setAdapter(momentObjectAdapter);

    List<MomentObject> myMoments = getMoments();
    for(final MomentObject entry : myMoments) {
        momentObjectAdapter.add(entry);
    }

    //ListViewFragment.this.setListAdapter(momentObjectAdapter);
    momentObjectListView.setAdapter(momentObjectAdapter);

    return view;
}

private List<MomentObject> getMoments() {

    // Let's setup some test data.
    // Normally this would come from some asynchronous fetch into a data source
    // such as a sqlite database, or an HTTP request

    final List<MomentObject> entries = new ArrayList<MomentObject>();

    for(int i = 1; i < 50; i++) {
        entries.add(
                new MomentObject(
                        "Test Entry " + i,
                        "Anonymous Author",
                        new GregorianCalendar(2011, 11, i).getTime(),
                        R.drawable.photoicon
                )
        );
    }

    return entries;
}

}
And here is my activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#ffffffff">

<fragment android:name="com.malatras.moment2.ListViewFragment"
    android:id="@+id/list"
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

Please let me know if there is anything I need to provide to solve this.
LogCat:
    e02-24 18:54:29.119    2325-2325/com.malatras.moment2 I/art﹕ Not late-enabling -Xcheck:jni (already on)
02-24 18:54:29.191    2325-2325/com.malatras.moment2 D/AndroidRuntime﹕ Shutting down VM
02-24 18:54:29.191    2325-2325/com.malatras.moment2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.malatras.moment2, PID: 2325
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.malatras.moment2/com.malatras.moment2.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
            at android.app.Activity.setContentView(Activity.java:2144)
            at com.malatras.moment2.MainActivity.onCreate(MainActivity.java:11)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
            at com.malatras.moment2.ListViewFragment.onCreateView(ListViewFragment.java:34)
            at android.app.Fragment.performCreateView(Fragment.java:2053)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:870)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1045)
            at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1147)
            at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2116)
            at android.app.Activity.onCreateView(Activity.java:5282)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
            at android.app.Activity.setContentView(Activity.java:2144)
            at com.malatras.moment2.MainActivity.onCreate(MainActivity.java:11)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

MainActivity:
public class MainActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

MomentObjectAdapter:
    public final class MomentObjectAdapter extends ArrayAdapter<MomentObject> {

    private final int momentObjectLayoutResource;

    public MomentObjectAdapter(final Context context, final int momentObjectLayoutResource) {
        super(context, 0);
        this.momentObjectLayoutResource = momentObjectLayoutResource;
    }

    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {

        // We need to get the best view (re-used if possible) and then
        // retrieve its corresponding ViewHolder, which optimizes lookup efficiency
        final View view = getWorkingView(convertView);
        final ViewHolder viewHolder = getViewHolder(view);
        final MomentObject entry = getItem(position);

        // Setting the title view is straightforward
        viewHolder.titleView.setText(entry.getTitle());

        // Setting the subTitle view requires a tiny bit of formatting
        final String formattedSubTitle = String.format("By %s on %s",
                entry.getAuthor(),
                DateFormat.getDateInstance(DateFormat.SHORT).format(entry.getPostDate())
        );

        viewHolder.subTitleView.setText(formattedSubTitle);

        // Setting image view is also simple
        viewHolder.imageView.setImageResource(entry.getIcon());

        return view;
    }

    private View getWorkingView(final View convertView) {
        // The workingView is basically just the convertView re-used if possible
        // or inflated new if not possible
        View workingView = null;

        if(null == convertView) {
            final Context context = getContext();
            final LayoutInflater inflater = (LayoutInflater)context.getSystemService
                    (Context.LAYOUT_INFLATER_SERVICE);

            workingView = inflater.inflate(momentObjectLayoutResource, null);
        } else {
            workingView = convertView;
        }

        return workingView;
    }

    private ViewHolder getViewHolder(final View workingView) {
        // The viewHolder allows us to avoid re-looking up view references
        // Since views are recycled, these references will never change
        final Object tag = workingView.getTag();
        ViewHolder viewHolder = null;

        if(null == tag || !(tag instanceof ViewHolder)) {
            viewHolder = new ViewHolder();

            viewHolder.titleView = (TextView) workingView.findViewById(R.id.moment_object_title);
            viewHolder.subTitleView = (TextView) workingView.findViewById(R.id.moment_object_subtitle);
            viewHolder.imageView = (ImageView) workingView.findViewById(R.id.moment_object_icon);

            workingView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) tag;
        }

        return viewHolder;
    }

    /**
     * ViewHolder allows us to avoid re-looking up view references
     * Since views are recycled, these references will never change
     */
    private static class ViewHolder {
        public TextView titleView;
        public TextView subTitleView;
        public ImageView imageView;
    }

}

moment_object_list_item:
<?xml version="1.0" encoding="utf-8"?>

<!-- Layout for individual news entries in a list -->
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <!-- Icon shown next to the title/subtitle -->
        <ImageView
            android:id="@+id/moment_object_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:padding="3dp" />

    <!-- Title of the news entry -->
        <TextView
            android:id="@+id/moment_object_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/moment_object_icon"
            android:layout_alignTop="@id/moment_object_icon"
            android:layout_margin="5dp"
            android:textSize="14sp"
            android:textStyle="bold" />

    <!-- Subtitle contains author and date -->
        <TextView
            android:id="@+id/moment_object_subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/moment_object_title"
            android:layout_below="@id/moment_object_title"
            android:textSize="12sp" />

    </RelativeLayout>

A: Change in your XML file this line :  android:id="@+id/list"
to:
android:id="@id/android:list
and in ListViewFragment change this :  ListView momentObjectListView =(ListView)view.findViewById(R.id.list);
to this:
ListView momentObjectListView = (ListView)view.findViewById(android.R.id.list);

A: In your Logcat file, it says

android.view.InflateException: Binary XML file line #9: Error
inflating class fragment

This means an xml file is not proper. Also deeper in the log,

The code MainActivity.onCreate(MainActivity.java:11)
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
null object reference at
com.malatras.moment2.ListViewFragment.onCreateView(ListViewFragment.java:34)
...
ListViewFragment.onCreateView(ListViewFragment.java:34)

Need to load file ListViewFragment.java too. In order to save time, perhaps post more files.

A: Another possible good code change is to modify ListViewFragment definition from:
public class ListViewFragment extends ListFragment {

to:
public class ListViewFragment extends Fragment implements AbsListView.OnItemClickListener {

The OnItemClickListener is optional.
The reason I say this is that MainActivity already hosts ListView object through ListActivity. Another reason, Android Studio wizard generates the "to" suggested code. And it sounds good to me.
Another way is to remove ListActivity from MainActivity to just Activity, with the same reason.
All these suggestions may be considered to be code style however.

A: This code I don't like and not compatible with your method getMoments is:
for(final MomentObject entry : getMoments()) {
        momentObjectAdapter.add(entry);
    }

For now try this for a quick sample fix:
List<MomentObject> myMoments = getMoments();
for(final MomentObject entry : myMoments) {

The reason is getMoments() in the for loop is evaluated dynamically. I think so even though you declared it with final.
In the log,

Attempt to invoke virtual method 'void
  android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
  null object reference

I believe object momentObjectListView is null. I could not find the UI in fragment_list_view.xml. It is however in activity_main.xml. Sample code :
View view = inflater.inflate(R.layout.activity_main, container, false);
ListView momentObjectListView = (ListView)view.findViewById(R.id.list);

Sample layout element for a ListFragment in activity_main:
 <fragment android:name="com.malatras.moment2.ListViewFragment"
 android:id="@+id/list"
 ...>

A good webpage for explaining layouts is required for understanding the basics @ Layouts .


text:
Q: UNIX to datatime conversion I am trying to convert the data type of a date/time column from int64 to datetime but it's in UNIX so by default the date is set to 1970.
I've tried changing the unit to seconds, milliseconds, nanoseconds, microseconds, and days but the result is still set on 1970.
# Convert the timestamp column to datetime
weather['time_stamp'] = pd.to_datetime(weather['time_stamp'],origin='unix', unit='ms')

# After converting the timestamp column to datetime datatype.
# Create a datetime object from the year, month and day column as well as
# the hour and minute column.

weather['year'] = weather['time_stamp'].map(lambda x : x.year)
weather['month'] = weather['time_stamp'].map(lambda x : x.month)
weather['day'] = weather['time_stamp'].map(lambda x : x.day)
weather['hour'] = weather['time_stamp'].map(lambda x : x.hour)
weather['minute'] = weather['time_stamp'].map(lambda x : x.minute)
weather.take(np.random.permutation(len(weather))[:15]

What am I doing wrong? I've used this method before and it worked well.
I even added
format='%Y/%m/%d %H:%M:%S' to the syntax but still no change.
This is the input:
time_stamp
1545003901

This is the output:
time_stamp                  year  month  day  hour minute
1970-01-18 20:42:22.520     1970  1      18   20   42

A: Your input has ten digits, so this perhaps is the unix time in seconds (seconds since 1970/1/1). If so, you need to set unit="s".
pd.to_datetime(1545003901, unit="s")
#Timestamp('2018-12-16 23:45:01')


text:
Q: Declaring class methods in class_methods or included require 'active_support/concern'

module M
  extend ActiveSupport::Concern

  included do
    def self.b
      puts 'b'
    end
  end

  class_methods do
    def a
      puts 'a'
    end
  end
end

class H
  include M
end

Though class_methods is the standard way to define class methods in ActiveSupport::Concern, I do find a few examples where people declare class methods in included by using self.
Both works, so are there edgecases if class methods are defined inside included?


text:
Q: Can congruence or similarity be used to find the length of a triangle when some of its sides have odds proportionality? In my book there is this problem but I don't know if congruence or similarity can be used as means to solve it.
The problem is as follows:

A CTV broadcasting tower is resting atop a square flat base in the
  highest hill of Taipei. The tower is supported by five cables which
  are held tight to the ground by four retention screws labeled
  $\textrm{A}$, $\textrm{C}$, $\textrm{D}$, $\textrm{E}$, $\textrm{F}$
  as indicated in the picture. The radio technician notices that the
  length between $\textrm{HC = 3 feet}$, meanwhile $3AB=5BC$ and $m\angle ABH= 3m \angle HBC$
  From this information find the distance between $\textrm{H}$ and
  $\textrm{A}$.

The alternatives given on my book are:
$\begin{array}{ll}
1.&\textrm{13 feet}\\
2.&\textrm{11 feet}\\
3.&\textrm{9 feet}\\
4.&\textrm{10 feet}\\
\end{array}$
What I attempted to do is shown in the figure from below.

But other than just putting what is stated in the problem I could not reach any further in my observations. I tried hardly to imagine different ways to arrange the triangles in a manner that they could be used as congruence (from which I noticed one). But other than that I coudn't find more.
Therefore can somebody help me to find the answer using mainly simple euclidean geometry?. i.e using constructions and tying it with similarity or congruence or something like this? This is what basically gets me stuck.
Although I welcome an answer using plane trigonometry this question was supposedly been able to be solved without requiring trig or any advanced math tools, hence I hope somebody could help me with a trig free approach.

A:
Draw the line BD such that $\angle DBH = \angle CBH$. Then, $DH = HC = 3$ feet. Apply the sine rule to triangles BAD and BDC,
$$\frac{\sin 2\alpha}{\sin(180-\beta)} = \frac{AH - 3}{AB},\>\>\>\>\>
\frac{\sin 2\alpha}{\sin\beta} = \frac{6}{BC}$$
Use the fact $\sin(180-\beta)=\sin\beta$ to get
$$\frac{AH-3}{6}=\frac{AB}{BC}=\frac 53$$
which yields $AH = 13 \>\text{feet}$.


text:
Q: A Codility test that needs to be solved I can not understand the question, can someone clarify it a little bit ?
Update : here is my solution using Kadane algorithm but it fails at the following arrays:
Example test:    [-8, 3, 0, 5, -3, 12]
WRONG ANSWER  (got 17 expected 12)

Example test:    [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]
WRONG ANSWER  (got 12 expected 8)

int max_so_far = 0, max_ending_here = 0;

    for (int i = 0; i < A.size(); i++)
    {
        max_ending_here = max_ending_here + A[i];
        if (max_ending_here < 0)
            max_ending_here = 0;
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
    }
    return max_so_far;

A: The function can look as it is shown in the demonstrative program
#include <iostream>
#include <algorithm>
#include <vector>

long long int solution( const std::vector<int> &v )
{
    long long int max_sum = 0;

    for ( auto it = v.begin();
         ( it = std::find_if( it, v.end(), []( int x ) { return !( x < 0 ); } ) ) != v.end();
        )
    {
        long long int sum = 0;

        while ( it != v.end() && !( *it < 0 ) ) sum += *it++;

        if ( max_sum < sum ) max_sum = sum;
    }

    return max_sum;
}

int main()
{
    std::vector<int> v = { 1, 2, -3, 4, 5, -6 };

    std::cout << solution( v ) << std::endl;

    return 0;
}

Its output is
9

You can rewrite the function using indices instead of iterators.
As for your function then it is incorrect at least relative to this condition
    if (max_ending_here < 0)
        max_ending_here = 0;

because instead of checking the current element whether it is less than zero the condition checks the current sum of elements.


text:
Q: Numpy Arrays in Keras I have a list of numpy arrays and a list of labels that I would like to train a CNN with in keras.
What object do I need to convert the list of numpy arrays into?
Would it be a tensorflow tensor object (as in tf.convert_to_tensor) or something different?
I suppose I just would like to understand how I go from raw np arrays to something that can be tangibly trained on in keras.


text:
Q: Pandas subtracting rows gives wrong result My pandas dataframe consists of a Column "timeStamp", the elements of which are of type datetime.datetime. I'm trying to obtain the difference between two consecutive rows of this column to obtain the time spent in seconds. I use the following piece of code for it.
df["Time"] = df["timeStamp"].diff(0).dt.total_seconds()

Generally it's working fine, however, I keep getting 0.0 as a result of this operation in quite a few instances even when it's not the case.
Examples values that result in 0.0:
import pandas as pd
import datetime
import numpy as np

df = pd.DataFrame({'S.No.': [1, 2, 3, 4], 'ABC': [datetime.datetime(2019,2,25,11,49,50), datetime.datetime(2019,2,25,11,50,0),datetime.datetime(2019,2,25,11,50,7),datetime.datetime(2019,2,25,11,50,12)]})

df["Time"] = df["ABC"].diff(0).dt.seconds

print df

Note: using python2.7

A: Use
df["Time"] = df["timeStamp"].diff().dt.total_seconds()

instead.
The argument in diff specifies the number of rows above of the row with which you want to calculate the difference. Now, you're filling it with 0, so your subtracting a value from itself, which will always give 0. By leaving it empty, it uses the default value 1, so the difference with 1 row above.

A: Try this:
print(df["timestamp"].diff().fillna(0).dt.seconds)

0     0
1    10
2     7
3     5

df['difference']=df["timestamp"].diff().fillna(0).dt.seconds
print(df)

            timestamp  difference
0 2019-02-25 11:49:50           0
1 2019-02-25 11:50:00          10
2 2019-02-25 11:50:07           7
3 2019-02-25 11:50:12           5


text:
Q: Need some advice on DynamoDb Tables schema I am building a review site.
It will review hotels, restaurants and cafes (lets call them listings),
so there will be three categories of listings.
Each of these listings will have reviews.
Now end users will be able to like / dislike the listing or individual reviews.
I am using AWS Amplify to build this site.
The way the front end will query the data would as follows.

*

*A search box may want to see restaurants in a given location say Sydney / London etc.

*when the list of restaurants has come up, the end user can click on each restaurant to see the reviews for this restaurant.

*The end user can like / dislike the restaurant or do the same like / dislike for individual reviews.

I am new to NoSQL Database concepts, so need some advice on how this should be structured. Below image shows what I have in mind.

A: NoSQL schema modeling should performed based on the access patterns of the data. Based on the access patterns you provided

*

*Restaurants for a given location can be searched the Listing
Secondary Partition and in addition to that you can also sort them
using the listing rating.

*For each restaurant you can get the
reviews associated with that. Are you storing the original review
blobs here? If so be cautioned about the maximum row size and
consider compressing the review or use S3 to store the original
review.

*Incrementing the columns for Review_Likes and Dislikes
would solve your use case 3.

However, to completely validate your schema I need the following information. In Listing table the Primary Partition key - Category values are in very small number (Hotel, Cafe, Restaurant, etc.) and this can cause hot partitions. DynamoDB expects the primary keys to be uniformly distributed for optimal performance.


text:
Q: Dataweave 2 How to map Object to JSON Arrays of Object Have a JSON Object which I need to map to an array of objects but can't get the structure right after many tries. Would it be better, if the script gets very complex and damages readability and ease of maintenance, to have this process divided into to scripts instead of a one dataweave 2 script?
Current output:
{
  "batchId": "71f7a8534907940cb1b5",
  "status": "1",
  "products": [
    {
      "materialNumber": "9780429435942",
      "errorMessages": [
        "Failure",
        "Mistake"
      ],
      "materialNumber": "9780429435950",
      "errorMessages": [
        "Exception"
      ]
    }
  ]
}

Desired output:
{
  "batchId": "71f7a8534907940cb1b5",
  "status": "1",
  "products": [
    {
      "materialNumber": "9780429435942",
      "errorMessages": [
        "Failure",
        "Mistake"
      ]
    },
    {
      "materialNumber": "9780429435950",
      "errorMessages": [
        "Exception"
      ]
    }
  ]
}

DW2 script:
%dw 2.0
output application/json
var failedProducts = vars.response.materials filterObject ((product) -> product.status == "1")
---
{
    batchId: vars.batchId,
    status: vars.overallStatus,
    products: [
        failedProducts mapObject (value,key,index) -> {
            materialNumber: value.materialNumber,
            errorMessages: value.messages.*item.*msgText
        }
    ]
}

Source data:
<response>
    <overallStatus>1</overallStatus>
    <materials>
      <item>
        <status>0</status>
        <materialNumber>9781231231231</materialNumber>
        <messages>
          <item>
            <msgText>Success</msgText>
          </item>
        </messages>
      </item>
      <item>
        <status>1</status>
        <materialNumber>9780429435942</materialNumber>
        <messages>
          <item>
            <msgText>Failure</msgText>
          </item>
          <item>
            <msgText>Mistake</msgText>
          </item>
        </messages>
      </item>
      <item>
        <status>1</status>
        <materialNumber>9780429435950</materialNumber>
        <messages>
          <item>
            <msgText>Exception</msgText>
          </item>
        </messages>
      </item>
    </materials>
</response>

A: Here's code (different than yours) that give you the desired result:
%dw 2.0
output application/json
var xml = '
<response>
    <overallStatus>1</overallStatus>
    <materials>
      <item>
        <status>0</status>
        <materialNumber>9781231231231</materialNumber>
        <messages>
          <item>
            <msgText>Success</msgText>
          </item>
        </messages>
      </item>
      <item>
        <status>1</status>
        <materialNumber>9780429435942</materialNumber>
        <messages>
          <item>
            <msgText>Failure</msgText>
          </item>
          <item>
            <msgText>Mistake</msgText>
          </item>
        </messages>
      </item>
      <item>
        <status>1</status>
        <materialNumber>9780429435950</materialNumber>
        <messages>
          <item>
            <msgText>Exception</msgText>
          </item>
        </messages>
      </item>
    </materials>
</response>
'
var data = read(xml,"application/xml")
var batchId = "71f7a8534907940cb1b5"
---
{
    batchId: batchId,
    status: data.response.overallStatus,
    products:
        data.response.materials.*item filter ($.status as Number != 0)
        map {
            materialNumber: $.materialNumber,
            errorMessages: [$.messages.item]
        }
}

I did use DW variables instead of the vars you have.

A: The problem which you are facing is because XML does not natively support arrays. So while reading an XML using dataweave you need to explicitly mention that you want a certain path to be read as an array, which is exactly what you did when you wrote value.messages.*item.*msgText in your dataweave. You just need to do the same thing for the "item" element (which you are calling products).
This is the dataweave you are looking for:
%dw 2.0
output application/json
var failedProducts = vars.response.materials.*item filter ((product) -> product.status == "1")
---
{
    batchId: vars.batchId,
    status: vars.overallStatus,
    products: failedProducts map (value) -> {
            materialNumber: value.materialNumber,
            errorMessages: value.messages.*item.*msgText
        }
 }

A: %dw 2.0
output application/json
var failedProducts = vars.response.materials filterObject ((value) -> value.status contains  "1")
---
{
    batchId: vars.batchId,
    status: vars.overallStatus,
    products: failedProducts.*item map (value) -> {
            materialNumber: value.materialNumber,
            errorMessages: value.messages.*item.msgText
        }
}


text:
Q: Determining correlation between discrete data I have two variables

*

*The number of likes that a comment has received.

*Total AFINN score calculated from a comment.

Now the AFINN algorithm assigns an integer based on the sentiment of each word (between -5 and 5+). The total AFINN score is the sum of all the AFINN scores in that comment.
I am trying to determine if these correlate. However, I have some issues.

*

*The comment length is variable, and so the AFINN score is between -12 and 44+. Is there a way to determine the correlation between these variables?

*If I split the AFINN scores into top and bottom, would this be a valid way to run statistical significance testing? If so, what would you run?

A: You can calculate correlations between these variables. The fact that one can be negative or positive is not a problem. The fact that number of likes is a count may be a limitation. Pearson correlation is checking how close the relationship is to linear. My wild guess is that a straight line relationship is unlikely here, but that doesn't make Pearson correlation totally useless. Spearman and Kendall correlations are checking how close the relationship is to monotonic.
The deeper question is why you are doing this any way. If it's an exploratory check on whether there is a relationship, then OK, but a graph might well be as or more helpful. At another wild guess, many comments attract none or a very few likes and a few comments might attract very many likes, and that's what it is, but it can be quite to hard to model such a situation with very simple tools.
As for splitting on AFINN scores, that sounds like a step backwards. I know nothing about AFINN scores, but they sound like an attempt to measure something systematically, and degrading measurements into arbitrary groups rarely helps in statistics, any more than splitting off tall and short people is any kind of advance on using people's heights as a predictor. What significance tests did you have in mind?


text:
Q: Oracle SQL - PLS-00049 - bad bind variable I have table defined like this:
create table "nakup"  (
   "cislo_n"            INTEGER                         not null,
   "id_zak"             INTEGER                         not null,
   "jm_pobocky"         CHAR(15)                        not null,
   "datum_cas"          DATE                            not null
      constraint CKC_DATUM_CAS_NAKUP check ("datum_cas" >= TO_DATE('1.01.1994 8:30:25', 'DD.MM.YYYY HH24:MI:SS')),
   constraint PK_NAKUP primary key ("cislo_n")

I want to create a trigger that would block inserting a date from the future, my code looks like this:
create or replace TRIGGER TRIGGER1
BEFORE INSERT OR UPDATE ON "nakup"
FOR EACH ROW
BEGIN
  if (:new.datum_cas > current_timestamp) then
  raise_application_error(-20000, 'Špatně zadané datum a čas.');
end if;
END;

I keep getting error Error(5,7): PLS-00049: chybná vázaná proměnná 'NEW.DATUM_CAS' (bad bind variable in english). What am I doing wrong?

A: As Gordon Linoff suggested, your trigger will compile if you enclose the column name in double quotes:
create or replace TRIGGER TRIGGER1
BEFORE INSERT OR UPDATE ON "nakup"
FOR EACH ROW
BEGIN
  if (:new."datum_cas" > current_timestamp) then
  raise_application_error(-20000, 'Špatně zadané datum a čas.');
end if;
END;
/

Trigger TRIGGER1 compiled

Quoted identifiers have to be quoted everywhere they are referenced. You seem to have realised that when you referred to the table name in the trigger definition, but it applies to the column names too.
Your life will be much simpler if you use unquoted identifiers (or quoted uppercase identifiers, which is the same thing as long as they don't contain any invalid characters). Oracle does not recommend using quoted identifiers for database object names. So this works with no double-quotes at all:
create table nakup  (
   cislo_n            INTEGER                         not null,
   id_zak             INTEGER                         not null,
   jm_pobocky         CHAR(15)                        not null,
   datum_cas          DATE                            not null,
   constraint CKC_DATUM_CAS_NAKUP
     check (datum_cas >= TO_DATE('1.01.1994 8:30:25', 'DD.MM.YYYY HH24:MI:SS')),
   constraint PK_NAKUP primary key (cislo_n)
);

Table NAKUP created.

create or replace TRIGGER TRIGGER1
BEFORE INSERT OR UPDATE ON nakup
FOR EACH ROW
BEGIN
  if (:new.datum_cas > current_timestamp) then
  raise_application_error(-20000, 'Špatně zadané datum a čas.');
end if;
END;
/

Trigger TRIGGER1 compiled

You can then refer to nakup.datum_cas etc. in your code, instead of having to use "nakup"."datum_cas".

A: yes...
datum_cas column name is different from datum_cas column name..
Oracle stores column names as uppercase by default,if we use double quotes ("") the column name is stored as-is (upper/lower)
example....
SQL> create table test5 (id number,"id1" number);
      table created.

SQL> insert into  test5 values(1,2);

 1 row created.

SQL> select * from  test5;

  ID        id1
----- ----------
    1          2

id is stored as ID and id1 is stored as id1.