text:
Q: Twilio Node JS - filter sms per phone number I would like to filter sms per phone number and date the SMS was sent using REST API, however the output of the following code is not available outside of client.messages.each() block.
Please advise how I can use the latest sms code sent to the filtered number:
const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
client.messages.each(filterOpts, (record) => {
  codeCollection.push(record.body.match(pattern)[0]);
  console.log(record.body.match(pattern)[0], record.dateSent);
 });
 console.log(codeCollection,'I get an empty array here');//how to get
 the latest sms and use it
 doSomethingWithSMS(codeCollection[0]);

A: Twilio developer evangelist here.
The each function doesn't actually return a Promise. You can run a callback function after each has completed streaming results by passing it into the options as done like this:
const codeCollection = [];
const pattern = /([0-9]{1,})$/;

const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD'),
  done: (err) => {
    if (err) { console.error(err); return; }
    console.log(codeCollection);
    doSomethingWithSMS(codeCollection[0]);
  }
};

client.messages.each(filterOpts, (record) => {
  codeCollection.push(record.body.match(pattern)[0]);
  console.log(record.body.match(pattern)[0], record.dateSent);
 });

Let me know if that helps at all.

A: Do you have access to the length of the array of messages? If so, you can do something like this
const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
var i = 0
client.messages.each(filterOpts, (record) => {
    if (i < messages.length){
        codeCollection.push(record.body.match(pattern)[0]);
        console.log(record.body.match(pattern)[0], record.dateSent);
        i++;
    else {
        nextFunction(codeCollection);
    }
 });

function nextFunction(codeCollection){
     console.log(codeCollection,'I get an empty array here');
     doSomethingWithSMS(codeCollection[0]);
}

A: messages.each() is running asynchronously, so your main thread moves on to the next call while the client.messages() stuff runs on a background thread.  So, nothing has been pushed to codeCollection by the time you've tried to access it. You need to somehow wait for the each() to finish before moving on. Twilio client uses backbone style promises, so you can just add another .then() link to the chain, like below. You could also use a library like async which lets you use await to write asynchronous code in a more linear looking fashion.
const filterOpts = {
  to: '+13075550185',
  dateSent: moment().utc().format('YYYY-MM-DD')
};
let pattern = /([0-9]{1,})$/;
let codeCollection = [];
client.messages.each(filterOpts, (record) => {
    codeCollection.push(record.body.match(pattern)[0]);
    console.log(record.body.match(pattern)[0], record.dateSent);
}).then(
    function() {
        console.log(codeCollection,'I get an empty array here');
        if( codeCollection.count > 0 ) doSomethingWithSMS(codeCollection[0]);
    }
);


text:
Q: how to execute bash script with crontab in centos? My bash file is not executed by cronjob created as root. The cronjob setup looks as it follows
0 0 * * * mysql_backup.sh

does need to be decalared with the bash command 0 0 * * * bash mysql_backup.sh ? if I execute manually my bash script manually sudo bash mysql_backup.sh than it's working.
I have been creating the cronjob using sudo crontab u root -e and the bash file is in the root of centos

A: First, you need to use full path like:
0 0 * * * /path/to/mysql_backup.sh

Second, you need to make sure your script has execute permission or you can invoke it using:
0 0 * * * /bin/bash /path/to/mysql_backup.sh

Third, you need to make sure you are executing your cron job with enough privilege.

A: also, you could add the following command in the first line of your script:
#!/bin/bash

(assuming bash is located in /bin/bash). This will make your script run by bash even when called directly, and not as a parameter of the bash.
You could add some logging and also check your crontab log, to see if there is any error that could lead you to the solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Javascript to send SSH commands in a browser My goal is to have a gateway that sends SSH commands to a remote server from a webpage. There are a few browser based extensions, but I wasn't able to find any that were exposed via Javascript. Is there a way to accomplish this client-side without a proxy server in between?
I really don't even need async communications, I really just need a "fire and forget" bucket for SSH calls triggered from a webpage, hopefully without introducing another service somewhere.

A: You can check out Ajaxterm which is a web based terminal.
also check Orbited which is provides a JavaScript TCP socket API for real-time browser applications.
I hope that help you.


text:
Q: How do I create a generic page for all my Spring controller exceptions? I'm using Spring 3.2.11.RELEASE.  I'm trying to set up a JSP as a catch-all page for any exceptions originating from my controllers.  However, the mechanism isn't kicking in.  I have added this to my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true">

    <display-name>subco Application</display-name>
    <session-config>
        <cookie-config>
            <path>/myproject</path>
        </cookie-config>
    </session-config>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/META-INF/spring/applicationContext-myproject.xml,
            classpath:/META-INF/spring/infrastructure.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>Owasp.CsrfGuard.Config</param-name>
        <param-value>csrfguard.properties</param-value>
    </context-param>

    <context-param>
        <param-name>Owasp.CsrfGuard.Config.Print</param-name>
        <param-value>true</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>CSRFGuard</filter-name>
        <filter-class>org.owasp.csrfguard.CsrfGuardFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CSRFGuard</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.owasp.csrfguard.CsrfGuardServletContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.owasp.csrfguard.CsrfGuardHttpSessionListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.mainco.subco.myproject.mvc.listener.SbSessionAttributeListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>JavaScriptServlet</servlet-name>
        <servlet-class>org.owasp.csrfguard.servlet.JavaScriptServlet</servlet-class>
        <init-param>
            <param-name>source-file</param-name>
            <param-value>WEB-INF/csrfguard.js</param-value>
        </init-param>
        <init-param>
            <param-name>inject-into-forms</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>inject-into-attributes</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>domain-strict</param-name>
            <param-value>false</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>JavaScriptServlet</servlet-name>
        <url-pattern>/csrfjs</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>MyprojectDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/jboss-as-spring-mvc-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyprojectDispatcher</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>MyprojectDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/WEB-INF/error.jsp</location>
    </error-page>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

and created the error.jsp in my WEB-INF directory.  However, when exceptions are generated from within my controllers, e.g. NullPointerExceptions, I do not see the error.jsp page, but rather a generic spring message that reads, '{"status":"failure","exception":"NullPointerException"}'.  What other configurations do I need to do to engage my generic error page?  I'm using JBoss 7.1.3.Final if that matters.
Edit:
Here is the application context file, referenced in the web.xml file from above:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="org.mainco.subco.assessment.mvc"/>
    <context:component-scan base-package="org.mainco.subco.myproject.mvc"/>
    <context:component-scan base-package="org.mainco.subco.myproject.validator"/>
    <context:component-scan base-package="org.mainco.subco.standards.mvc"/>
    <context:component-scan base-package="org.mainco.subco.resource.mvc"/>
    <context:component-scan base-package="org.mainco.subco.registration"/>

    <context:component-scan base-package="org.mainco.subco.section.mvc" />
    <context:component-scan base-package="org.mainco.subco.user.mvc" />
    <context:component-scan base-package="org.mainco.subco.util.mvc" />

    <context:component-scan base-package="org.mainco.subco.security" />
    <context:component-scan base-package="org.springframework.security.saml"/>
    <context:component-scan base-package="org.mainco.subco.myproject.lti" />

    <mvc:annotation-driven />

    <context:property-placeholder location="classpath:core.properties,classpath:application.properties"/>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:MyprojectUserMessages"/>
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10000000"/>
        <property name="maxInMemorySize" value="10000000" />
    </bean>

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="3" p:defaultErrorView="error" />

</beans>

A: Try use in your web.xml like this:
<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/WEB-INF/error.jsp</location>
</error-page>

Are you using Spring MVC? If so, try config an exception resolver in your mvc application context, something like this:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="3" p:defaultErrorView="error" />

Your error.jsp must be in the path of your viewResolver (e.g. "WEB-INF/pages", "WEB-INF/views", etc.).
PS.: to use p:* you have add xmlns:p="http://www.springframework.org/schema/p" in your beans, something like this:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- your configs go here -->

</beans>

You can also use @ExceptionHandler and/or a @ControllerAdvice with Spring MVC.


text:
Q: Distinct Sylow $p$-subgroups intersect only at the identity, which somehow follows from Lagrange's Theorem. Why? It seems that often in using counting arguments to show that a group of a given order cannot be simple, it is shown that the group must have at least $n_p(p^n-1)$ elements, where $n_p$ is the number of Sylow $p$-subgroups.

It is explained that the reason this is the case is because distinct Sylow $p$-subgroups intersect only at the identity, which somehow follows from Lagrange's Theorem.

I cannot see why this is true.
Can anyone quicker than I tell me why? I know it's probably very obvious.
Note: This isn't a homework question, so if the answer is obvious I'd really just appreciate knowing why.
Thanks!

A: In some situations, to prove that groups of order $n$ cannot be simple, you can use the counting argument if all Sylow subgroups have trivial intersection, and a different argument otherwise.
For example let $G$ be a simple group of order $n=144 = 16 \times 9$. The number $n_3$ of Sylow 3-subgroups is 1, 4 or 16. If $n_3 = 1$ then there is normal Sylow subgroup and if $n_3= 4$ then $G$ maps nontrivially to $S_4$, so we must have $n_3 = 16$.
If all pairs of Sylow 3-subgroups have trivial intersection, then they contain in total $16 \times 8$ non-identity elements, so the remaining 16 elements must form a unique and hence normal Sylow 2-subgroup of $G$.
Otherwise two Sylow 3-subgroups intersect in a subgroup $T$ of order 3. Then the normalizer $N_G(T)$ of $T$ in $G$ contains both of these Sylow 3-subgroups, so by Sylow's theorem it has at least 4 Sylow 3-subgroups, and hence has order at least 36, so $|G:N_G(T)| \le 4$ and $G$ cannot be simple.

A: It simply isn't true, Sylow p-subgroups can very well intersect non-trivially, Plop gave an example thereof.
Well, it seems like you actually cannot say the following, see comments. I'm just leaving it here as a mistake one shouldn't make, so I won't mind if a moderator deletes it since it's not an actual answer.
[wrong]You could say that the number of elements of order $p$ is at least $n_p(p^n-p^{n-1})+p^{n-1}$,  which is the case when all $p$-groups intersect maximally. [/wrong] Note that in this case however the intersection of all Sylow $p$-subgroups is a normal subgroup (even a  characteristic subgroup, it is called $\mathbf O_p(G)$), so this cannot occur in a simple group.

A: Suppose $P$ and $Q$ are Sylow p-subgroups of prime order p (so not just any power of p; as others remarked, then it is not true in general). Note that $P\cap Q$ is a subgroup of $P$ (and of $Q$). So by Lagrange, the order $|P\cap Q|$ divides p. As p is prime, it is 1 or p. But it cannot be p, as $P$ and $Q$ are distinct. So $|P\cap Q|=1$ and consequently the intersection is trivial.

A: That's because it is not true in general. Look at $2$-Sylows in $S_5$: they have nontrivial intersection.


text:
Q: Creating array2D doesn't work Using MSDN sample:
let my2DArray = array2D [ [ 1; 0]; [0; 1] ]

Trying to run it in F# Interactive, but get the following error:

error FS0003: This value is not a function and cannot be applied

I know I can use Array2D.init, but wondering why array2D doesn't work.

A: The single-line sample you posted in your question works fine for me, so the error is probably caused by some other code that is on the next line (or on the previous line).
For example, I get the error "This value is not a function and cannot be applied" when I write this:
let my2DArray =
  array2D [ [ 1; 0]; [0; 1] ]
    printfn "hi"

In this case, the error is caused by incorrect indentation. The compiler thinks that you're treating the code on the second line (array2D [ .. ]) as a function and using the code on the third line as an argument (because it is indented further). Fixing the indentation (remove spaces before printfn) solves the problem.
It is hard to say what is the problem in your case, but I suspect something very similar.


text:
Q: Can't resize vim splits inside tmux Everything is working fine outside of tmux. But in tmux I can't resize vim splits with the mouse.
I have set mouse=a in my .vimrc. Is there a solution for this?
.tmux.conf:
$ cat ~/.tmux.conf
set-option -g mode-mouse on
set-option -g mouse-resize-pane on
set-option -g mouse-select-pane on
set-option -g mouse-select-window on

A: It appears that dragging the status line to resize a split is not possible when the Vim option ttymouse is xterm; it does work when the value is xterm2 though. The latter value configures Vim to ask for an extended mouse reporting mode that (among other things) provides better dragging support. This extended mode only works with newer versions of xterm (and other compatible terminal emulators, including tmux), so it is not the default value.
You could use something like the following in your .vimrc to set the option:
set mouse+=a
if &term =~ '^screen'
    " tmux knows the extended mouse mode
    set ttymouse=xterm2
endif

(Though, I am not sure how this will affect actual screen instances, which also use a TERM that starts with screen.)
When you are outside of tmux, the TERM environment variable is probably an xterm-ish value, and Vim will probe for the xterm version by using the t_RV control sequence.

A: In my case it resolved both cases: mouse split resize and mouse position problem for wide screen.
The fix is:
if has("mouse_sgr")
    set ttymouse=sgr
else
    set ttymouse=xterm2
end


text:
Q: Stack in android it's first time for me I use java
I need to use a stack in android funcions
but if I define the stack out of the function
give me the error (should be parametrized) and the application crashes
public class Televideo extends Activity{
    Stack pila = new Stack();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        pila.push(mystring);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        mystring = pila.peek();
    }
}

how can I use the stack through class functions in java? thanks

A: parametrising means that you tell the Class (in this case your Stack) what type of objects its instance (in this case pila) will contain. Try this code instead of yours:
Stack<String> pila = new Stack<String>()

However, this should not be an error but only a warning as far as I know.


text:
Q: Get compile errors for dependent TypeScript files in WebStorm I'm wondering if there is a way to make WebStorm show me compilation errors in dependent TypeScript files after an edit.  As an example, say I have Class1.ts as follows:
class Class1 {
    foo(n: number): number { return 3; }
}

export = Class1;

And also Class2.ts:
import Class1 = require('./Class1');

class Class2 extends Class1 {

    foo(n: number): number { return 4; }
}

Now, say I edit Class1.ts and change the parameter type of foo:
class Class1 {
    foo(n: string): number { return 3; }
}

export = Class1;

When I perform the edit and save, I don't see any new errors appear.  If I switch focus to the Class2.ts tab, at that point an "Incompatible override" message appears.  But ideally, I'd like some way to see all the errors I introduced in the whole project after making an edit.  Is there some view I can enable to accomplish this?

A: Is using an external filewatcher an option for you?
I found the webstorm filewatcher for typescript to be a little buggy. As a result, I disabled the filewatcher and simpyly use grunt-contrib-watch in it's place. It works great, and provides a little more flexibility if you need it.
You could do something like this in your gruntfile.js:
module.exports = function (grunt) {
    var files = [
            'app/**/*.ts'
        ];

    grunt.initConfig({
        tslint: {
            options: {
                configuration: grunt.file.readJSON("tslint.json")
            },
            files: {
                src: files
            }
        },
        typescript: {
            base: {
                src: files,
                options: {
                    module: 'commonjs',
                    target: 'es5'
                }
            },
            build: {
                src: ['./app.ts'],
                options: {
                    module: 'commonjs',
                    target: 'es5'
                }
            }
        },
        watch: {
            ts: {
                files: ['app/**/*.ts', 'shared/**/*.ts'],
                tasks: ['typescript']
            }
        }
    });

    // Load Tasks
    grunt.loadNpmTasks('grunt-tslint');
    grunt.loadNpmTasks('grunt-typescript');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // Register Tasks
    grunt.registerTask('default', ['watch']);
};

Then simply running grunt will perform the watch command, and you can eliminate the webstorm typescript filewatcher. This will give you build errors you are looking for on save.
*Note: I left tslint in the gruntfile as it's a good idea to run tslint on your files regularly, but it's certainly not necessary. Let me know if you have any questions about it.

A: Still a manual process but better then guessing which files you need to open.
Select a project root folder, hit Ctrl+Shift+A -> Ctrl+Shift+A to enable non-menu actions -> type "run file " -> choose Run File Watchers....
This was part of an answer to another question.(https://stackoverflow.com/a/26779818/1757491)

A: WebStorm now supports tsconfig. You'll need to setup the tsconfig.json file and then go to File/Settings/Languages & Frameworks/TypeScript and check the 'Use tsconfig.json'. Once I did this I was able to (eventually) see type errors in the TypeScript Compiler window. The errors do not appear immediately like in Visual Studio. But for me they appear within 15 to 30 seconds. Also, another quick 'n dirty approach is to open a terminal window in the os or in WebStorm and type 'tsc --watch'. This tells the TypeScript compiler to compile everything immediately and shows you any errors. The '--watch' means that tsc (TypeScript compiler) will continue to monitor all .ts files and show any errors in the terminal window.


text:
Q: When does Node Readable Stream of _read() called I create my own readstream. But I want to know when the _read() be called? If I don't  add on('data') listerner, the _read() will not be called. Why?
var data = [{"id":0,"name":"object 0","value":3}],
    Readable = require('stream').Readable,
    util = require('util');

var ReadStream = function() {
    Readable.call(this, {objectMode: true});
    this.data = data;
    this.curIndex = 0;
};
util.inherits(ReadStream, Readable);

ReadStream.prototype._read = function() {
    if (this.curIndex === this.data.length)
        return this.push(null);

    var data = this.data[this.curIndex++];
    //console.log('read: ' + JSON.stringify(data));
    this.push(data);
};

var stream = new ReadStream();
stream.on('data', function(record) {
    console.log('received: ' + JSON.stringify(record));
});

stream.on('end', function() {
    console.log('done111');
});

A:
If I don't add on('data') listerner, the _read() will not be called. Why?

The stream is paused. Assuming you are using a recent version of node.
https://nodejs.org/api/stream.html#stream_two_modes

All Readable streams begin in paused mode but can be switched to flowing mode in one of the following ways:
Adding a 'data' event handler.
Calling the stream.resume() method.
Calling the stream.pipe() method to send the data to a Writable.

BTW, to create a readable, check noms or mississippi.from


text:
Q: Pinescript tradingview indicator on previous candle value I am writing a code that is triggered on the current candle value, but uses the previous candle's as well. I was successful however this code looks probably kind of funny :)
Is there an easier way of using the previous  candle value, i.o. repeating [..]?
Thanks a lot.
signal6a =( signal6[12] or signal6[11] or signal6[10] or signal6[9] or signal6[8] or signal6[7] or signal6[6] or signal6[5] or signal6[4] or signal6[3] or signal6[2] or signal6[1] or signal6 or signal6[13] or signal6[14] or signal6[15] or signal6[16] or signal6[17] or signal6[18] or signal6[19] or signal6[20] or signal6[21] or signal6[22] or signal6[23] or signal6[24] or signal6[25] or signal6[26] or signal6[27] or signal6[28] or signal6[29] or signal6[30] or signal6[31] or signal6[32] or signal6[33] or signal6[34] or signal6[35] or signal6[36] or signal6[37] or signal6[38] or signal6[39] or signal6[40]) and high >ta.ema(high, 8)

A: You can use the math.sum() function for this purpose.
If you want to check if signal6 was true for 40 bars consecutievly, you would do it like below:
is_signal6a = math.sum(signal6 ? 1 : 0, 40) == 40

It will lookback the last 40 candles and return the number of times signal6 is true. If that rolling sum is equal to 40, you know that signal6 was true for the last 40 candles.
If you want to check if signal6 was true for at least one bar (this is your case), you would do it like below:
is_signal6a = math.sum(signal6 ? 1 : 0, 40) > 0

A: I would personally would use a custom function to check if signal6 is true:
checkForTrue(source, len) =>
    p = false
    for i=0 to len
        p := source[i]
        if p
            break
    p

Once you have this function, your code can be written as:
signal6a = checkForTrue(signal6, 40) and high > ta.ema(high, 8)


text:
Q: Displaying data from a database table based on id of user logged in I'm trying to get certain information from a database according to the user that's logged in. Right now I can get information from the columns and rows but its not user specific. Can I use a $_SESSION? Would that work in the $query?
PHP:
$query = "SELECT * ".
"FROM leavetable, users ".
"WHERE leavetable.users_id = users.id ";

$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
    echo ' <tr> ';
    echo ' <td> ';
    echo $row['id'];
    echo ' <td> ';
    echo $row['hours'];
    echo ' <td> ';
    echo $row['email'];
    echo ' <td> ';
    echo $row['username'];
    echo ' <td> ';
}

A: Yes, but never build your SQL queries like suggested by Mr Shahnewaz's answer. This kind of approach is vulnerable to SQL injection attacks, I'd suggest you to take some time to read about them and experiment.
The proper way to perform a parameterized query is by using a prepared statement:
$stmt = $dbh->prepare('SELECT * FROM leavetable WHERE leavetable.users_id = :id');
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->fetch();

The key point to keep in mind is that the query string passed to the prepare method must be a plain hardcoded string. You can use named placeholers (:whatever) where needed, as shown in the example.
By the way, in this example $dbh would be an instance of the PDO class, which you might consider using instead of the old mysql_* functions.


text:
Q: View wont update using ScheduledExecutorService I'm having some trouble with getting ScheduledExecutorService to work.
This is the method that i'm calling which works if I call it without scheduling it.
However, if I call it through an ScheduledExecutorService my screen wont update, it also only runs one time, so I guess there's an exception being thrown, but I dont see an exception on either the server or client.
private void getNextRoundFromServer() throws IOException{
    try{
        if(!this.connected) return;
        this.dos.writeByte(2);
        this.dos.flush(); // Send data
        this.grid = (Grid) this.ois.readObject(); //i have checked, i do recieve this object
        setMainPane(render.render(this.grid)); //this renders the view
    } catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }
}

This is how I do my implementation.
continuousPlayButton.setOnMouseClicked(e -> {
    try{
        Runnable scheduledRound = () -> {
            try {
                getNextRoundFromServer();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        };
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(scheduledRound, 1, 5, TimeUnit.SECONDS);
    }catch(Exception ex){
        ex.printStackTrace();
    }
});

Why isn't my view updating?
Update
Solution:
As mention by user tjanu: I forgot to call Platform.runLater on the scheduled task. Which I already did when I called it without scheduling...

A: You need to do UI updates on the JavaFX application thread.
This is what Platform::runLater is for.
-- edit
As requested, the change needed for this code:
private void getNextRoundFromServer() throws IOException{
    try{
        if(!this.connected) return;
        this.dos.writeByte(2);
        this.dos.flush(); // Send data
        this.grid = (Grid) this.ois.readObject(); //i have checked, i do recieve this object
        // This is the needed change
        Platform.runLater(() -> setMainPane(render.render(this.grid))); //this renders the view
    } catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }
}

A: Not an full answer to your question, but a suggestion.Maybe you could try to override the run() method.
Runnable scheduledRound = new Runnable() {
    @Override
    public void run() {
        try {
            getNextRoundFromServer();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
};

A: You're referencing instance variables in your getNextRoundFromServer() method and you're now calling the method from within a new (anonymous) Runnable instance, So your references to "this" may not resolve to where you think they're resolving.
Perhaps pass in a reference to the original instance?
private void getNextRoundFromServer(YourObjectClass instance) throws IOException{
    try{
        if(!instance.connected) return;
        instance.dos.writeByte(2);
        instance.dos.flush(); // Send data
        instance.grid = (Grid) instance.ois.readObject(); //i have checked, i do recieve this object
        setMainPane(render.render(instance.grid)); //this renders the view
    } catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }
}

continuousPlayButton.setOnMouseClicked(e -> {
    try {
        final instanceRef = getReferenceToYourOriginalInstance();
        Runnable scheduledRound = () -> {
            try {
                getNextRoundFromServer( instanceRef );
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        };
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(scheduledRound, 1, 5, TimeUnit.SECONDS);
    }catch(Exception ex){
        ex.printStackTrace();
    }
});


text:
Q: How redirect to alogin page in html Django if user is not authinticated How to in HtMl to redirect user if it is noit registered using this template. I want to redirect if not registered to Login page
{% if user.is_authenticated %}

Authenticated user

{% else %}
    redirect to 'login' page
{% endif %}

I have in settings.py
LOGOUT_REDIRECT_URL = 'login'

A: Template is not place to do redirects on
Use login_required decorator on view instead

A: redirect doesn't work within the Django template.  To redirect you can try some of the decorators that Django has provided us.
Just in your view.py do as I did.
from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

In this example, the @login_required decorator checks if the user has logged in.  If not, it will redirect the user to the route specified in the LOGOUT_REDIRECT_URL.
Otherwise, if you wish to do this check in the template, you can try some thing like this.
{% if user.is_authenticated %}

Authenticated user

{% else %}

Create a view here which tells the user to login.

{% endif %}

A: user = authenticate(username='john', password='secret')

if user is not None:
# A backend authenticated the credentials
else:
# No backend authenticated the credentials


text:
Q: Rails Model - Update Nested Key/Value in JSON I have a model with the following table format:
string  "name"
integer "line_id"
json    "filters"

Where the filters field contains a json object with nested keys. I want to modify a specific key without overwriting the rest of the json.
Currently, the json object stored in filters looks like
{
  "ext": {"name": "filter", "id": 3},
  "int": {"name": "numb", "id": 1}
}

I'm trying to update int.name's value to "remove" without modifying the rest of the json object.
If I do the following, it'll simply overwrite the entire json object instead of modifying that specific key:
Model.where("filters->>'int'->>'name' IS NOT NULL").update(
  filters: {
    int: {
      name: "remove"
    }
  }
)

How can I simply update that one key with the path int.name while keeping the rest of the attributes the same?

A: which version of rails are you using?   if you are using rails 5, you should be able to
m = Model.where("filters->>'int'->>'name' IS NOT NULL").first
m.filters['name'] = 'remove'
m.save

this will leave the existing hash keys in place.
I think with rails 4, you need a json serializer on the field, but should work the same way once you have the serializer, i believe.

A: How about something like this
models = Model.where("filters->>'int'->>'name' IS NOT NULL")
  .each_with_object({}) do |m,obj|
    # credit to mudasobwa for the tap usage
    obj[m.id] = {filters: m.filters.tap { |h| h['int']['name'] = 'remove' } }
  end
Model.update(models.keys,models.values)

I have never used a json column so I am unsure if the anticipated value is meant to be JSON or a Hash that will be converted to JSON before insertion but the update statement will be akin to
Model.update([1],[{
         "ext"=> {"name"=> "filter", "id"=> 3},
         "int"=> {"name"=> "remove", "id"=> 1}
       }])

This uses ActiveRecord::Relation#update where the first Array is the ids to update and the second Array is the new values to associate with those ids.


text:
Q: Multiple sites: what am I missing? I should have 3 web sites on one apache2 (up-to-date Ubuntu).
Each site has its own file in "sites-enabled". Each has its own IP.
Apache2 seems to be running fine: /var/log/apache2/error.log only says:
[Fri Nov 08 12:30:12 2013] [notice] Apache/2.2.22 (Ubuntu) PHP/5.4.6-1ubuntu1.4 configured -- resuming normal operations
The DNS files seem OK. But when I point a browser to the second and third site (to their domain names or to their IP adresses), it just hangs until timeout.
What should I check next, please?
----------------------- ANSWER 1:
ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:16:3e:93:68:c0 brd ff:ff:ff:ff:ff:ff
    inet 92.243.20.169/22 brd 92.243.23.255 scope global eth0
    inet6 2001:4b98:dc0:45:216:3eff:fe93:68c0/64 scope global dynamic
       valid_lft 2591871sec preferred_lft 604671sec
    inet6 fe80::216:3eff:fe93:68c0/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:16:3e:84:91:0a brd ff:ff:ff:ff:ff:ff
    inet 92.243.21.141/22 brd 92.243.23.255 scope global eth1
    inet6 2001:4b98:dc0:45:216:3eff:fe84:910a/64 scope global dynamic
       valid_lft 2591871sec preferred_lft 604671sec
    inet6 fe80::216:3eff:fe84:910a/64 scope link
       valid_lft forever preferred_lft forever
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:16:3e:1f:2d:85 brd ff:ff:ff:ff:ff:ff
    inet 92.243.4.114/21 brd 92.243.7.255 scope global eth2
    inet6 2001:4b98:dc0:41:216:3eff:fe1f:2d85/64 scope global dynamic
       valid_lft 2591952sec preferred_lft 604752sec
    inet6 fe80::216:3eff:fe1f:2d85/64 scope link
       valid_lft forever preferred_lft forever

ifconfig
eth0      Link encap:Ethernet  HWaddr 00:16:3e:93:68:c0
          inet addr:92.243.20.169  Bcast:92.243.23.255  Mask:255.255.252.0
          inet6 addr: 2001:4b98:dc0:45:216:3eff:fe93:68c0/64 Scope:Global
          inet6 addr: fe80::216:3eff:fe93:68c0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9550641 errors:0 dropped:3 overruns:0 frame:0
          TX packets:3749560 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:953636357 (953.6 MB)  TX bytes:6983319124 (6.9 GB)
          Interrupt:27

eth1      Link encap:Ethernet  HWaddr 00:16:3e:84:91:0a
          inet addr:92.243.21.141  Bcast:92.243.23.255  Mask:255.255.252.0
          inet6 addr: 2001:4b98:dc0:45:216:3eff:fe84:910a/64 Scope:Global
          inet6 addr: fe80::216:3eff:fe84:910a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5797827 errors:0 dropped:3 overruns:0 frame:0
          TX packets:34854 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:607191525 (607.1 MB)  TX bytes:1464788 (1.4 MB)
          Interrupt:28

eth2      Link encap:Ethernet  HWaddr 00:16:3e:1f:2d:85
          inet addr:92.243.4.114  Bcast:92.243.7.255  Mask:255.255.248.0
          inet6 addr: 2001:4b98:dc0:41:216:3eff:fe1f:2d85/64 Scope:Global
          inet6 addr: fe80::216:3eff:fe1f:2d85/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9231950 errors:0 dropped:2 overruns:0 frame:0
          TX packets:29473 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:914989353 (914.9 MB)  TX bytes:1349244 (1.3 MB)
          Interrupt:29

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:11570 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11570 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1135320 (1.1 MB)  TX bytes:1135320 (1.1 MB)

I don't understand most of that, but I can see the IPs: 92.243.20.169, 92.243.21.141 and 92.243.4.114, which are as they should be. I don't know if it is normal that the Bcast and Mask are different. The reports about the packets also look OK to me.
-------------------------- ANSWER 2
netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:mysql                 *:*                     LISTEN
tcp        0      0 *:gandi-agent           *:*                     LISTEN
tcp        0      0 *:ftp                   *:*                     LISTEN
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp        0    368 Charlotte:ssh           reverse-27.fdn.fr:37999 ESTABLISHED
tcp6       0      0 [::]:http               [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61519 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61352 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61442 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61209 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61550 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61421 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61579 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61606 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61386 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61469 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61275 TIME_WAIT
tcp6       0      0 Charlotte:http          ks4000493.ip-198-:61247 TIME_WAIT
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  3      [ ]         DGRAM                    2346     /dev/log
unix  2      [ ACC ]     STREAM     LISTENING     229      @/com/ubuntu/upstart
unix  2      [ ACC ]     STREAM     LISTENING     3598978  /var/run/mysqld/mysqld.sock
unix  2      [ ACC ]     SEQPACKET  LISTENING     430      /run/udev/control
unix  3      [ ]         STREAM     CONNECTED     3597550
unix  3      [ ]         STREAM     CONNECTED     3597549
unix  2      [ ]         DGRAM                    3597541
unix  3      [ ]         STREAM     CONNECTED     709      @/com/ubuntu/upstart
unix  3      [ ]         STREAM     CONNECTED     706
unix  3      [ ]         DGRAM                    438
unix  3      [ ]         DGRAM                    437
unix  3      [ ]         STREAM     CONNECTED     393      @/com/ubuntu/upstart
unix  3      [ ]         STREAM     CONNECTED     390

This I have no idea what it all means.
---------------------- ANSWER 3
ping 92.243.20.169
PING 92.243.20.169 (92.243.20.169) 56(84) bytes of data.
64 bytes from 92.243.20.169: icmp_req=1 ttl=59 time=57.3 ms
64 bytes from 92.243.20.169: icmp_req=2 ttl=59 time=45.7 ms
64 bytes from 92.243.20.169: icmp_req=3 ttl=59 time=43.9 ms
64 bytes from 92.243.20.169: icmp_req=4 ttl=59 time=44.9 ms
^C
--- 92.243.20.169 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 43.968/48.000/57.368/5.449 ms

ping 92.243.21.141
PING 92.243.21.141 (92.243.21.141) 56(84) bytes of data.

--- 92.243.21.141 ping statistics ---
7 packets transmitted, 0 received, 100% packet loss, time 6047ms

ping 92.243.21.141
PING 92.243.21.141 (92.243.21.141) 56(84) bytes of data.
--- 92.243.21.141 ping statistics ---
13 packets transmitted, 0 received, 100% packet loss, time 12000ms

-------------------@MadHatter
By "the DNS files seem OK", I mean I did not modify them and no program modified them either. They used to function before, so I guess they are OK. Would you like me to post a copy of them?

A: If you've got multiple IPs, you'll need multiple interfaces brought up. Can you ping the IPs? it may not even be an Apache problem. Type "ip addr" or "ifconfig" and see if you see them listed.
If that's all fine, make sure your virtual hosts are set up to listen on each IP respectively.


text:
Q: How to enable https protocol in a normal website? Kindly let me know the number of methods to proceed with this query. It will be really so nice of you for answering my question.

A: If you want https you need to buy a certifiate.
Here's a useful link: https://support.google.com/webmasters/answer/6073543?hl=en

A: *

*Host the website with a dedicated IP address

*Buy a SSL certificate from "Certificate Authorities" (CA's)

*Activate the certificate

*Install the certificate

*Update your site to use HTTPS

Source http://www.howto-expert.com/how-to-get-https-setting-up-ssl-on-your-website/

A: I am not sure what your question is, but from what I understand here is my input. Please explain your question a little more.
You can try web.config -- it will force HTTPS for ALL resources like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

A: <IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>


text:
Q: Need to understand ConcurrentUpdateException after sorting? I wrote a program which is throwing ConcurrentUpdateException , I am unable to understand this behavior, It should not through any exception as i have only single thread to work with and i have not taken any iterator.
What happens in, sorting ? Why it is throwing this exception ? Please explain.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
        public static void main(String[] args) {
        List<Double> list1 = new ArrayList<Double>(Arrays.asList(3., 2., 0., 1., 2.));
        List<Double> subList = list1.subList(0, 3);
        Collections.sort(list1);
        System.out.println(subList.get(0));

    }
}

A: Function subList returns a view of the specified range within this list. So when you sort collection, subList will also change. That's why you get 0.0, and not 3.0.


text:
Q: Subversion does not show .php files in web-frontend Subversion 1.7 doesn´t show php files in the web frontend (file not found). Every other extension (ini, bmp, txt, ...) works. There are no issues with subversion clients (Netbeans etc.) Commit and Checkout works.
Any Ideas?
kind regards


text:
Q: variable incremented inside function has value 1 EDIT: so sorry, the original code was an iteration while i was trying to figure the problem out, I've edited the code
This question started similar, but here's the real problem I'm having:
In this code:
<?php
    $a = 2:

    function incr(){
        $a++;
    echo $a;
    }

    echo $a;
    incr();
?>

the output is 2  and  then 1, and  that signals to me that the variable $a gets initialized to 0 inside the function. Does the server know just by the virtue that i used the increment syntax to initialize the variable to 0?

A: $a is undefined, then when you increment it, it goes to 1.
function incr(){
    $a++; // $a is undefined
    return $a;
}

As pointed out in the manual:

Note:
The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

You could use global, and it will return as expected.
function incr(){
    global $a;
    $a++;
    return $a;
}

A: If you want it to be properly incremented within the function, you need to change your code to this:
<?php
    $a = 2:

    function incr($a){
        return $a++;
    }

    echo $a;
    echo incr($a);
?>

The $a inside and the $a outside the function are two entirely different variables in your code snippet, they are not in the same scope.
You can read about variable scope here : http://www.php.net//manual/en/language.variables.scope.php
You can also use global variables, also mentioned in the previous link, however their use is usually not recommended.

A: use this:
<?php
    $a = 2:

    function incr($a){
        return $a++;
    }

    echo $a;
    echo incr($a);
?>

A: In php global variables have to be declared global inside the function it is using them:
<?php
    $a = 2:

    function incr(){
        global $a;
        $a++;
    }

    echo $a;
    incr();
    echo $a;
?>

Don't mean to be rude, but this is explained in the manual:
http://www.php.net/manual/en/language.variables.scope.php
Or pass them as variables as the other answers by suggest. Note that PHP also allows to pass variables by reference (at least in PHP 5).


text:
Q: Recursive Stock Maximization The problem is to maximize the profit of a stock given the prices of stock on a given day.
I can buy only 1 stock, sell any number or do nothing.
Test cases:
Input: 1 2 100
Output: 197
Explanation: Bought on day 1 and day 2 sold on day 3 total profit = (100 - 1) + (100 - 2) = 197

Input: 1 3 1 2
Output: 3
Explanation: buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.

I have a recursive solution below and I know there are other solutions but I am trying to build on from a recursive one:
int maxProfit(vector<int> stock)
{
    int profit = helper(stock, stock[0], 1, 1);
    return profit < 0 ? 0 : profit;
}

int helper(vector<int>& stock, int cost, int index, int stockcount)
{
    if (index == stock.size() - 1)
    {
        return (stock[index] * stockcount) - cost;
    }
    int buy = helper(stock, cost + stock[index], index + 1, stockcount + 1);
    int sell = helper(stock, cost - stock[index], index + 1, stockcount - 1);
    return max(buy, sell);
}

Is the algorithm a correct recurisve approach and is there a way I can memoize the above? possibly removing the accumulator cost?

A: The recursive solution you offer seems to account for the choice to buy one stock but ignore the choice to do nothing and the varied choice of selling any number of owned stock.
But most importantly, it ignores what in real life would be the most important advantage: knowing the future :)
If you were to traverse the array from the end to the beginning, keeping track of the highest price so far, think about what you would do if:
(1) the price you encounter is lower than the one in your record? (remember that your record is of a future price)
and (2) the price you encounter is the same or higher than the price in your record? (again, remember that the price in your record is the highest future price coming after the current viewed price)
(Regarding memoization - in general, one can memoize the return value of a function by hashing or creating a lookup table for its set of parameters, optimising by considering which of the parameters may be constant or could be made constant and therefore ignored. Memoization is useful if you expect the same set of parameters to be called many times repeatedly during the calculation.)
Below are a JavaScript version with memoization of the rules you described, followed by the O(n) reverse traversal I hinted at above.
Memoized recursion:

function maxProfit(stock){
  return helper(stock, 0, 0, 0);
}

var hash = {};

function helper(stock, cost, index, stockcount){
  let key = [cost, index, stockcount].join('-');

  if (hash[key] !== undefined)
    return hash[key];

  if (index == stock.length)
    return -cost;

  var buy_or_not = helper(stock, cost + stock[index], index + 1, stockcount + 1);

  for (let i=0; i<=stockcount; i++)
    buy_or_not = Math.max(
      buy_or_not,
      helper(stock, cost - i*stock[index], index + 1, stockcount - i)
    );

  return hash[key] = buy_or_not;
}

console.log(maxProfit([1,1,50,1,1,50,1,1,40]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

O(n) reverse traversal:

function f(arr){
  if (!arr.length)
    return 0;

  var i = arr.length - 1,
      highest_sale_price = arr[i],
      stock_count = 0,
      current_cost = 0,
      total_profit = 0;

  for (i--; i>=0; i--){
    // Wouldn't want to buy this
    if (arr[i] >= highest_sale_price){

    // Go back to the future and
    // sell anything bought after
    // this day at the next highest
    // price
    total_profit += stock_count * highest_sale_price - current_cost;

    highest_sale_price = arr[i];
    current_cost = 0;
    stock_count = 0;

    // Otherwise, we know a
    // higher future price
    // so buy this stock!
    } else {
      stock_count++;
      current_cost += arr[i];
    }
  }

  // Day 0, go back to the future and sell
  // anything we have left at a higher price
  if (highest_sale_price)
    total_profit += stock_count * highest_sale_price - current_cost;

  return total_profit;
}

console.log(f([1,1,50,1,1,50,1,1,40]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Terminology: a stock is a particular ownership class of a company, such as INTC for Intel or MSFT for Microsoft common stock.  The individual partitions you buy and sell are called shares.
As גלעד ברקן already pointed out, you know the future.  There is no guessing, no dollar-averaging, no partial solutions.  You have total information.
Lemma: If it makes sense to sell 1 share of stock it makes sense to sell all you have.  This will greatly simplify your algorithm: you don't have to explore the alternative from 1-N.
Lemma: If today's price is lower than the future max price, the best strategy is to buy the maximum allowed.
Algorithm
// Base case:
If the array is empty, return

// Process
Find the maximum price in the array (call that day_s)
Buy max shares (one) on each day 1 : day_s
Sell all shares on day_s
(balance accounting is left as an exercise for the student)

// Recur
helper(stock[day_s: ], balance, 0)

A: Here is the recursive solution. In this solution, I am checking for every value i, to see if I find a value of j such that a[j] > a[i]. Then I calculate the profit as a[j] - a[i] and then add the profit to the recurrence from index j + 1 to e.
 int solve(int *a, int s, int e, int k){
    // passing array a, starting index s, ending index e, max stocks one
    // can sell k

    // base case
    if(s>=e)return 0;
    if(k == 0)return 0;

    int ans = 0;

    for(int i = s; i<e; i++){
      for(int j = i+1; j<=e; j++){
        int temp =0;
        if(a[j]>a[i]){
          temp += a[j] - a[i] + solve(a,j+1,e,k-1);
        }
        ans = max(ans,temp);
      }
    }
    return ans;
  }


text:
Q: SQL select, pad with chronological missing months Notice the 2015-02 and 2015-03 months are missing in the output from the following group by SQL. If there is no data for a month I want to show the month and 0. Anyone know how to go about this?
SELECT convert(char(7), MeterReadDate, 121),count(*)
FROM [myTable]
where (MeterReadDate > dateadd(d,-356,getdate()))
group by  convert(char(7), MeterReadDate, 121)
order by  convert(char(7), MeterReadDate, 121)

Sample data:
YYYY-MM COUNT
2014-06 23
2014-07 42
2014-08 80
2014-09 92
2014-10 232
2014-11 88
2014-12 8
2015-01 5
2015-04 2
2015-05 1

Still cannot clear the missing rows, here is where I am with it..
DECLARE @StartDate DATETIME = dateadd(m,-12,getdate()), @EndDate DATETIME = getdate(), @DATE DATETIME

DECLARE @TEMP AS TABLE (MeterReadDate datetime)

SET @DATE = @StartDate

WHILE @DATE <= @EndDate
BEGIN
     INSERT INTO @TEMP VALUES ( @DATE)
    SET @DATE = DATEADD(MONTH,1,@DATE)
END

SELECT convert(char(7), t.MeterReadDate, 121),count(*)

  FROM @TEMP m left join
     [myTable] t
     on convert(char(7), t.MeterReadDate, 121) = convert(char(7), m.MeterReadDate, 121)

  where (t.MeterReadDate > dateadd(m,-12,getdate()))
  group by  convert(char(7), t.MeterReadDate, 121)
  order by  convert(char(7), t.MeterReadDate, 121)

A: You need a list of dates/months that covers the entire period.  Here is one method using a recursive CTE:
with months as (
      select cast(getdate() - 365) as thedate
      union all
      select date_add(1, month, thedate)
      from months
      where thedate <= getdate()
     )
select convert(char(7), m.thedate, 121) as yyyy-mm, count(t.MeterReadDate)
from months m left join
     [myTable] t
     on convert(char(7), MeterReadDate, 121) = convert(char(7), m.thedate, 121)
group by convert(char(7), m.thedate, 121)
order by convert(char(7), m.thedate, 121);

A: If you don't want to go beyond your min and max dates of your results then you can do the following:
WITH    cte
          AS ( SELECT convert(char(7), MeterReadDate, 121) AS [Date], COUNT(*) AS [Count]
               FROM [myTable]
               WHERE (MeterReadDate > dateadd(d,-356,getdate()))
               GROUP by  convert(char(7), MeterReadDate, 121)
             ),
        minmax
          AS ( SELECT   CAST(MIN([Date] + '-01') AS DATE) AS mind ,
                        CAST(MAX([Date] + '-01') AS DATE) maxd
               FROM     cte
             ),
        calendar
          AS ( SELECT   mind ,
                        CONVERT(CHAR(7), mind, 121) AS cmind
               FROM     minmax
               UNION ALL
               SELECT   DATEADD(mm, 1, calendar.mind) ,
                        CONVERT(CHAR(7), DATEADD(mm, 1, calendar.mind), 121)
               FROM     calendar
                        CROSS JOIN minmax
               WHERE    calendar.mind < minmax.maxd
             )
    SELECT  c.cmind AS [Date],
            ISNULL(cte.[Count], 0) AS [Count]
    FROM    calendar c
            LEFT JOIN cte ON c.cmind = cte.[Date]
    OPTION  ( MAXRECURSION 0 )

A: The best way to do this would be to join onto a table containing calendar information, one way to do this without actually altering the database schema (and is more dynamic in my opinion) would be to use a table variable and the DATEADD() function.
DECLARE @StartDate DATETIME = '2015-01-01', @EndDate DATETIME = '2015-12-01', @DATE DATETIME

DECLARE @TEMP AS TABLE ([DATE] DATETIME)

SET @DATE = @StartDate

WHILE @DATE <= @EndDate
BEGIN
     INSERT INTO @TEMP VALUES (@DATE)
    SET @DATE = DATEADD(MONTH,1,@DATE)
END

SELECT * FROM @TEMP

Set @Start and @End to your required dates, then just join onto your results set!
UPDATE:
To extract the date in the format you gave above under "sample data", meaning you would be able to join onto the table, use:
SELECT
CONCAT(YEAR([DATE]),'-',right('0' + cast(month([DATE]) as varchar),2))
FROM @TEMP
LEFT JOIN MyTable ON...


text:
Q: How to differential spline graph in the matlab I'm the begginer of the matlab. So i can't find how to differential the spline graph. So could you explain me how to differential spline graph?
I wanna differential the graph below
x = -4:4;
y = [0 .15 1.12 2.36 2.36 1.46 .49 .06 0];
cs = spline(x,[0 y 0]);
xx = linspace(-4,4,101);
plot(ppval(cs,xx));


text:
Q: Connecting to a Remote Server on a different domain -- how do I enter the username and password? I have a vbscript where I am parsing information on a remote machine.
I have this line of code for the connection
strComputer is defined to be the name of the server we are connecting to.
Set objWmiService = GetObject("winmgmts:{impersonationLevel=impersonate!\\" & strComputer & "\root\cimv2")

As long as I am executing the script on the SAME domain as the remote server, the script will run just fine. My requirement is to be able to run the script from one domain to access a remote computer on a different domain.
To do this, I need to provide a username and password. I think the username must have the domain as part of it?
Anyways,
Is this possible? If so, how and where do I enter the username and password for this? I can simply add it as an argument.

A: According to Microsoft it should be possible. You need to authenticate against the remote domain, though, e.g. like this:
computer = "..."
username = "OTHERDOMAIN\user"
password = "..."

Set locator = CreateObject("WbemScripting.SWbemLocator")
Set wmi = locator.ConnectServer(computer, "root\cimv2", username, password)
wmi.Security_.ImpersonationLevel = 3


text:
Q: why convert the SKSpriteNode when detect a collision in SpriteKit sometimes not working and throw an error I've build an game using swift. First I create a class named alienNode which inherited from SKSpriteNode
var hP = 0

init() {
    let alienTexture = SKTexture(imageNamed: "Alien_Normal.png")
    self.hP = 5
    super.init(texture: alienTexture, color: UIColor.white, size: alienTexture.size())
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

then I create 3 aliens in GameScene
func buildAlien() {
    for i in 0...2 {
        let alienNode = AlienNode()
        addChild(alienNode)
        alienNode.name = kAlienName
        let position_i_Factor = i - 1
        alienNode.position = CGPoint(x: size.width / 2 + CGFloat(position_i_Factor * 130), y: size.height / 2 + 200)

        alienNode.physicsBody = SKPhysicsBody(texture: alienNode.texture!, size: alienNode.size)
        alienNode.physicsBody?.affectedByGravity = false
        alienNode.physicsBody?.allowsRotation = false

        alienNode.physicsBody?.mass = 1000000

        alienNode.physicsBody?.categoryBitMask = BodyType.alien.rawValue
        alienNode.physicsBody?.contactTestBitMask = BodyType.bullet.rawValue
    }

when I shoot a bullet, it detected collision pretty well, but when I convert
the SKSpriteNode to AlienNode, it works not good, sometimes it will throw an
error.
Here's the code in didBegin()
    let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]
    print(nodesName)

    if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
        //A bullet hit a alien
        contact.bodyB.node?.removeFromParent() //remove the bullet
        print("hit")
        let alienNode = contact.bodyA.node as! AlienNode// it doesn't work sometimes
        alienNode.hP -= 1
        if alienNode.hP <= 0 {
            alienNode.removeFromParent()
            print("Alien killed")
        }

is that anything wrong with my code, how could I fix this. thank you really much!

A: I guess what @OOPer is hinting at in his comment is:
How do you know that the AlienNode is bodyA.node?
Couldn't it just a well be bodyB.node?
You start out with this to fill your nodesName array
let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]

Next you check that nodesName actually contains kAlienName and kBulletName
if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {

But you still don't know the order of the nodes in your nodesName array.
Sometimes bodyA.node could be an AlienNode and other times it could be bodyB.node.
I imagine something like this could work:
if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
    //find the alien node
    var alienNode: AlienNode?
    if let _ = contact.bodyA.node as? AlienNode {
        //it was a
        alienNode = contact.bodyA.node as? AlienNode
        contact.bodyB.node?.removeFromParent() //remove the bullet
    } else {
        //it was b
        alienNode = contact.bodyB.node as? AlienNode
        contact.bodyA.node?.removeFromParent() //remove the bullet
    }
    print("hit")
    //it should be safe to force unwrap here
    alienNode!.hP -= 1
    if alienNode!.hP <= 0 {
        alienNode!.removeFromParent()
        print("Alien killed")
    }

It is untested but hopefully you get the idea.
Hope that helps.


text:
Q: jquery popbox not popping up all!
I'm sure I'm asking a very basic question, but I spent a whole day on it, and just can't figure it out.
I have a table inside a tabbed box.  And to the table header row I need to add a button that will pop up a box for data entry.  Tabbed area works, the table displays, and the button also.  But when I click on that button, nothing happens.
I'm using the following tutorial as an example
http://gristmill.github.com/jquery-popbox/example.html
Added popbox.js and popbox.css to my html code and added
$(document).ready(function() {
            $("#tabs").tabs();
            $('.popbox').popbox();
        });

at the end of the html file.
However, it doesn't pop up.  I added alerts to the method, and popbox function does get called, but bind does not seem to get executed.  I added some alerts, but alerts are not triggered:
return this.each(function(){
    alert("test1");
  $(this).css({'width': $(settings['box']).width()}); // Width needs to be set otherwise popbox will not move when window resized.
    alert("test2");
  $(settings['open'], this).bind('click', methods.open);
    alert("test3");
  $(settings['open'], this).parent().find(settings['close']).bind('click', methods.close);
});

As far as I see, it's not popping up because the open and close clicks are not bound.  But not sure what is going on.  I'm a newbie at jsp and diving head in into jquery.  Apologize for newbie questions.
Thank you for your help!


text:
Q: Topology of Disjoint Sets Forms Cover I noticed the following when looking at the various topologies on finite sets (specifically 2, 3, and 4 elements).
If $\mathcal{T}$ is a topology on a point set $X$, and $\mathcal{T}\backslash\{X\}$ is pairwise disjoint, then $\mathcal{T}\backslash\{X\}$ forms an open cover of $X$.
I have no idea if this is true. I had tried to create several counterexamples but cannot find any. So is this true in just some cases, or all cases?

A: If $\mathcal{T}\setminus \{X\}$ has at least two non-empty sets $U,V$ in it, such that $U \cup V \neq X$, then $U \cup V$ cannot be disjoint from $U$ or $V$, while all 3 are in  $\mathcal{T}\setminus \{X\}$. And if  $\mathcal{T}\setminus \{X\}$ has three pairwise disjoint non-empty sets $U,V,W$ then $U,V$ satisfy the previous case.
So  $\mathcal{T}\setminus \{X\}$ pairwise disjoint implies that  $\mathcal{T}\setminus \{X\}$ has at most two non-empty sets, and if there are two, their union must equal $X$.
So all such topologies are of the form $\{X,\emptyset\}$, $\{X,\emptyset ,A\}$ or $\{\emptyset, X, A, X\setminus A\}$. In the latter case your cover statement holds, but for the first two it does not. The Sierpinski topology $\{\emptyset ,\{0,1\}, \{0\}\}$ on $\{0,1\}$ is the smallest non-trivial counterexample.  $\mathcal{T}\setminus \{X\}$ is then $\{\emptyset, \{0\}\}$ which is pairwise disjoint but not a cover. You probably encountered the last type a few times, and didn't consider the more trivial examples of pairwise disjoint sets.
So it's true iff $\left|\mathcal{T}\setminus \{X\} \right| = 3$ (including $\emptyset$) and is (pairwise) disjoint.


text:
Q: Multiple yield in Meteor.js application template I have one general {{>yield}} for iron-router in a layout file which renders my pages, which are templates.
In one of my pages, I have a side menu and according to the selection in this menu, I want to load different templates related to this page in this page.
How can I achieve this?

A: I have done a similar thing using iron-router's layout template option. Say I want to create a home view with multiple views/templates inside of this home view that will change. First I would declare my route:
Router.map(function () {
  this.route('home', {
  path: '/',
  template: 'myHomeTemplate',
  layoutTemplate: 'layout',
  yieldTemplates: {
    'myAsideTemplate': {to: 'aside'},
    'myFooter': {to: 'footer'}
    }
  });
});

Where the html for the layout template would look like:
 <template name="layout">

     {{> yield region='aside'}}

    {{> yield}}

    {{> yield region='footer'}}

</template>

So that the templates specified in the yields aside and footer get rendered in the specified spot. For your case you can specify a sidemenu yield.
No that you have the basic layout and idea you can define another route. Say we call it differentHome.
Router.map(function () {
  this.route('differentHome', {
  path: '/differentHome',
  template: 'myHomeTemplate',
  layoutTemplate: 'layout',
  yieldTemplates: {
    'myDifferentAsideTemplate': {to: 'aside'},
    'myDifferentFooter': {to: 'footer'}
    }
  });
});

Notice on this route declaration I am changing the yield templates, but I am not changing the basic template that will be rendered in the main yield. Now on an event you can re-route which will change the two different yields templates:
Router.go("differentHome");

Or you can use html to route, say with a link.
EDIT (Haphazard Solution):
Use Session Variable To Dictate Side Menu choice.
HTML:
<template name="main">
  ......

     {{#if sideMenu1}}
        {{> side1Template}}
     {{/if}}

     {{#if sideMenu2}}
        {{> side2Template}}
     {{/if}}

 </template>

JS:
Template.main.helpers({
    sideMenu1 : function () {
         return Session.equals("sideMenuChoice", "sideMenu1")
    },
    sideMenu2 : function () {
         return Session.equals("sideMenuChoice", "sideMenu2")
    }
 });

Now on an event set the Session to what ever sideMenuChoice.


text:
Q: How to detect IE/Edge using javascript? I am trying to use javascript to apply a certain style to the pages based on which browser the user is using. I can detect all of the browsers except for IE/Edge. In my code snippet I am just trying to detect IE/Edge and apply the style.
Here is my code:
var bodyStyle = document.querySelector("#bodyArea");
if((navigator.userAgent.indexOf("Edge") != -1 ) || (!!document.documentMode == true ))
{
    alert("asdf");
    bodyStyle.style.paddingTop = "500px";
}
else
{
    bodyStyle.style.paddingTop = "300px";
}

When I put an alert in the else section it gives me an alert, but it doesn't work on the if part. So I think my problem is occurring when I try to detect IE/Edge. Or if it lay elsewhere, let me know. If anyone has any feedback, it will be greatly appreciated. Thanks in advance!

A: You can use this custom script to detect IE/Edge:
if (/MSIE 10/i.test(navigator.userAgent)) {
   // this is internet explorer 10
   window.alert('isIE10');
}

if(/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)){
    // this is internet explorer 9 and 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/12./i.test(navigator.userAgent)){
   // this is Microsoft Edge
   window.alert('Microsoft Edge');
}

Check out this page for the latest IE and Edge user agent strings: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx


text:
Q: Small Lines On Webpage From Unknown Code On this website, there are lines on the side and top, almost as if they are margins, but I can't find the code that is the cause. What is causing those lines?

A: The background color of the page is #000000 (black) as you can see in assets/main.css. However, there is a white #pageoverview over the black background.

A: It's part of the user agent style sheet. This stylesheet has a default margin value of 8px. You can see this in the inspector:


text:
Q: My Haskell Solution to Euler #3 is Inefficient I am attempting to solve Euler problem 3 in Haskell, which involves finding the largest prime factor of a number. My code runs for a long time and seems to hang. What is causing my code to be so grossly inefficient?
primes = sieve (2:[3,5..])
 where sieve (x:xs) = x:[y | y <- (sieve xs), mod y x /= 0]
       sieve [] = []
primefactors n = filter (\x -> mod n x == 0) (primesUnder n)
 where primesUnder z = reverse (takeWhile (< z) primes)
solve3 = head (primefactors 600851475143)

A: Your main problem is you're checking for enormous primes -- all the way up to 600851475143. You can improve things a lot by observing two things:

*

*Every time you find a prime, you can decrease the maximum prime you look at by dividing away that factor.

*You only have to look for primes until you reach the square root of the target. If your primes are bigger than that, and you know there are no smaller factors, you're done.

Using these two improvements together, even without the nicety that you used of only checking primes for divisibility, makes the program run in a snap:
factor = go (2:[3,5..]) where
    go (p:ps) n
        | p*p > n        = [n]
        | n `mod` p == 0 = p : go (p:ps) (n `div` p)
        | otherwise      = go ps n
main = print . last . factor $ 600851475143

In ghci:
*Main> main
6857
(0.00 secs, 0 bytes)

You can see that we only had to inspect numbers up to 6857 -- eight orders of magnitude smaller than what you would have to do with your approach.
Independently, your sieve is dog slow. You could have a look at the wiki for ideas about how to find primes quickly.


text:
Q: change the order of bars on sas graph I have a macro that produce a graph as in image graph. I want to change the order of bars to Dev 201601 201602 201603 201604 201605 instead of
201601 201602 201603 201604 201605 Dev. Here is my code
goptions reset=global gunit=pct border cback=white
colors=(black red green blue) ftitle=swissb
ftext=ZAPFB htitle=5 htext=1.7
offshadow=(1.5,1.5);
axis1 label=none;
axis2 label=none value=none
order=(0 to 110 by 10)
major=none
minor=none;
legend1 cborder=black cblock=CXF0E68C label=none
shape=bar(3,3)
POSITION=(bottom center);
pattern1 color=vpapb;
pattern2 color=bigy;
pattern3 color=paoy;
pattern4 color=vligb;
pattern5 color=lipk;
pattern6 color=vpap;
pattern7 color=pab;
pattern8 color=lio;

proc gchart data= Recent.char_&value;
title ;
vbar Period / sumvar=Percent
subgroup=&value
inside=subpct
width=12
space=8
maxis=axis1
raxis=axis2
legend=legend1
cframe=BWH
coutline=black;

What should I do to solve the problem?

A: The easiest way to do this is to have your bar value be an ordering value that you use a format to display as your actual value.  So here I have 0 = Dev, 1 = 201601, 2 = 201602, etc.; I use a picture format to get there since things work so nicely, but you could use a regular value format if there's not a simple logical mapping like this.
data test_data;
input period value; /* you may need to convert from '201601' to '1' if your data already has 201601 type values;  use an informat (opposite of format). */
datalines;
1 10
2 20
3 25
4 25
5 30
0 20
;;;;
run;

proc format;
picture periodF
0 = 'Dev'  /* map 0 to Dev */
1-12 = 99 (prefix='2016');  /* for values 1-12, display in 2 digit zero padded format, prefix with 2016) */
quit;

proc sgplot data=test_data;
  format period periodf.;    /*apply format here or in an earlier datastep */
  vbar period/response=value;
run;


text:
Q: Search associative array of arrays. How? My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.
Please feel free to improve on array layout.
$price_list = array(
  1 => array("9.99", "EA_WTRESRVD"),
  2 => array("9.99", "EA_WTRESRV")
);

A: Provided there will never be any duplication of the second column, you can do this:
$search = "EA_WTRESRVD"; //value to search for

$price_list = array(
  1 => array("9.99", "EA_WTRESRVD"),
  2 => array("9.99", "EA_WTRESRV")
);

$array = array_column($price_list, 0, 1);
echo $array[$search];

A: I would suggest that if you have a unique product code (SKU), you should use this to index your array.
$products = [
    'EA_WTRESRVD' => [
        'name'  => '...',
        'price' => 9.99,
        // ...
    ],
    'EA_WTRESRV' => [
        'name'  => '...',
        'price' => 9.99,
        // ...
    ],
];

Then you can access the price of any product by it's SKU.
$price = $products['EA_WTRESRV']['price'];

A: Here's one way:
<?php

$price_list = [  1 => array("9.99", "EA_WTRESRVD"),
                 2 => array("9.99", "EA_WTRESRV")];

$search = "EA_WTRESRV";

foreach ($price_list as $arr) {
  if (in_array( $search, $arr )) {
        echo $search;
  }
}

The foreach iterates over the multidimensional array whose elements are each arrays.  Each array is inspected by in_array() for the search term.
However, this is not the only way.  If you wish to avoid in_array(), you could also code as follows:

<?php

$price_list = [  1 => array("9.99", "EA_WTRESRVD"),
                 2 => array("9.99", "EA_WTRESRV")];

$search = "EA_WTRESRV";
$len = strlen($search);

foreach ($price_list as $arr) {
  $val = array_values($arr);

  foreach($val as $v) {
     if ( ( strpos( $v,$search )) !== false) {
        if ( strlen($v) == $len) {
             echo "$search is in the price list.\n";
        }
     }
  }
}


text:
Q: Prove: $E^1_u$ with the usual topology is a Baire space I need to prove that the euclidean line is a Baire Space.
I have this definitions for Baire Space:

*

*A space $Y$ is a Baire space if the intersection of each countable family of open dense sets in $Y$ is dense.

-$X$ is a Baire Space if the following condition holds: Given any countable collection $\{A_n\}$ of closed sets of $X$ each of which has empty interior in $X$, their union $\cup A_n$ also has empty interior in $X$.
I know that $E^1_u$ with the usual topology is $\mathbb{R}$ and this is of second category and we have that Baire space is of second category but "Not all space of the second category is Baire Space". So I have troubless to do this proof. Thank you very much.

A: We can prove that the space $\Bbb R$ is Baire using the fact that each its non-empty open subset has an open homeomorphic copy of $\Bbb R$ which is of second category in itself, or directly as it the following theorem   from "Baire spaces" by Haworth and McCoy.


text:
Q: Why don't I see events relating to failed Kubernetes probes? I have defined readiness and liveness probes for the container in a Kubernetes deployment. When these fail I expect to see their output included in an event for the pod. However I don't see such events. I do see other events for the same pod.
I am running on GKE, with Kubernetes v1.6.4.
The code that should produce the events is here: https://github.com/kubernetes/kubernetes/blob/v1.6.4/pkg/kubelet/prober/prober.go#L94.
What I see instead is logs indicating that a "ref" for the container could not be retrieved. I see similar logs for other places in the code that try to record container-related events.
Is this a bug? These events are potentially very useful. In particular it's the only way to see output from a failing probe so that I can diagnose probes that are failing unexpectedly.
[I'm not certain if this is an appropriate issue for StackOverflow. Please let me know if it would be better raised as an issue in Github.]

A: This was a bug that has been fixed in Kubernetes 1.6.7.


text:
Q: Sending the name of a function to a function What I want to do is:
class A
{
    public:
    double sum(double a, double b);
    double max(double a, double b);
}

template <typename T>
class B
{
    std::vector<T> data;

    public:

    double sum (double a, double b);
    double max (double a, double b);
    double average( MyFunction, double a, dobule b)
    {
        double sum = 0;
        int n = data.size();

        for ( int i = 0; i < n; i++)
            sum = sum + data[i].MyFunction(double a, double b)

            return sum / n;
    }

}

example:
double average( max, double a, double b)
{
    double sum = 0;
    int n = data.size();

    for ( int i = 0; i < n; i++)
        sum = sum + data[i].max(double a, double b)

        return sum / n;
}

Why?

*

*it would save me to write function like: average of sum. average of max. average of min
which are all pretty similar functions.

*the way it is coded B< B< A> > works

What have I tried?

*

*function pointer

*S1:
  typedef double (A::*MyFunctionf)(double, double);
  typedef double (B<A>::*MyFunctionff)(double, double);
  typedef double (B<B<A> >::*MyFunctionfff)(double, double);

*

*it Works. Problems:

*

*it is not beautiful to declare 3-4 typedef of function pointer

*if I want to write the function inside B that sent a function pointer it will be hard coded and only 1 of the 3 typedef can be hard coded. Meaning: it is not working for every cases

*S2 (based on Template typedefs - What's your work around?):
  template <typename rtype, typename t>
  struct CallTemplate
  {
    typedef rtype (t::*ptr)(double, double);
  };

 // the function becomes :
 template <typename T>
 template<typename rtype>
 double B<T>::average(CallTemplate<double, T> MyFunction, double a, double b)
 {
    double sum = 0;
   int n = data.size();

      for ( int i = 0; i < n; i++)
        sum = sum + (data[i].*MyFunction)( a, b)

    return sum / n;
  }

example:
 // makes an error "Myfunction was not declared" + "
 // dependent-name'{anonymous}::CallTemplate<double, A>::ptr'
 // is parsed as a non-type, but instantiation yields a type"
 CallTemplate<double, A>::ptr MyFunction = &A::max;
 Average(max, t, v);

I do not know where the problem comes from.
I have also tried Boost.Function

A: Yes it's possibile.
You're looking for member pointers. The syntax is not obvious however:
struct A
{
    double x, y;
    A(double x, double y) : x(x), y(y) {}
    double sum() { return x + y; }
    double max() { return std::max(x, y); }
};

This is a class that defines a couple of methods (sum and max).
template <typename T>
struct B
{
    std::vector<T> data;
    double average(double (T::*MyMethod)())
    {
        double sum = 0;
        int n = data.size();
        for (int i = 0; i < n; i++)
            sum = sum + (data[i].*MyMethod)();
        return sum / n;
    }
};

This is a class with a method that accepts a method pointer and that will compute the average of the result of calling the pointed method over the elements of a vector.
An example of passing the two A methods is:
int main(int argc, const char *argv[]) {
    B<A> b;
    b.data.push_back(A(1, 2));
    b.data.push_back(A(3, 4));
    b.data.push_back(A(5, 6));
    std::cout << b.average(&A::max) << std::endl;
    std::cout << b.average(&A::sum) << std::endl;
    return 0;
}

A: Solution With Boost.Function
class A
{
    public:
    double sum(double a, double b);
    double max(double a, double b);
}

template <typename T>
class B
{
    std::vector<T> data;

    public:

    double sum (double a, double b);
    double max (double a, double b);
    double average(boost::function<double (T*, double, double) MyFunction, double a, dobule b)
    {
        double sum = 0;
        int n = data.size();

        for ( int i = 0; i < n; i++)
            sum = sum + MyFunction(&data[i], a, b)

            return sum / n;
    }

}

example
boost::function<double (A*, a, b)> MyFunction = &A::max;
average(MyFunction, a, b);

The working example ::
#include <cmath>

using namespace std;

#include <vector>
#include <boost/function.hpp>

#define CallTemplate(returnvalue, FINClass) boost::function<returnvalue (FINClass*, double, double)>

class zc
{
    double n;
    double r;
    double p;

    public:
    zc(double nn, double rr, double pp):n(nn), r(rr), p(pp) {}

    double pv(double t, double v) { return p/ pow ( ( 1 + r + v), ( n - t) );}
    double d(double t, double v)  { return (n - t); }
    double c(double t, double v)  { return (n - t)*(n - t)+(n - t); }
};

template <typename T>
class Master
{
    public:

    Master(){}
    std::vector<T> data;

    double pv(double t, double v) {CallTemplate(double, T) f = &T::pv;  return sum(f, t, v);}
    double d(double t, double v)  {CallTemplate(double, T) f = &T::d;   return weightedAverage(f, t, v);}
    double c(double t, double v)  {CallTemplate(double, T) f = &T::c;   return weightedAverage(f, t, v);}

    double sum(CallTemplate(double, T) MyFunction, double t, double v)
    {
        double sum = 0;
        for( int i = 0, n = data.size(); i < n; i++)
            sum = sum + MyFunction(&data[i], t, v);

        return sum;
    }

    double weightedAverage(CallTemplate(double, T) MyFunction, double t, double v)
    {
        double sum = 0;
        double weight = 0;
        double buf =0;

        for( int i = 0, n = data.size(); i < n; i++)
        {
            buf = data[i].pv(t, v);

            sum = sum + buf;

            weight = weight + MyFunction(&data[i], t, v) * buf;
        }

        return weight/sum;
    }

};

int main()
{
    Master<zc> A;

    for (int i = 1; i < 10; i++)
        A.data.push_back(zc(i, 0.1, 100));

    A.data.push_back(zc(10, 0.1, 1100));

    cout << A.pv(0, 0) << endl;
    cout << A.d(0, 0) << endl;
    cout << A.c(0, 0) << endl;

    return 0;
}

A: The common C++ idiom to do these kind of things is to pass a function "object" and accept it as a template parameter:
#include <algorithm>

// definition of class A by user http://stackoverflow.com/users/320726/6502
// in answer http://stackoverflow.com/a/18944672/420683
struct A
{
    double x, y;
    A(double x, double y) : x(x), y(y) {}
    double sum() const { return x + y; }
    double max() const { return std::max(x, y); }
};

template <typename T>
struct B
{
    std::vector<T> data;
    template<class Function>
    double average(Function f)
    {
        double sum = 0;
        int n = data.size();
        for (int i = 0; i < n; i++)
            sum = sum + f(data[i]);
        return sum / n;
    }
};

#include <functional>

int main()
{
    B<A> b{ {{1.0, 42.0}, {2.0, 43.0}, {3.0, 44.0}} };
    b.average([](A const& p){ return p.sum(); });
    b.average(std::mem_fn(&A::sum));
}

This is very general approach as it not only accepts function pointers or member function pointers, but any kind of callable object. Using a member function pointer is simple via std::mem_fn.


text:
Q: Query JSONPath in JQ Format I have JSONPath:
$.endpointAgents[?(@.clients.userName=~ 'a')].agentId

How it will look in jq format on Linux??
jq '.endpointAgents [] | select(.clients.userName=~"a") | {agentId}')"

does not work.
Code:
{
  "endpointAgents": [
    {
      "agentId": "MyId",
      "agentName": "MYNAME",
      "location": {
        "locationName": "location"
      },
      "clients": [
        {
          "userProfile": {
            "userName": "Name"
          },
          "browserExtensions": [
            {
              "active": false
            }
          ]
        }
      ],
      "totalMemory": "16222 MB",
      "agentType": "enterprise"
    }
  ]
}

A:
I want to get userName value by specifying agentId

jq '.endpointAgents[] | select(.agentId == "MyId") | .clients[].userProfile.userName'

Will output "Name"

*

*.endpointAgents[]
Loop over each endpointAgent

*select(.agentId == "MyId")
Select the objects where .agentId == "MyId"

*.clients[].userProfile.userName
Since clients is an array, loop over it, and show .userProfile.userName for each object.

Try it online!

A: If I understand correctly, you want to produce the agent id of endpoints with a client whose name matches a.
.endpointAgents[] |
select( any( .clients[].userProfile.userName; test("a") ) ) |
.agentId

To produce the agent id of endpoints with a client whose name is equal to a, use the following instead:
.endpointAgents[] |
select( any( .clients[].userProfile.userName; . == "a" ) ) |
.agentId


text:
Q: All integer solutions of $x^3-y^3=2020$.
Find all integer pairs  $(x,y)$ satisfying $$x^3-y^3=2020\,.$$

First,
$x^3-y^3=(x-y)(x^2+xy+y^2)=2020$
and $2020=2^2\cdot 5 \cdot 101$.
But what next? Can it be worked out by using modulo? Or how?
Any idea? Thanks in advance.

A: Let $d = x - y$. Then we want $x^3 - (x-d)^3 = 2020$, which is a quadratic equation in $x$. The discriminant is $24240d - 3d^4 = 3d (8080 - d^3)$, which is nonnegative only for $d \in [0, 8080^{1/3}]$, and since $d$ is an integer it must be between $0$ and $20$.
Moreover, since $(x-y)^3 = d(x^2 + xy + y^2) = 2020$, $d$ must be a divisor of $2020$. This leaves only $6$ possibilities: $d = 1, 2, 4, 5, 10, 20$. We already had a finite problem to solve before, but this observation reduces the number of cases.
For each value of $d$, the solutions to the quadratic equation have irrational solutions, so there are no integer solutions $(x,y)$.

A: There are no solutions, because $x^3,y^3\equiv0$ or $\pm1\pmod7$, but $2020\equiv4\bmod7$.

A: Alternatively, if $p$ is a prime natural number that divides $x^2+xy+y^2$, then $$(2x+y)^2+3y^2=4(x^2+xy+y^2)\equiv 0\pmod{p}\,.$$  Thus, either $p$ divides both $x$ and $y$, or $\left(\dfrac{-3}{p}\right)=1$.  Now, by quadratic reciprocity,
$$1=\left(\dfrac{-3}{p}\right)=\left(\dfrac{p}{-3}\right)=\left(\dfrac{p}{3}\right)\,,$$
whence $p\equiv 1\pmod{3}$.  Because $$(x-y)(x^2+xy+y^2)=x^3-y^3=2020=2^2\cdot 5\cdot 101$$ with $5\not\equiv 1\pmod{3}$ and $101\not\equiv 1\pmod{3}$, we conclude that $5$ and $101$ cannot divide $x^2+xy+y^2$.  Thus, the only possible prime divisor of $x^2+xy+y^2$ is $2$, and if $2\not\equiv 1\pmod{3}$ is a factor of $x^2+xy+y^2$, we must have $2\mid x$ and $2\mid y$.  Since $x^2+xy+y^2\geq 0$, this implies
$$x^2+xy+y^2=1\text{ or }x^2+xy+y^2=4\,.$$
The only solutions $(x,y)\in\mathbb{Z}\times\mathbb{Z}$ to $x^2+xy+y^2=1$ are $$(x,y)=\pm (1,0),\pm(0,1),\pm(1,-1)\,.$$
The only solutions $(x,y)\in\mathbb{Z}\times\mathbb{Z}$ to $x^2+xy+y^2=4$ are $$(x,y)=\pm (2,0),\pm(0,2),\pm(2,-2)\,.$$
None of these solutions satisfies $x^3-y^3=2020$.


text:
Q: How to show different tool-tip images on hover in following scenario where the same tool-tip image is appearing? I've following HTML code :

Now I want to show the different tool tip image for each of the images on hovering over them. For it I've written following CSS but with it I'm able to show only one image in a tool-tip for all the three images which I want to avoid.
How should I achieve this?
Following is CSS code :
CSS Code :
    tr span {
    display: block;
    position: relative;
}
tr span:hover {
    z-index: 1;
}
tr span:hover:after {
    content:"";
    background-image: url('http://lorempixel.com/273/274/');
    position: absolute;
    top:50%;
    left: 50%;
    width: 273px;
    height: 274px;
}

JSFiddle

A: I would make the following changes:

And on the HTML:

And if you want the images in thumbs to be different just change or remove the class names on thumbs div.


text:
Q: Как получить информацию из строки json, которая указана в Javascript коде внутри html страницы, используя python3.x? Всем доброго времени суток.
Есть один код, который парсит html с помощью requests.get.
Далее из полученного html мне необходимо взять json строку ...
<script>
    try{
        try{
            var card = JSON.parse('{"CardPAN":"1234567890123456789","EndDate":"01.01.2016","TicketTypeDesc":"00.04 CardName","CityName":"City","CardSum":99,"Time":"01.09.2016 11:11:01"}');
        }
 ...

из которой мне необходим параметр CardSum.
Пытался с помощью beautifulsoup что-то вроде soup.find_all('try')) и soup.find_all('var')) и soup.find('var', 'CardSum') и так далее - везде выходило пустое значение.
Буду рад любым советам.

A: Всё очень просто. JSON надо преобразовать в объект, и оттуда взять нужное.
inputString = '{YOUR_JSON_STRING}'
resultData = json.loads(resultString)

И в resultData['CardSum'] ваши данные.

A: requests.get() вызов не распознаёт html, он просто загружает указанную страницу. Чтобы распознать html, нужен html-парсер. Чтобы распознать javascript, нужен javascript парсер. Чтобы распознать json, нужен json парсер.
Простейший (и самый хрупкий вариант) это просто использовать регулярное выражение, чтобы получить необходимую информацию:
card_sum = int(re.search(r'"CardSum"\s*:\s*(\d+)', html).group(1))

Можно комбинировать применение парсеров с регулярными выражениями, чтобы повысить устойчивость и общность кода.


text:
Q: Why variable doesn't work inside for /F command? If you have a variable inside this for /f command, it doesn't get printed out to file.
setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo %duration% > file.txt
)

Contents of file.txt: Echo is ON.
If you move set duration=asdf out of for /f wrap and put it below setlocal line it works correct and prints asdf into file.txt
Why? How do I do this with the set variable inside the for command?

A: This is due to delayed expansion, which stops variables from being set and used, in the same command.
You are getting Echo is ON. in file.txt, because to the command interpreter it's reading the echo command as:
echo > file.txt

Which as documented by echo /?

Type ECHO without parameters to display the current echo setting.

The simplest fix is to replace the % with !
Updated script:
setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo !duration! > file.txt
)


text:
Q: Convert List to datatable, having some properties also as List I need to create a DataTable from a List of objects of type DetalleHora. This post explains how to accomplish it, creating a column for each property of DetalleHora.
The problem I am facing is that one the properties of DetalleHora is a List of objects of type Hora, which will contain an undefined number of items (that's why I can't do this), and I can't get to iterate through this List so that the resulting DataTable contains a column for each one of the  items.
This is the DetalleHora class definition:
class DetalleHora
{
    public int Id { get; set; }
    public string Fecha { get; set; }
    public string Solicitante { get; set; }
    public string Orden { get; set; }
    public string DMR { get; set; }
    public string Descripcion { get; set; }
    public string Operario { get; set; }
    public string Entrada { get; set; }
    public string Salida { get; set; }
    public List<Hora> Horas { get; set; }
    public double TotalHoras { get; set; }
    public string FirmaSolicitante { get; set; }
    public int NumeroSemana { get; set; }
}

This is the Hora class definition:
public class Hora
{
    public int IdTipoHora { get; set; }
    public string Tipo { get; set; }
    public double Cantidad { get; set; }
}

This is what I've doing (per one of the links below):
public DataTable ListToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            // ******* I need a new column for each item in the List<Hora> Property
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                // *********** BUT THIS WON'T WORK WHEN PROPERTY IS A LIST<T>
                // I need a new column for each of the items in the List<Hora> Property
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }

I've looking for a way to determine if a given property is a List of a specific type of object, but none of the folowing approaches seemed to work for me:

*

*How do I check if a given value is a generic list?

*Check if Property is List using Reflection in C#

*How to know if a PropertyInfo is a collection

A: I wanted to convert the List<DetalleHora> to a DataTable in order to use it to generate an Excel file using NPOI libraries in an elegant and efficient way.
However, since I was in a hurry, I discarded the original idea and decided to write the Excel file looping through the Lists' items.
Thanks anyway.

A: Try Following
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Fecha", typeof(string));
            dt.Columns.Add("Solicitante", typeof(string));
            dt.Columns.Add("Orden", typeof(string));
            dt.Columns.Add("DMR", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            dt.Columns.Add("Operario", typeof(string));
            dt.Columns.Add("Entrada", typeof(string));
            dt.Columns.Add("Salida", typeof(string));
            dt.Columns.Add("IdTipoHora", typeof(int));
            dt.Columns.Add("Tipo", typeof(string));
            dt.Columns.Add("Cantidad", typeof(string));
            dt.Columns.Add("TotalHoras", typeof(double));
            dt.Columns.Add("FirmSolicitante", typeof(string));
            dt.Columns.Add("NumeroSemana", typeof(int));

            List<DetalleHora> detailHoras = new List<DetalleHora>();

            foreach (DetalleHora detailHora in detailHoras)
            {
                foreach (Hora hora in detailHora.Horas)
                {
                    dt.Rows.Add(new object[] {
                        detailHora.Id,
                        detailHora.Fecha,
                        detailHora.Solicitante,
                        detailHora.Orden,
                        detailHora.DMR,
                        detailHora.Description,
                        detailHora.Operario,
                        detailHora.Entrada,
                        detailHora.Salida,
                        hora.IdTipoHora,
                        hora.Tipo,
                        hora.Cantidad,
                        detailHora.TotalHoras,
                        detailHora.FirmaSolicitante,
                        detailHora.NumeroSemana
                    });
                }
            }

        }
    }
    class DetalleHora
    {
        public int Id { get; set; }
        public string Fecha { get; set; }
        public string Solicitante { get; set; }
        public string Orden { get; set; }
        public string DMR { get; set; }
        public string Description { get; set; }
        public string Operario { get; set; }
        public string Entrada { get; set; }
        public string Salida { get; set; }
        public List<Hora> Horas { get; set; }
        public double TotalHoras { get; set; }
        public string FirmaSolicitante { get; set; }
        public int NumeroSemana { get; set; }
    }
    public class Hora
    {
        public int IdTipoHora { get; set; }
        public string Tipo { get; set; }
        public double Cantidad { get; set; }
    }
}