text:
Q: How to split but ignore separators in quoted strings, in python? I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks.
part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5
Result should be:

*

*part 1

*"this is ; part 2;"

*'this is ; part 3'

*part 4

*this "is ; part" 5

I suppose this can be done with a regex but if not; I'm open to another approach.

A: You appears to have a semi-colon seperated string. Why not use the csv module to do all the hard work?
Off the top of my head, this should work
import csv
from StringIO import StringIO

line = '''part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5'''

data = StringIO(line)
reader = csv.reader(data, delimiter=';')
for row in reader:
    print row

This should give you something like
("part 1", "this is ; part 2;", 'this is ; part 3', "part 4", "this \"is ; part\" 5")
Edit:
Unfortunately, this doesn't quite work, (even if you do use StringIO, as I intended), due to the mixed string quotes (both single and double). What you actually get is
['part 1', 'this is ; part 2;', "'this is ", " part 3'", 'part 4', 'this "is ', ' part" 5'].
If you can change the data to only contain single or double quotes at the appropriate places, it should work fine, but that sort of negates the question a bit.

A: Most of the answers seem massively over complicated. You don't need back references. You don't need to depend on whether or not re.findall gives overlapping matches.  Given that the input cannot be parsed with the csv module so a regular expression is pretty well the only way to go, all you need is to call re.split with a pattern that matches a field.
Note that it is much easier here to match a field than it is to match a separator:
import re
data = """part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5"""
PATTERN = re.compile(r'''((?:[^;"']|"[^"]*"|'[^']*')+)''')
print PATTERN.split(data)[1::2]

and the output is:
['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ; part" 5']

As Jean-Luc Nacif Coelho correctly points out this won't handle empty groups correctly. Depending on the situation that may or may not matter. If it does matter it may be possible to handle it by, for example, replacing ';;' with ';<marker>;' where <marker> would have to be some string (without semicolons) that you know does not appear in the data before the split. Also you need to restore the data after:
>>> marker = ";!$%^&;"
>>> [r.replace(marker[1:-1],'') for r in PATTERN.split("aaa;;aaa;'b;;b'".replace(';;', marker))[1::2]]
['aaa', '', 'aaa', "'b;;b'"]

However this is a kludge. Any better suggestions?

A: re.split(''';(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', data)

Each time it finds a semicolon, the lookahead scans the entire remaining string, making sure there's an even number of single-quotes and an even number of double-quotes.  (Single-quotes inside double-quoted fields, or vice-versa, are ignored.)  If the lookahead succeeds, the semicolon is a delimiter.
Unlike Duncan's solution, which matches the fields rather than the delimiters, this one has no problem with empty fields.  (Not even the last one: unlike many other split implementations, Python's does not automatically discard trailing empty fields.)

A: While it could be done with PCRE via lookaheads/behinds/backreferences, it's not really actually a task that regex is designed for due to the need to match balanced pairs of quotes.
Instead it's probably best to just make a mini state machine and parse through the string like that.
Edit
As it turns out, due to the handy additional feature of Python re.findall which guarantees non-overlapping matches, this can be more straightforward to do with a regex in Python than it might otherwise be. See comments for details.
However, if you're curious about what a non-regex implementation might look like:
x = """part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5"""

results = [[]]
quote = None
for c in x:
  if c == "'" or c == '"':
    if c == quote:
      quote = None
    elif quote == None:
      quote = c
  elif c == ';':
    if quote == None:
      results.append([])
      continue
  results[-1].append(c)

results = [''.join(x) for x in results]

# results = ['part 1', '"this is ; part 2;"', "'this is ; part 3'",
#            'part 4', 'this "is ; part" 5']

A: >>> x = '''part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5'''
>>> import re
>>> re.findall(r'''(?:[^;'"]+|'(?:[^']|\\.)*'|"(?:[^']|\\.)*")+''', x)
['part 1', "this is ';' part 2", "'this is ; part 3'", 'part 4', 'this "is ; part" 5']

A: >>> a='A,"B,C",D'
>>> a.split(',')
['A', '"B', 'C"', 'D']

It failed. Now try csv module
>>> import csv
>>> from StringIO import StringIO
>>> data = StringIO(a)
>>> data
<StringIO.StringIO instance at 0x107eaa368>
>>> reader = csv.reader(data, delimiter=',')
>>> for row in reader: print row
...
['A,"B,C",D']

A: since you do not have '\n', use it to replace any ';' that is not in a quote string
>>> new_s = ''
>>> is_open = False

>>> for c in s:
...     if c == ';' and not is_open:
...         c = '\n'
...     elif c in ('"',"'"):
...         is_open = not is_open
...     new_s += c

>>> result = new_s.split('\n')

>>> result
['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ; part" 5']

A: we can create a function of its own
def split_with_commas_outside_of_quotes(string):
    arr = []
    start, flag = 0, False
    for pos, x in enumerate(string):
        if x == '"':
            flag= not(flag)
        if flag == False and x == ',':
            arr.append(string[start:pos])
            start = pos+1
    arr.append(string[start:pos])
    return arr

A: Here is an annotated pyparsing approach:
from pyparsing import (printables, originalTextFor, OneOrMore,
    quotedString, Word, delimitedList)

# unquoted words can contain anything but a semicolon
printables_less_semicolon = printables.replace(';','')

# capture content between ';'s, and preserve original text
content = originalTextFor(
    OneOrMore(quotedString | Word(printables_less_semicolon)))

# process the string
print delimitedList(content, ';').parseString(test)

giving
['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4',
 'this "is ; part" 5']

By using pyparsing's provided quotedString, you also get support for escaped quotes.
You also were unclear how to handle leading whitespace before or after a semicolon delimiter, and none of your fields in your sample text has any.  Pyparsing would parse "a; b ; c" as:
['a', 'b', 'c']

A: This regex will do that: (?:^|;)("(?:[^"]+|"")*"|[^;]*)

A: Although the topic is old and previous answers are working well, I propose my own implementation of the split function in python.
This works fine if you don't need to process large number of strings and is easily customizable.
Here's my function:
# l is string to parse;
# splitchar is the separator
# ignore char is the char between which you don't want to split

def splitstring(l, splitchar, ignorechar):
    result = []
    string = ""
    ignore = False
    for c in l:
        if c == ignorechar:
            ignore = True if ignore == False else False
        elif c == splitchar and not ignore:
            result.append(string)
            string = ""
        else:
            string += c
    return result

So you can run:
line= """part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5"""
splitted_data = splitstring(line, ';', '"')

result:
['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ; part" 5']

The advantage is that this function works with empty fields and with any number of separators in the string.
Hope this helps!

A: Even though I'm certain there is a clean regex solution (so far I like @noiflection's answer), here is a quick-and-dirty non-regex answer.
s = """part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5"""

inQuotes = False
current = ""
results = []
currentQuote = ""
for c in s:
    if not inQuotes and c == ";":
        results.append(current)
        current = ""
    elif not inQuotes and (c == '"' or c == "'"):
        currentQuote = c
        inQuotes = True
    elif inQuotes and c == currentQuote:
        currentQuote = ""
        inQuotes = False
    else:
        current += c

results.append(current)

print results
# ['part 1', 'this is ; part 2;', 'this is ; part 3', 'part 4', 'this is ; part 5']

(I've never put together something of this sort, feel free to critique my form!)

A: My approach is to replace all non-quoted occurrences of the semi-colon with another character which will never appear in the text, then split on that character. The following code uses the re.sub function with a function argument to search and replace all occurrences of a srch string, not enclosed in single or double quotes or parens, brackets or braces, with a repl string:
def srchrepl(srch, repl, string):
    """
    Replace non-bracketed/quoted occurrences of srch with repl in string.
    """
    resrchrepl = re.compile(r"""(?P<lbrkt>[([{])|(?P<quote>['"])|(?P<sep>["""
                          + srch + """])|(?P<rbrkt>[)\]}])""")
    return resrchrepl.sub(_subfact(repl), string)

def _subfact(repl):
    """
    Replacement function factory for regex sub method in srchrepl.
    """
    level = 0
    qtflags = 0
    def subf(mo):
        nonlocal level, qtflags
        sepfound = mo.group('sep')
        if  sepfound:
            if level == 0 and qtflags == 0:
                return repl
            else:
                return mo.group(0)
        elif mo.group('lbrkt'):
            if qtflags == 0:
                level += 1
            return mo.group(0)
        elif mo.group('quote') == "'":
            qtflags ^= 1            # toggle bit 1
            return "'"
        elif mo.group('quote') == '"':
            qtflags ^= 2            # toggle bit 2
            return '"'
        elif mo.group('rbrkt'):
            if qtflags == 0:
                level -= 1
            return mo.group(0)
    return subf

If you don't care about the bracketed characters, you can simplify this code a lot.
Say you wanted to use a pipe or vertical bar as the substitute character, you would do:
mylist = srchrepl(';', '|', mytext).split('|')

BTW, this uses nonlocal from Python 3.1, change it to global if you need to.

A: A generalized solution:
import re
regex = '''(?:(?:[^{0}"']|"[^"]*(?:"|$)|'[^']*(?:'|$))+|(?={0}{0})|(?={0}$)|(?=^{0}))'''

delimiter = ';'
data2 = ''';field 1;"field 2";;'field;4';;;field';'7;'''
field = re.compile(regex.format(delimiter))
print(field.findall(data2))

Outputs:
['', 'field 1', '"field 2"', '', "'field;4'", '', '', "field';'7", '']

This solution:

*

*captures all the empty groups (including at the beginning and at the end)

*works for most popular delimiters including space, tab, and
comma

*treats quotes inside quotes of the other type as non-special characters

*if an unmatched unquoted quote is encountered, treats the remainders of the line as quoted

A: Instead of splitting on a separator pattern, just capture whatever you need:
>>> import re
>>> data = '''part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5'''
>>> re.findall(r';([\'"][^\'"]+[\'"]|[^;]+)', ';' + data)
['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ', ' part" 5']

A: Simplest is to use shlex (Simple lexical analysis) -- a built in module in Python
import shlex
shlex.split("""part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5 """ )

['part',
 '1;this is ; part 2;;this is ; part 3;part',
 '4;this',
 'is ; part',
 '5']

A: This seemed to me an semi-elegant solution.
New Solution:
import re
reg = re.compile('(\'|").*?\\1')
pp = re.compile('.*?;')
def splitter(string):
    #add a last semicolon
    string += ';'
    replaces = []
    s = string
    i = 1
    #replace the content of each quote for a code
    for quote in reg.finditer(string):
        out = string[quote.start():quote.end()]
        s = s.replace(out, '**' + str(i) + '**')
        replaces.append(out)
        i+=1
    #split the string without quotes
    res = pp.findall(s)

    #add the quotes again
    #TODO this part could be faster.
    #(lineal instead of quadratic)
    i = 1
    for replace in replaces:
        for x in range(len(res)):
            res[x] = res[x].replace('**' + str(i) + '**', replace)
        i+=1
    return res

Old solution:
I choose to match if there was an opening quote and wait it to close, and the match an ending semicolon. each "part" you want to match needs to end in semicolon.
so this match things like this :

*

*'foobar;.sska';

*"akjshd;asjkdhkj..,";

*asdkjhakjhajsd.jhdf;

Code:
mm = re.compile('''((?P<quote>'|")?.*?(?(quote)\\2|);)''')
res = mm.findall('''part 1;"this is ; part 2;";'this is ; part 3';part 4''')

you may have to do some postprocessing to res, but it contains what you want.


text:
Q: How to use a heroku app inside a html iframe? I want to use this heroku app (spring boot) inside an iframe. https://sef-github-leaderboard.herokuapp.com/ but it doesn't work. it says refused to connect. Here's the code.
<!DOCTYPE html>
<html>
<body>

<iframe src="https://sef-github-leaderboard.herokuapp.com/" title="Iframe Example" style="height:500px;width:100%;"></iframe>

</body>
</html>

A: If you open up devtools, click the Network tab, refresh the page, and click the first item in the waterfall, you'll find that the Content Security Policy header X-Frame-Options is set to DENY on the URL you are seeking to embed. This instructs the browser to disallow loading the page within an iframe. To get around this, you would need to use a forward proxy to strip out the headers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ OpenGL Flickering on Large Element Count Draw Currently working on a personal implementation of the Boids Flocking simulation to test what I've learned about OpenGL, I've been looking to see how high I can get the # of bonds drawn upon the screen above 30 FPS.
Unfortunately I've hit a road-block with how at 2^16 and beyond boids (Where each boid is three float vertices each of size 3, where the z value is maintained to be 0) the graphical output begins to flicker with boids disappearing and reappearing upon the screen.
Interestingly this only seems to happens in the beginning stages of the app, with the flickering seemingly ending upon the boids forming their "flocks" and coincidentally clumping together visually.
I am also suspect of the number 2^16 as it matches with the GLshort bit count of 16, so potentially an overflow of the values?
Here is the area I thought was most pertinent to the issue
std::vector<float> vertices(flock.boids.size()*9, 0.f);

    unsigned int VAO, VBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0])*static_cast<uint>(vertices.size()), vertices.data(), GL_DYNAMIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    float FPS_sum = 0;
    size_t frames = 0;
    float CPS_sum = 0;
    std::chrono::high_resolution_clock::time_point start;
    // render loop
    while(!glfwWindowShouldClose(window))
    {
        processInput(window);

        //Begin CPS timer
        start = std::chrono::high_resolution_clock::now();
        //Computation Step
        std::vector<point_bucket<Boid> > tree;
        point_bucket<Boid> base(0, 0, 2, 2, flock.boids);
        base_split(base, 16, tree, 20);
        for(auto& elm: tree)
        {
            flock.Update(elm.bucket);
        }
        flock.Mirror();
        CPS_sum+=1000.f/std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()-start).count();

        // rendering commands here
        glClearColor(0.2f, 0.3f, 0.2f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shaderProgram);

        //Begin FPS timer
        start = std::chrono::high_resolution_clock::now();

        glBindVertexArray(VAO);
        updateVertices(flock.boids, window, vertices);
        updateBuffer(VBO, 0, vertices.data(), sizeof(vertices[0])*static_cast<uint>(vertices.size()), GL_ARRAY_BUFFER);
        size_t draw_running_total = vertices.size()/3;
        GLint draw_offset = 0;
        while(draw_running_total > 0)
        {
            glDrawArrays(GL_TRIANGLES, draw_offset, draw_running_total > draw_size? draw_size: draw_running_total);
            draw_running_total -= draw_size;
            draw_offset += draw_size;
        }

        // check and call events and swap the buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

        // PULL FPS FOR DRAW
        FPS_sum+=1000.f/std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()-start).count();

        frames++;
        if(frames==100)
        {
            std::cout << "Average across 100 frames... \n" << FPS_sum/frames << " FPS\n"
            << CPS_sum/frames << " CPS\n";
            FPS_sum = 0;
            CPS_sum = 0;
            frames = 0;
        }

        //END PULL FOR FPS

    }

void updateBuffer(uint &id, uint offset, void *data, uint size, GLenum shaderType)
 {
    glBindBuffer(shaderType, id);
    glBufferSubData(shaderType, offset, size, data);
}

Personally looking online myself I was able to find questions like...
https://stackoverflow.com/questions/24099139/c-opengl-flickering-issues
... which seem only to deal with extraneous buffer swapping, whereas I only swap buffers at the end of the draw loop.
A reddit post addressed a similar issue and found a potential solution in a FBO, but still couldn't discover the root cause of the problem
Any help on would be greatly appreciated!
The GitHub repo for this project is also available for those interested.


text:
Q: Jboss 4.2.3 fails to deploy Java 8 compiled MBean I am migrating a legacy code to java 8 and after changing the Spring version to 3.2.10.RELEASE and deploying it on jboss 4.2.3 I am getting:
2014-09-02 05:57:57,396 ERROR [org.jboss.deployment.MainDeployer] Could not create deployment: file:/project/SA/opt/jboss-4.2.3.GA/server/sa/deploy/sa/sa-pmt-service-1.0.4-SNAPSHOT-dev.sar
org.jboss.deployment.DeploymentException: MBean attribute 'name' must be given.
        at org.jboss.system.ServiceConfigurator.parseObjectName(ServiceConfigurator.java:783)
        at org.jboss.system.ServiceConfigurator.internalInstall(ServiceConfigurator.java:449)

It was running fine on jdk 7 compiled version. Here is jboss-service.xml
<server>
  <loader-repository>
    com.sa:loader=pmt-password-service.sar
    <loader-repository-config>java2ParentDelegation=true
    </loader-repository-config>
  </loader-repository>

  <mbean code="com.ems.services.common.ServiceInvoker" name="jmx.service.ems:name=SAS_PMTPasswordService,version=1.0"
    xmbean-dd="resource:META-INF/serviceinvoker-xmbean.xml">
    <attribute name="Service">SAS_PMTPasswordService</attribute>
  </mbean>

    <mbean code="com.sa.services.pmtsender.PmtMomService"
        xmbean-dd="resource:META-INF/serviceinvoker-xmbean.xml">
        <attribute name="Listener">pmtMessageListener</attribute>
        <attribute name="MomServiceName">pmt-service</attribute>
        <attribute name="active">true</attribute>
    </mbean>
</server>


text:
Q: Delete the [dhtml] tag On StackOverflow, we have a dhtml tag, which is quite useless. DHTML is "is an umbrella term for a collection of technologies used together to create interactive and animated web sites by using a combination of HTML, JS and CSS".
It's just a collection name for HTML + JS/CSS. That means every question tagged with dhtml has also a html tag and one/both of javascript and css, which means the tag doesn't make sense at all.

A: I would agree with aliasing dhtml to html because

*

*By the defininition of DHTML (i.e. dynamic HTML), every DHTML question is also an HTML question

*The questions that are also related to CSS and/or JavaScript should already be tagged as such.


text:
Q: Creating NSStream from dispatch_io_t How do i create a NSStream from a dispatch_io_t?
/*!
 * @typedef dispatch_io_t
 * A dispatch I/O channel represents the asynchronous I/O policy applied to a
 * file descriptor. I/O channels are first class dispatch objects and may be
 * retained and released, suspended and resumed, etc.
 */
DISPATCH_DECL(dispatch_io);


text:
Q: Send e-mail after update statement in ASPX I'm building for my project work at school a website.
The main idea is that users can report damage or report a non functioning computer.
Then the IT department can give in if they've taken any steps try fixing it and there is also a checkbox if the problem is dealth with. If the checkbox in the formview is checked and updated, there should be sent an automatic e-mail to the original user with a message that the problem is solved. I've done everything and everything works, except for the e-mail part.
Can anybody give me some advice in how I should do this? There is an unique datasource who handeles the update statement.
Yours sincerely;
A.
Here is my code:
<asp:AccessDataSource ID="accAfgehandeld" runat="server"
    DataFile="~/App_data/dbMeldingen.mdb"
    DeleteCommand="DELETE FROM [tblMeldingen] WHERE [MeldingID] = ?"
    InsertCommand="INSERT INTO [tblMeldingen] ([MeldingID], [Afgehandeld], [Categorie]) VALUES (?, ?, ?)"
    SelectCommand="SELECT [MeldingID], [Afgehandeld], [Categorie] FROM [tblMeldingen] WHERE ([MeldingID] = ?)"
    UpdateCommand="UPDATE [tblMeldingen] SET [Afgehandeld] = true, [Categorie] = ? WHERE [MeldingID] = ?"
    OnUpdated="OnDSUpdatedHandler">
    <DeleteParameters>
        <asp:Parameter Name="MeldingID" Type="Int32" />
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="MeldingID" Type="Int32" />
        <asp:Parameter Name="Afgehandeld" Type="Boolean" />
        <asp:Parameter Name="Categorie" Type="Int32" />
    </InsertParameters>
    <SelectParameters>
        <asp:QueryStringParameter Name="MeldingID" QueryStringField="id" Type="Int32" />
    </SelectParameters>
    <UpdateParameters>

        <asp:Parameter Name="Categorie" Type="Int32" />
        <asp:Parameter Name="MeldingID" Type="Int32" />
    </UpdateParameters>
</asp:AccessDataSource>

and my script in the same page:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="meldingendetails.ascx.vb" Inherits="meldingendetails" %>

<script runat="server">
private void OnDSUpdatedHandler(Object sender, e.Updated) {

   if (e.AffectedRows > 0)
    {
       MailMessage mailMessage = new MailMessage();
       SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
       smtpClient.Send(mailMessage);
   }
}
</script>

Visual studio gives an error over and over again with my script, even from the void part...

A: Set OnUpdated-handler
<asp:SqlDataSource
     ...
      UpdateCommand="..."
      OnUpdated="OnDSUpdatedHandler">
  </asp:SqlDataSource>

and use it to send email
<script runat="server">
private void OnDSUpdatedHandler(Object source, SqlDataSourceStatusEventArgs e) {

   if (e.AffectedRows > 0) {
       MailMessage mailMessage = new MailMessage();
       ...
       SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
       smtpClient.Send(mailMessage);
   }

}
</script>


text:
Q: Uncaught exception 'Zend_Config_Exception' with message 'Comments starting with '#' are deprecated I have developed a web application and deployed the same under php version 5.2.13 but when i shifted the same to server having PHP Version 5.3.6 it started to give me the error

Uncaught exception 'Zend_Config_Exception' with message 'Comments
  starting with '#' are deprecated in ...

Please suggest any workaround to run the same without downgrading the php version.

A: The clue is in the error. You can no longer comment out lines in an ini file using a hash, use a semi-colon instead. If you simply change this in whichever ini file it's complaining about the error should disappear.
Edit: Since the error is coming from Zend_Config I'm assuming it's an ini file it's complaining about. If it's a PHP script then use // to comment out the line instead.


text:
Q: How can I run a Background job with Hangfire every n minutes/hours/days I have been working recentelly with Hangfire I have created RecurringJobs,because a ReccuringJob only runs with a cron expression like:
        /// <summary>
        /// Schedule a job at a given time frequently
        /// </summary>
        /// <typeparam name="T"> Type of the function< </typeparam>
        /// <param name="jobId"> the job Id </param>
        /// <param name="methodToTrigger">he method that will be triggered at a given time</param>
        /// <param name="cronExpression">Expression that will define the frequency of trigger for the job</param>
        /// <returns></returns>
        public Task SchedulReccurentJob<T>
            (string jobId, Expression<Func<T, Task>> methodToTrigger, string cronExpression)
        {
            RecurringJob.AddOrUpdate<T>(jobId, methodToTrigger, cronExpression, TimeZoneInfo.Local);

            return Task.CompletedTask;
        }

I get the cron expressions via these expressions (they work just fine):
    /// <summary>
    /// Creates an expression for launching job every n minutes
    /// </summary>
    /// <param name="minutes"></param>
    /// <returns></returns>
    public static string EveryMinutes(int minutes)
    {
        return $"0 */{minutes} * ? * *"; // cant set minutes > 59
    }

    /// <summary>
    /// Creates an expression for launching job every n hours
    /// </summary>
    /// <param name="hours"></param>
    /// <returns></returns>
    public static string EveryHours(int hours)
    {
        return $"0 0 0/{hours} 1/1 * ? *";  // cant set hours > 23
    }

    /// <summary>
    /// Creates an expression for launching job every days at given hour and minute
    /// </summary>
    /// <param name="days"></param>
    /// <param name="hour"></param>
    /// <param name="minute"></param>
    /// <returns></returns>
    public static string EveryDaysAtHourAndMinute(int days, int hour, int minute)
    {
        return $"0 {minute} {hour} */{days} * ?"; // cant set days > 31
    }

My problem is that I want to run a specific job every given minutes , or  every given hours, or maybe every given days but with the same hour/minute.
I took a look on the cron expression it's apprentelly not possible:

Do u have any ideas ? Thanks for your help.


text:
Q: Chaging textview from another activity I have two activities
first one have two buttons
second one have one textview
what I need is
when I click on the first button the second activity open and the textview show(hello)
when I click on the second button the second activity open and the textview show(how are you)
this is the first activity layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:scrollbars="none"
tools:context=".DailyPrayersActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn1"
        style="@style/Button_Normal"
        android:background="@drawable/btn01"
        android:onClick="hello"
        android:text="@string/hello" />

    <Button
        android:id="@+id/btn2"
        style="@style/Button_Normal"
        android:background="@drawable/btn01"
        android:onClick="hru"
        android:text="@string/hru" />

</LinearLayout>

</ScrollView>

this is the java class of the first activity
package com.daily.morning;

public class FirstActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_1);
}

public void hello(View v) {
    Intent i1 = new Intent(firstActivity.this, SecondActivity.class);
    SecondActivity.textview.setText("Hello");
    startActivity(i1);
    finish();
}

public void hru(View v) {
    Intent i2 = new Intent(FirstActivity.this, SecondActivity.class);
    SecondActivity.textview.setText("good morning");
    startActivity(i2);
    finish();
}

}

when I click on the first button or the second button the application force close
this is the logcat
>>09-06 14:26:24.054: E/AndroidRuntime(30993): FATAL EXCEPTION: main
09-06 14:26:24.054: E/AndroidRuntime(30993): java.lang.IllegalStateException: Could not execute method of the activity
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.view.View$1.onClick(View.java:3699)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.view.View.performClick(View.java:4223)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.view.View$PerformClick.run(View.java:17275)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.os.Handler.handleCallback(Handler.java:615)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.os.Looper.loop(Looper.java:137)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.app.ActivityThread.main(ActivityThread.java:4898)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at java.lang.reflect.Method.invokeNative(Native Method)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at java.lang.reflect.Method.invoke(Method.java:511)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:103)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at dalvik.system.NativeStart.main(Native Method)
09-06 14:26:24.054: E/AndroidRuntime(30993): Caused by: java.lang.reflect.InvocationTargetException
09-06 14:26:24.054: E/AndroidRuntime(30993):    at java.lang.reflect.Method.invokeNative(Native Method)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at java.lang.reflect.Method.invoke(Method.java:511)
09-06 14:26:24.054: E/AndroidRuntime(30993):    at android.view.View$1.onClick(View.java:3694)
09-06 14:26:24.054: E/AndroidRuntime(30993):    ... 12 more
09-06 14:26:24.054: E/AndroidRuntime(30993): Caused by: java.lang.NullPointerException
09-06 14:26:24.054: E/AndroidRuntime(30993):    at com.daily.morning.FirstActivity.hello(FirstActivity.java:38)
09-06 14:26:24.054: E/AndroidRuntime(30993):    ... 15 more

A: you should call Activity and send data to that Activity:
Intent i2 = new Intent(FirstActivity.this, SecondActivity.class);
i2.putExtra("key","good_morning");
startActivity(i2);

And in your Second ACtivity on onCreate() method:
Intent n = getIntent();
String mrng = n.getStringExtras("key");
textview.setText(mrng);

you should put like this:
i2.putExtra("key",getResource().getString(R.string.yourstring));

Add your SecondActivity class to your AndroidManifest file:
Ans yes may be you have not initialized your textview...Or not find its id..

A: As your TextView is in another SecondActivity.Firts You need to fetch it via XML through setContentView() and findViewById(), but as FirstActivity has already it's own
 XML Layout. Fetching View is totally wrong turn.
You need to achieve your goal by pass value in a Bundle from FirstActivity to SecondActivity with some Key and fetch it there.
Here is a snipped how you can achieve these: -
 public void hello(View v)
 {
  Intent i1 = new Intent(firstActivity.this, SecondActivity.class);
  i.putExtra("KEY",YourData); // i.putExtra("greetings", "Hello"); --> Hello is data and greeting is key to fetch from.
  startActivity(i1);
  finish();
 }

In SecondActivity class
You need fetch your Bundle which you sent from FirstActivity to SecondActivity and fetch value against the same KEY which you passed on from your FirstActivity.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("KEY"); //      String value = extras.getString("greetings"); --> which will fetch data from key greetings to value. Thus value now contains Hello.
TextView.setText(value);
 }

Note: Exception Thrown in your Case as you trying to call method setText() on TextView which is not even present in FirstActivity. That's the reason why RunTime throws IllegalStateException

A: I recommend to read
Observer Patter android
Thanks this you will do what you want to do :)

A: try code something like this
FirstActivity
public void hello(View v) {
  Intent i1 = new Intent(firstActivity.this, SecondActivity.class);
  i1.putExtra("msg","Hello");
  startActivity(i1);
  finish();
}

public void hru(View v) {
  Intent i2 = new Intent(FirstActivity.this, SecondActivity.class);
  i2.putExtra("msg","How are you ?");
  startActivity(i2);
  finish();
}

And in your Second ACtivity on onCreate() method:
textview=(TextView)findViewById(R.id.textview);
Intent n = getIntent();
String mrng = n.getStringExtras("msg");
textview.setText(mrng);

get string from strings.xml
 String myString=getResources().getString("STRING_NAME");

A: In the first class you have to change your code as:
public void hello(View v) {
Intent intent = new Intent(firstActivity.this, SecondActivity.class);
intent.putextra("data","Hello");    //Pass the value to the intent for another class
finish();                          //If you want to finish your current activity
startActivity(intent);

}

public void hru(View v) {
Intent intent = new Intent(firstActivity.this, SecondActivity.class);
intent.putextra("data","How are You ?");
finish();
startActivity(intent);

}
And in the SecondActivity class
public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);

//Get the value from the intent
Intent intent = getIntent();
String Msg = intent.getStringExtras("data"); //the parameter "data" here defines the same name as you have used while passing the argument to intent in first class

//Get your textView
TextView textView=(TextView)findViewById(R.id.textView1);
textview.setText(Msg);
....

}


text:
Q: Hero View's Position Calculated Wrongly During Shared Element Transition I have two activities, Toolbars and CoordinatorLayouts in both of them.
Toolbars can be hidden by scrolling, thanks to CoordinatorLayout.
I'm trying to make a shared element transition between them and these are the steps I've taken so far:

*

*Set an image view as hero view.

*Set toolbar, navigationbar and status bar as hero too, to avoid an overlay issue.

Here is my problem:
When shared element animation starts, hero toolbar slides from up to down leading to whole screen move up to down.
Because hero imageview's position is calculated before this animation, it flashes to its final position after a move animation.
Is there a way to let animator calculate the imageview's final position correctly?
I'm not sure that I have addressed my problem sufficiently, so I can provide extra information with comments.
Sorry for long question.
Thanks in advance.


text:
Q: Yii simple relation understanding I have a problem understanding relations.
I have these tables:
Modules
- name (pk)
- status_id (fk references status(id))

Status
- id (pk)
- name

So in Module I declare relations:
public function relations()
{
  return array(
    'status'=>array( self::HAS_ONE, 'Status', 'status_id' ),
  );
}

However this doesn't work, each status is NULL.
query executed by Yii:
SELECT `t`.`name` AS `t0_c0`, `t`.`status_id` AS `t0_c1`, `t`.`session_limit` AS `t0_c2`, `status`.`id` AS `t1_c0`, `status`.`name` AS `t1_c1` FROM `ss_module` `t`  LEFT OUTER JOIN `ss_module_status` `status` ON (`status`.`id`=`t`.`name`)

+------------+-------+-------+-------+-------+
| t0_c0      | t0_c1 | t0_c2 | t1_c0 | t1_c1 |
+------------+-------+-------+-------+-------+
| digidoc    |     2 |     0 |  NULL | NULL  |
| docusearch |     1 |     2 |  NULL | NULL  |
| printbox   |     2 |     0 |  NULL | NULL  |
+------------+-------+-------+-------+-------+

I have a problem understanding if the constants apply to the relationed model or the current model, example Module HAS_ONE Status or if should be status BELONGS_TO a Module.
Note that BELONGS_TO does work, so maybe I am answering myself but I would like some advice on how to better understand relations, because in the YII Guide examples, a user HAS_ONE Profile, so isn't it the same as user HAS_ONE status?
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship
Thanks a lot.

A: You have declared the relation in both models incorrectly, then it has given the unexpected result. Currently what your code did is select all of records from parent table (Status) regardless whether it has children (Module) or not rather than versa.
While the FK was in Module, not Status, it should be
Module BELONG_TO Status
Status HAS_ONE Module (this is special case of HAS_MANY where Status has at most one Module)
I understood your confusing around, the answer that I think it would help you clear out your mind
http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/


text:
Q: Wireless freezes computer on connection to specific network I have an odd problem with a wireless network.
I have 3 Dell laptops in the house, which we'll call BlackDell, BlueDell and Dellbert.  There's also a Tosh.  We have a ClearWire hotspot modem.  All 4 machine have been accessing the hotspot for about a year.  Now, there's a problem with Dellbert.  When Dellbert connects to the ClearWire, it completely freezes within 4 minutes.  It doesn't matter if if the machine is active or idle.
BlackDell, BlueDell and Tosh connect fine (I'm using BlueDell to post this).
Dellbert can connect to any other wireless and run for days.
Dellbert generally runs Win7 64.  However, I have a Debian Squeeze install on an external drive.  If I boot into Debian, Dellbert happily connects to the network and will run for hours.
Network card is Dell 1501 (Broadcom)
All in all, I'm pretty sure that something stored or cached somewhere is corrupt, but I have no idea.  I hadn't used the machine in the house for a few months, kept it in the office, so I don't know when it may have stopped.  Loads of Windows updates in that time, so it could have been any of them.
I've deleted the network.
I've reset winsock.
I've run out of ideas.


text:
Q: What jQuery annoyances should I be aware of as a Prototype user? We're considering switching our site from Prototype to jQuery. Being all-too-familiar with Prototype, I'm well aware of the things about Prototype that I find limiting or annoying.
My question for jQuery users is: After working with jQuery for a while, what do you find frustrating? Are there things about jQuery that make you think about switching (back) to Prototype?

A: I think the only that gets me is that when I do a selection query for a single element I have to remember that it returns an array of elements even though I know there is only one.  Normally, this doesn't make any difference unless you want to interact with the element directly instead of through jQuery methods.

A: Probably the only real issue I've ever ran into is $(this) scope problems.  For example, if you're doing a nested for loop over elements and sub elements using the built in JQuery .each() function, what does $(this) refer to?  In that case it refers to the inner-most scope, as it should be, but its not always expected.
The simple solution is to just cache $(this) to a variable before drilling further into a chain:
$("li").each(function() {
    // cache this
    var list_item = $(this);
    // get all child a tags
    list_item.find("a").each(function() {
        // scope of this now relates to a tags
        $(this).hide("slow");
    });
});

A: (The only thing I can think of is that this is the element instead of a jQuery object in $("...").each(function)-calls, as $(element) is more often used then just the element. And that extremly minor thing is just about it.
Example of the above (simplified and I know that there are other much better ways to do this, I just couldn't think of a better example now):
// Make all divs that has foo=bar pink.
$("div").each(function(){
  if($(this).attr("foo") == "bar"){
    $(this).css("background", "pink");
  }
});

each is a function that takes a function as parameter, that function is called once for each matching element. In the function passed, this refers to the actual browser DOM-element, but I find that you often will want to use some jQuery function on each element, thus having to use $(this). If this had been set to what $(this) is, you'd get shorter code, and you could still access the DOM element object using this.get(0). Now I see the reason for things being as they are, namely that writing $(this) instead of this, is hardly that cumbersome, and in case you can do what you want to do with the DOM element the way it is is faster than the way it could have been, and the other way wouldn't be faster in the case you want $(this).)

A: My two pain points have been the bracket hell, can get very confusing
$('.myDiv').append($('<ul />').append($('<li />').text('content')));

My other common issue has to do with the use of JSON in jQuery, I always miss the last comma,
$('.myDiv').tabs({ option1:true, options2:false(, woops)});

Finally,  I've been using jQuery for about 6 months now and I don't think I'll ever go back to prototypes.  I absolutely love jQuery, and a lot of the tricks they use have helped me learn a lot.  one cool trick that I like is using string literals for method calls, I never really did that too much with prototypes.
$('.myDiv')[(add ? 'add' : 'remove') + 'Class']('redText');

A: I don't think there are any real gotchas, or even any lingering annoyances. The other answers here seem to confirm this - issues are caused simply by the slightly different API and different JavaScript coding style that jQuery encourages.
I started using Prototype a couple of years ago and found it a revelation. So powerful, so elegant. After a few months I tried out jQuery and discovered what power and elegance really are. I don't remember any annoyances. Now I am back working on a project using Prototype and it feels like a step back (to be fair, we're using Prototype 1.5.1).
If you reversed the question - "What Prototype annoyances should I be aware of as a jQuery user?" - you would get a lot more answers.

A: Nope. Nada. Nyet.

A: .each:
jQuery (you need Index, even if you're not using it):
$.each(collection, function(index, item) {
  item.hide();
});

Prototype (you're usually using the item, so you can omit the index):
collection.each(function(item) {
  item.hide();
});

A: This is really only an annoyance if you're doing a lot of DOM manipulation. PrototypeJs automatically adds its API to DOM Elements, so this works in prototypejs (jQuery of course doesn't do this):
var el = document.createElement("div");
el.addClassName("hello"); // addClassName is a prototypejs method implemented on the native HTMLElement

Even without running the native element through the $() function.
PS: Should note that this doesn't work in IE.


text:
Q: Reading InputStream from java.net.Socket sometimes blocks Below is my method where I pass in as a parameter java.net.Socket:getInputStream().
This works perfectly well at almost all times.
Problem occurs when input stream from the socket is a big chunk of empty bytes (ambiguous data). This makes my program to stop responding altogether. Does anyone know what's going on? Should I not get IOException or something rather than just stop responding? How can I just quit the read if e.g. data is some useless ambiguous information.
public static String fromStream(InputStream in) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
    }
    return out.toString();
}

A: If the stream contains '00' bytes, it's probably wrong to read the data using readLine(). You should read bytes instead.

A: The $64,000 question is what is this "meaningless ambiguous data"?
If it is truly meaningless, then you should really be focussing on why it is being sent.  The chances are that it is caused by a bug in the application that is sending the data.  Find and fix that, and you don't need to change your client code.
On the other hand, it could be meaningful data ... but you / your application don't know what it means.  In that case, the root problem is that the file is not a text file, and it is therefore incorrect to read it using a Reader / BufferedReader.
If you want to persist with trying to read this data as text ... in such a way that the zero bytes / characters don't cause you grief, then you need to read from the BufferedReader one character at a time.  When you encounter a zero character (or bad ones) your character reading code can bail out.  Otherwise, assemble the non-bad characters into lines if that is what you actually need.

There are a couple of things to note from your comment:

I was basically just expecting normal response e.g. including 200 i.e. OK from the HTTP server, where in this exceptional case I get these zero bytes and nothing else at all.

Firstly, it sounds like you might be trying to interact with an HTTP server using plain sockets.  This is a bad idea.  A really bad idea!  The chances are that you plain socket code will not be able to correctly interpret the various different ways that a kosher HTTP server could send a response.  (And that would explain the following ...)
Secondly, an HTTP response includes a "Content-type" that gives you the media type of stuff in the response body.  If your client ignores the Content-type header, you risk processing the response body the wrong way.  For instance, you might get a PDF file or a TAR file which could certainly contain large numbers of zero bytes.
On the other hand, you could be doing these things the right way, and the HTTP server could just be broken.


text:
Q: Error while compiling in matlab I got the following error while running

source.vid = videoinput('winvideo', 1,'YUY2_320x240');
Undefined function or variable 'videoinput'.

How to resolve it?

A: Your matlab installation is missing "Image Acquisition toolbox".Install it and run the code again


text:
Q: Why am I not accelerated by the reaction force applied by Earth on me? Newton's third law says that "to every action, there is always an equal but opposite reaction". And Newton's second law of motion says that, $F=ma$ $=>$ $a=\frac{F}{m}$. People says that If I stand on earth's surface, I am applying a force on earth which is equal to my weight and Earth, in return, is applying force to me which is equal in magnitude to my weight but opposite in direction. I know that these forces will not cancel each other out since they are applied on different bodies and not a single but I ask if net force is not zero then according to the equation, $a=\frac{F}{m}$, I must have some acceleration produced in my body. Because the equation is telling us that the force applied on me is same as my force applied to earth but since masses are different and acceleration is inversely proportional to the mass then I must experience some acceleration as my mass is lesser than earth and so acceleration produced must be greater.

A: In the framework of General Relativity, where the inertial frames are the ones in free fall, you can think that the Earth is accelerating upward, so it is not you who is pushing on Earth but it is Earth that is "running you over" because of its accelerated motion. Luckily enough, if we are standing on ground, we can avoid impulsive forces and our bodies are capable of sustaining a constant acceleration equal to $g$. The fact that we then cannot penetrate Earth as it accelerates upward is because the ground is pushing us up with a force equal to our bodies inertia.
So to make this a bit clearer, flies which are standing on the windscreen of an accelerating car will be squeezed against the windscreen like they have gained extra weight (the impulsive forces are those that would splatter any fly that wasn't already on the windscreen and that happens to smash against it because the car is moving towards them). Here we're focussing on the extra weight from acceleration alone, not on wind resistance.

A:
Why am I not accelerated by the reaction force applied by earth on me?

Because the net force on your centre of mass is zero.
The upward force on your feet is of the same magnitude as the downward force of gravity.
Your major leg bones and spine are in compression because of the opposing forces.

I know that these forces will not cancel each other out since they are applied on different bodies and not a single

You are mistaken. The planet's gravity acts on your body. The reaction force from the ground also acts on your body.

masses are different

Yes your body exerts an attractive gravitational force on the planet and your feet apply an opposite repulsive force to the planet.
However if your reference frame is the planet's local surface  and the planetary mass is many orders of magnitude greater than yours, you can ignore your effects on the planet as a whole.

A: I think it helps if you look at the problem from more of an intuitive perspective.
When you're standing still on Earth, you're clearly not accelerating, right? (In this example we are ignoring the energy and force exerted by the molecules in our body, which are all moving to some extent regardless of where we are.)
If you were accelerating, you'd see some change in velocity over time, which you clearly don't when you're still. We can say, then, that the net forces of you and gravity are pretty much zero. They are no longer zero, for example, when you jump, or run, etc.
However, you have to keep in mind that this is all from your own perspective (I think that's why one can bring up general relativity as a good talking point here) and the perspective of anyone on Earth looking at you. There are some theories that the Earth is moving really fast in a straight line (like a car, or bullet, or some other projectile) and humans are just "in the way" of that movement, and thus we feel the effect of this thing we call gravity (similar to a person inside an elevator going up; when you're in an elevator, you go up because you're accelerating with the elevator). If this is the case, then both humans and Earth are accelerating relative to everything else, but humans at a stand still are not accelerating relative to the Earth. This also confirms the notion that acceleration is always relative between two independent objects.

A:
I know that these forces will not cancel each other out since they are applied on different bodies and not a single ...

That's correct.

... but I ask if net force is not zero then according to the equation, a=Fm, I must have some acceleration produced in my body.

First off, it's $F=ma$ (or equivalently, $a=F/m$), not $a=Fm$.
One thing you are missing is that Newton's second and third law address different concepts. Newton's second law talks about how the acceleration of object is related to the net force exerted on that object by other objects. Newton's third law talks about the individual force (not net force) exerted by one object on another is related to the  different objects exert on one another.
In particular, Newton's second law says $\boldsymbol F_\text{net} = m\,\boldsymbol a$ while Newton's third law says $\boldsymbol F_{a,b;i} = - \boldsymbol F_{b,a;i}$, where $\boldsymbol F_{a,b;i}$ is the force exerted on body $a$ by body $b$ via interaction $i$. The $\boldsymbol F_\text{net}$ in Newton's second law is the sum of all of the individual forces acting on the body.
Another thing you are missing is that other forces act on you other than gravitation when you are standing on the ground. Suppose you stand on your chair and jump off. For a brief period of time between the jump and the landing, you are accelerating. The difference is that you have removed the upward force exerted on you by the ground. This is a different force than gravitation. It is the "normal force". It's what keeps you from sinking into the floor.
To go from Newton's third law to Newton's second law, you have to consider all of the forces acting on an object. This is why students are taught to draw free body diagrams. Forces are vector quantities. That means they add, in the vector sense of addition.
While Newton didn't use vectors (he couldn't have because the concept of a "vector" postdates Newton by 200 years), he did make the distinction between individual forces and net forces in his corollaries to his three laws of motion. Some physics even instructors go to the extent of teaching the vectorial nature of forces as Newton's fourth law.

Why am I not accelerated by the reaction force applied by Earth on me?

Truth be told, you are accelerated by the reaction forces applied by the Earth on you. The Earth is rotating, one revolution per day. Unless you are at the North Pole or South Pole, you are undergoing uniform circular motion about the Earth's rotation axis. The downward force gravitational force the Earth as a whole exerts on you and the upward normal force the Earth's surface exerts on you do not quite cancel. There's a tiny residual non-zero net force that is just enough to make you rotate about the Earth's rotation axis at one revolution per day.

A: To you, lets apply the second law. As it states, actually
$\sum F=m a$
NOTE THE SUMMATION, which means the resultant force applied. If you're just sitting or not moving, both normal force and gravity exerted in opposite direction, for its magnitude, they equals.
You're still having problem with how will the Earth move ha?
The third law tells, You give the earth some very small force (equal to your weight though), and as the earth exerts normal force on you, you're pushing the Earth also with the equal force (firstly equal to the normal force, and normal force equal to your weight). So If there's only you on the earth, the gravity from you and the normal force you exert on earth is in opposite direction and same magnitude, the Earth don't move either.


text:
Q: WebStorm expecting multiple arguments for $.insertBefore()? I have the following code which is currently working as desired.  It inserts elements into objGrid according to the property loadOrder.
let $elTileTitle = $('<div/>', { class: 'tileTitle', html: tile.title });

let $elNext;
for (let i = tile.loadOrder; i < objectLength(tiles); i++) {
    let $potentialNext = $(`.tile[data-loadorder="${i}"]`);
    if ($potentialNext.length > 0) {
        $elNext = $potentialNext;
        break;
    }
}
if (typeof $elNext !== 'undefined') {
    $elTile.insertBefore($elNext);
} else {
    let $elPrev;
    for (let i = tile.loadOrder; i < 0; i--) {
        let $potentialPrev = $(`.tile[data-loadorder="${i}"]`);
        if ($potentialPrev.length > 0) {
            $elPrev = $potentialPrev;
            break;
        }
    }
    if (typeof $elPrev !== 'undefined') {
        $elTile.insertAfter($elPrev);
    } else {
        $elTile.appendTo(objGrid);
    }
}

As stated, this seems to work well.  But I noticed a warning in my IDE that insertBefore() had an invalid number of arguments.  After viewing the documentation, I replaced that line with this:
$('#grid').insertBefore($elTile,$elNext);

This has presented odd behavior.  After this code runs, $('#grid') is empty.  Oddly, all the tiles exist in the DOM (ie, if I type $('#tile-store') in the console, I get an object back with all the expected properties), however I cannot find them in the HTML ("Elements" tab) and the UI is blank.
Is there something obvious I'm doing wrong? I can provide more information if needed

A:
But I noticed a warning in my IDE that insertBefore() had an invalid number of arguments.

Your IDE is mistaken. It's mistakenly applying the rules for the DOM's insertBefore to your use of jQuery's insertBefore. Your original use of jQuery's is just fine. If you were using the DOM's, you'd need to give it another argument. But they're completely different functions.


text:
Q: Add new VISA network device to resources I'm setting up a test environment including several instruments connected via LAN(TCP/IP) or USB. A Software shall be written in C# using the Ivi.Visa library. The instruments (which will change over time) get their IP address from a DHCP server so they won't show up in the Resources discovered byIVI.Visa.interop.ResourceManager.FindRsrc() unless they've been previously added by the Keysight Connection manager Software (or equivalent NI tool).
ResourceManager rMgr = new ResourceManager();
 string[] enumRcrs = rMgr.FindRsrc("?*INSTR");
How does one achieve to discover new VISA Network devices in C# and add them to the resources list without having to use the external software before?

A: Modern instruments may support discovery via mDNS (see LXI specification here). I'm not familiar with Ivi.Visa library, but you may want to look over its documentation for instrument discovery feature. If it is not supported then you can probably implement mDNS request in your C# code.


text:
Q: java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface Created a remote EJB project and deployed in the IBM websphere server as Jar.
Now, i created a EJB Client project in my local and trying to connected as Remote call.
but it is throwing an exception: java.lang.ClassCastException
client Program:
package ejb3.test;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class TestEJBClient {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties props = new Properties();

    props.put(javax.naming.Context.PROVIDER_URL, "iiop://(ip of remote ejb server):2809");

    ITestEJBRemoteInterface loEJB = null;
    Object lobj;

    try {

        InitialContext ctx = new InitialContext(props);
        System.out.println(ctx.getEnvironment());
        lobj = ctx.lookup("ejb3/test/ITestEJBRemoteInterface");// look up of corba
        System.out.println("--------" + lobj);

        loEJB = (ITestEJBRemoteInterface)     PortableRemoteObject.narrow((org.omg.CORBA.Object) lobj, ITestEJBRemoteInterface.class);
        String lsName = "Kevin";
        // Invoke the Method using bean object ;
        System.out.println("Is " + lsName + " present in the list:: " + loEJB.checkNames(lsName));
        System.out.println("EJB run successful");
    }
    catch (NamingException e) {
        e.printStackTrace();
    }

    }
}

exception:
{com.ibm.websphere.naming.hostname.normalizer=com.ibm.ws.naming.util.DefaultHostnameNormalizer, java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory, com.ibm.websphere.naming.name.syntax=jndi, com.ibm.websphere.naming.namespace.connection=lazy, com.ibm.ws.naming.ldap.ldapinitctxfactory=com.sun.jndi.ldap.LdapCtxFactory, com.ibm.websphere.naming.jndicache.cacheobject=populated, com.ibm.websphere.naming.namespaceroot=defaultroot, com.ibm.ws.naming.wsn.factory.initial=com.ibm.ws.naming.util.WsnInitCtxFactory, com.ibm.websphere.naming.jndicache.maxcachelife=0, com.ibm.websphere.naming.jndicache.maxentrylife=0, com.ibm.ws.naming.wsn.localonly=false, com.ibm.websphere.naming.jndicache.cachename=providerURL, java.naming.provider.url=iiop://10.176.106.207:2809, java.naming.factory.url.pkgs=com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming}
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
INFO: Client code attempting to load security configuration
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.LoadSCI
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.GettingConfig
Feb 18, 2016 7:39:53 PM null null
WARNING: ssl.default.password.in.use.CWPKI0041W
Feb 18, 2016 7:39:53 PM null null
INFO: ssl.disable.url.hostname.verification.CWPKI0027I
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.AuthTarget
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.ClientCSI
--------com.ibm.WsnOptimizedNaming._NamingContextStub:IOR:00bdbdbd0000003149444c3a636f6d2e69626d2f57736e4f7074696d697a65644e616d696e672f4e616d696e67436f6e746578743a312e3000bdbdbd0000000100000000000000f4000102bd0000000a6c6f63616c686f737400238c0000006b4a4d4249000000124773e3aa37643062633737336533616166633334000000240000004749454a500200f76a838007736572766572311a57736e44697374436f734f626a65637441646170746572574c4d00000016434c45564449434d2d3134334e6f6465303143656c6cbd00000007000000010000001400bdbdbd0501000100000000000101000000000049424d0a0000000800bd00011600000100000026000000020002bdbd49424d04000000050005020102bdbdbd0000001f0000000400bd0003000000200000000400bd0001000000250000000400bd0003
Exception in thread "P=592906:O=0:CT" java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface ejb3.test.ITestEJBRemoteInterface
    at com.ibm.rmi.javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:396)
    at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:148)
    at ejb3.test.TestEJBClient.main(TestEJBClient.java:38)

How could i resolve that error?
Can any one please share your thoughts.

A: ClassCastException - if narrowFrom cannot be cast to narrowTo.

Seems that corba.object and itestejbrremoteinterface are not related by inheritance

A: The relevant lines from the dumpNameSpace are:
  168 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb3.test.ITestEJBRemoteInterface
  168                                                    ejb3.test.ITestEJBRemoteInterface

  192 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface
  192                                                    ejb3.test.ITestEJBRemoteInterface

The root of the server context is (top)/nodes/CLEVDICM-143Node01/servers/server1/, which means you should use one of these strings:

*

*ejb3.test.ITestEJBRemoteInterface

*ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface


text:
Q: Visual Studio 2008 Installer, Custom Action. Breakpoint not firing I've got an installer with a custom action project.
I want the action to fire at install.
The action fires, when I write something to the event log, it works perfectly.
But I really need to debug the file since the action is quite complicated.
So I've got the following installer class:
namespace InstallerActions
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.Diagnostics;
    using System.IO;

    [RunInstaller(true)]
// ReSharper disable UnusedMember.Global
    public partial class DatabaseInstallerAction : Installer
// ReSharper restore UnusedMember.Global
    {
        public DatabaseInstallerAction()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            System.Diagnostics.Debugger.Launch();
            System.Diagnostics.Debugger.Break();

                        // none of these work

            Foo();
        }
        private static void Foo()
        {

        }
    }
}

The installer just finalizes without warning me, it doesn't break, it doesn't ask me to attach a debugger.
I've tried debug and release mode. Am I missing something?
Thanks
-Snake

A: The solution is to fire base.Install as last. Apparently the code after base.Install is NOT executed.


text:
Q: Could not determine artifacts for com.facebook.fresco:fresco:0.11.0: Skipped due to earlier error I'm currently getting this android build issue for react native and I didn't upgraded any libraries or anything.

* What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.
> Could not resolve all dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not determine artifacts for com.facebook.fresco:fresco:0.11.0: Skipped due to earlier error

I tried it by applying
implementation 'com.facebook.fresco:fresco:2.6.0'

in app/build.gradle. But that also not worked.


text:
Q: Secure user token between SPA HTML5 app and web service? Sorry if this has been asked a few times, but can't quite find out a solid response.
I want to secure the login procedure and session (kind of) between an HTML5 app and a PHP web service. I present the user with a login screen that uses HTTPS with the server, and then give the client a random GUID that is stored in a database with their time of login and last request time, and their actual user ID that I store for their row on a users table. So the GUID might be different every time but the user ID it maps to on login can only be seen server side.
I'm vary weary when it comes to authentication and never really dealt with a HTML5/JS app against a web service like this. I've usually developed ASP .NET sites and used sessions.
I've recently discovered JWT tokens which encrypts data stores in the token string that is contained on the client and passed to/from the server. Is this safer than what I'm doing? Should I be using JWT as opposed to this GUID mapping I have now?
What I'm aiming for is a session-less request to a web farm which could put you on to any specific web server, and the request is validated to see if that request has came from a valid logged in user.
Any advice would be welcome :).
Thanks.

A: Using a JWT token is totally safe provided you don't encode sensitive data in the token because the token can be decoded without the secret.
What you can do is to have two key pairs (private/public) RSA keys.
Private for encoding the token and sending it to the client on login success
the client saves the token to maybe a cookie, HTML5 localstorage e.t.c,
on every request, the client passes the token via the request header back to the web server, then the web server verifies the token with the public key. whilst decoding the token and getting the GUID from the token and can then proceed with the request.
This workflow can work across several server side languages as there are many JWT libraries for them.


text:
Q: Strings shortened when using UNION in Teradata SQL Assistant When I perform a UNION between 2 tables, the strings are automatically shortened. I get "30 Days Active Su" and "120 Days Active S". When I run the query individually, without any UNION, I get the full form "30 Days Active Subs" and "120 Days Active Subs", which I require. Why is this so and how to go about correcting it?
Following is the code:
SELECT
'30 Days Active Subs' AS PROPERTY
,(DISTINCT SUBS.SUBSCRIBER_COUNT) AS SUBS_COUNT
FROM PMP_AVEW.FCT_SUBS_DLY_SNAP AS SUBS
WHERE SUBS.DAYS=30
GROUP BY 1

UNION

SELECT
'120 Days Active Subs' AS PROPERTY
,(DISTINCT SUBS.SUBSCRIBER_COUNT) AS SUBS_COUNT
FROM PMP_AVEW.FCT_SUBS_DLY_SNAP AS SUBS
WHERE SUBS.DAYS=120

A: you need to cast this column.
SELECT
CAST('30 Days Active Subs' AS varchar(255)) AS PROPERTY
,(DISTINCT SUBS.SUBSCRIBER_COUNT) AS "30_DAYS_SUBS"
FROM PMP_AVEW.FCT_SUBS_DLY_SNAP AS SUBS
WHERE SUBS.DAYS=30
GROUP BY 1

UNION

SELECT
'120 Days Active Subs' AS PROPERTY
,(DISTINCT SUBS.SUBSCRIBER_COUNT) AS "120_DAYS_SUBS"
FROM PMP_AVEW.FCT_SUBS_DLY_SNAP AS SUBS
WHERE SUBS.DAYS=120

or you can use fixed length
 CAST('30 Days Active Subs' AS CHARACTER(20))


text:
Q: How to best visualize one-sample test? We are currently writing a paper with several one-sample Wilcoxon tests. While visualizing two-sample tests is easy via boxplots, I was wondering whether there is any good way to visualize one-sample test results?
# Example data
pd <- c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
        0.73, 1.46, 1.15, 0.88, 0.90, 0.74, 1.21)

wilcox.test(pd, mu = 1.1)

#   Wilcoxon signed rank test
#
# data:  pd
# V = 72, p-value = 0.5245
# alternative hypothesis: true location is not equal to 1.1

...and also:
I would like to get Z-value instead of V-value. I know that if I use coin package instead of basic stats I will have z-values, but coin package
seems not to be able perform one-sample Wilcoxon test.

A: Something like this?

Or were you after some interval for the median, like you get with notched boxplots (but suited to a one sample comparison, naturally)?
Here's an example of that:

This uses the interval suggested in McGill et al (the one in the references of ?boxplot.stats). One could actually use notches, but that might increase the chance that it is interpreted instead as an ordinary notched boxplot.
Of course if you need something to more directly replicate the signed rank test, various things can be constructed that do that, which could even include the interval for the pseudo-median (i.e. the one-sample Hodges-Lehmann location estimate, the median of pairwise averages).
Indeed, wilcox.test can generate the necessary information for us, so this is straightforward:
> wilcox.test(pd,mu=1.1,conf.int=TRUE)

    Wilcoxon signed rank test

data:  pd
V = 72, p-value = 0.5245
alternative hypothesis: true location is not equal to 1.1
95 percent confidence interval:
 0.94 1.42
sample estimates:
(pseudo)median
        1.1775

and this can be plotted also:

[The reason the boxplot interval is wider is that the standard error of a median at the normal (which is the assumption underlying the calculation based off the IQR) tends to be larger than that for a pseudomedian when the data are reasonably normalish.]
And of course, one might want to add the actual data to the plot:

Z-value
R uses the sum of the positive ranks as its test statistic (this is not the same statistic as discussed on the Wikipedia page on the test).
Hollander and Wolfe give the mean of the statistic as $n(n+1)/4$ and the variance as $n(n+1)(2n+1)/24$.
So for your data, this is a mean of 60 and a standard deviation of 17.61 and a z-value of 0.682  (ignoring continuity correction)

The code I used to generate the fourth plot (from which the earlier ones can also be done by omitting unneeded parts) is a bit rough (it's mostly specific to the question, rather than being a general plotting function), but I figured someone might want it:
notch1len <- function(x) {
  stats <- stats::fivenum(x, na.rm = TRUE)
  iqr <- diff(stats[c(2, 4)])
  (1.96*1.253/1.35)*(iqr/sqrt(sum(!is.na(x))))
}

w <- notch1len(pd)
m <- median(pd)

boxplot(pd,horizontal=TRUE,boxwex=.4)

abline(v=1.1,col=8)
points(c(m-w,m+w),c(1,1),col=2,lwd=6,pch="|")

ci=wilcox.test(pd,mu=1.1,conf.int=TRUE)$conf.int                       #$
est=wilcox.test(pd,mu=1.1,conf.int=TRUE)$estimate

stripchart(pd,pch=16,add=TRUE,at=0.7,cex=.7,method="jitter",col=8)

points(c(ci,est),c(0.7,0.7,0.7),pch="|",col=4,cex=c(.9,.9,1.5))
lines(ci,c(0.7,0.7),col=4)

I may come back and post more functional code later.

A: If you like boxplots, you can as readily show a single boxplot with a line or other reference showing your hypothesised value. (@Glen_b posted an answer with an excellent simple example precisely as I was first writing this.)
It is arguable that boxplots, now very popular, are massively overused for one-sample and two-sample exploration. (Their real value, in my view, is when you are comparing many sets of values, with number of samples or groups or variables more like 10, 30 or 100, and there is a major need to see overall patterns amid a mass of possible detail.)
The key point is that with just one or two samples (groups, variables), you have space on a plot to show much more detail, detail that could be interesting or important for comparison. With a good design, such detail need not be distracting in visual comparison.
Evidently, in most usual versions the box plot suppresses all detail in its box, showing the middle half of the data, except in so far as the position of the median inside the box conveys some information. Depending on the exact rules used, such as the 1.5 IQR convention of showing data points individually if and only if they are 1.5 IQR or more from the nearer quartile, it is even possible that the box plot suppresses most of the detail about the other half of the data. Often, and perhaps even usually, such detail may be irrelevant to something like a Wilcoxon test, but being prepared to see something illuminating in the data display is always a good idea.
A display that remains drastically underused in many fields is the quantile plot, a display of the ordered values against an associated cumulative probability. (For other slightly technical reasons, this cumulative probability is typically not $1/n, \cdots, n/n$ for sample size $n$ but something like $(i - 0.5)/n$ for rank $i$, 1 being the rank of the smallest value.)
Here are your example data with a reference line added for 1.1.

In other examples, key points include

*

*For two-sample comparisons, there are easy choices between superimposing traces, juxtaposing traces, or using related plots such as quantile-quantile plots.

*The plot performs well over a range of sample sizes.

*Outliers, granularity (lots of ties), gaps, bi- or multimodality will all be shown as or much more clearly than in box plots.

*Quantile plots mesh well with monotonic transformations, which is not so true for box plots.
Some will want to point out that cumulative distribution plots or survival function plots show the same information, and that's fine by me.
See W.S. Cleveland's books (details at http://store.hobart.com/) for restrained but effective advocacy of quantile plots.
Another very useful plot is the dot or strip plot (which goes under many other names too), but I wanted to blow a small trumpet for quantile plots here.
R details I leave for others. I am focusing here on the more general statistical graphics question, which clearly cuts across statistical science and all software possibilities.
Incidentally, I don't know the background story but the name wilcox.test in R seems a poor choice to me. So, you save on typing two characters, but the name encourages confusion, not least because of past and present people in statistical fields called Wilcox. Lack of justice for Mann and Whitney is another detail. The person being honoured was Wilcoxon.


text:
Q: Mnemonic Generation Using LSTM's | How do I make sure my Model Generates Meaningful Sentence Using a Loss Function? I'm working on project that generates mnemonics. I have a problem with my Model.
My question is ,How do I make sure my Model Generates Meaningful Sentence Using a Loss Function?
Aim of the project
To generate Mnemonics for a list of words. Given a list of words user wants to remember, the model will Output a meaningful, simple and easy to remember sentence which encapsulates the one-two first letters of the words that the user wants to remember in the words of Mnemonic to be generated. My model will receive only the first two letters of the words the user wants to remember as that is it carries all the information for the mnemonic to be generated.

Dataset
I'm Using Kaggle's 55000+ song lyrics data and the sentences in those lyrics contain 5 to 10 words and Mnemonic I want to generate also contain the same number of words.
Input/Output Preprocessing.
I am iterating through all the sentences after removing punctuation and numbers and extracting first 2 letters from each word in a sentence and assigning a unique number to those pair of letters from a predefined dictionary which contains pairs of keys a key and a unique number as value.
List of these unique number assigned while act as input and Glove vectors of those words will act as the output. At each time step LSTM model will take these unique numbers assigned to these words and will output the corresponding word's GloVe vector.

Model Architecture
I'm using LSTM's with 10 time steps.
At each time step the unique number associated with the pair of letters will be fed and the output will be the GloVe vector of the corresponding word.

optimizer=rmsprop(lr=0.0008)
model=Sequential()
model.add(Embedding(input_dim=733,output_dim=40,input_length=12))
model.add(Bidirectional(LSTM(250,return_sequences=True,activation='relu'),merge_mode='concat'))
Dropout(0.4)

model.add(Bidirectional(LSTM(350,return_sequences=True,activation='relu'),merge_mode='concat'))
Dropout(0.4)
model.add(TimeDistributed(Dense(332, activation='tanh')))
model.compile(loss='cosine_proximity',optimizer=optimizer,metrics=['acc'])

Results:
My model is outputting Mnemonics which match the first two letters of each word in the input. But the mnemonic generated carries little to no meaning.
I have realized this problem is caused because of the way I'm training. The order of letter extracts from words is already ready for sentence formation. But this is not the same in case of while testing. The order with which I'm feeding the letter extracts of words may not have a high probability of sentence formation.
So I built a bigram for my data and feed that permutation that had the highest probability of sentence formation into my mnemonic generator model. Though there were some improvements, the sentence as a whole didn't make any sense.
I'm stuck at this point.
Input

Output

My question is,
How do I make sure my Model Generates Meaningful Sentence? Using a Loss Function

A: First, I have a couple of unrelated suggestions. I do not think you should output the GLoVe vector of each word. Why? Word2Vec approaches are meant to encapsulate word meanings and would probably not contain information about their spelling. However, the meaning is also helpful in order to produce a meaningful sentence. Thus, I would instead have the LSTM produce it's own hidden state after reading the first two letters of each word (just as you currently do). I would then have that sequence be unrolled (as you currently do) into sequences of dimension one (indexes into a index to word map). I would then take that output, process it through an embedding layer that maps the word indexes to their GLoVe embeddings, and I would run that through another output LSTM to produce more indexes. You can stack this as much as you want - but 2 or 3 levels will probably be good enough.
Even with these changes, it is unlikely you will see any success in generating easy-to-remember sentences. For that main issue, I think there are generally two ways you can go. The first is to augment your loss with some sense that the resulting sentence being a 'valid English sentence'. You can do this with some accuracy programtically by POS tagging the output sentence and adding loss relative to whether it follows a standard sentence structure (subject predicate adverbs direct-objects, etc). Though this result might be easier than the following alternative, It might not yield actually natural results.
I would recommend, in addition to training your model in it's current fashion, to use a GAN to judge if the output sentences are natural sentences. There are many resources of Keras GANs, so I do not think you need specific code in this answer. However, here is an outline of how your model should train logically:

*

*Augment your current training with two additional phases.

*

*first train the discriminator to judge whether or not the output sentence is natural. You can do this by having an LSTM model read sentences and giving a sigmoid output (0/1) to whether or not they are 'natural'. You can then train this model on some dataset of real sentences with 1 labels and your sentences with 0 labels at roughly a 50/50 split.

*Then, in addition to the current loss function for actually generating the Mnemonics, add the loss that is the binary cross-entropy score for your generated sentences with 1 (true) labels. Be sure to obviously freeze the discriminator model while doing this.

Continue iterating over these two steps (training each for 1 epoch at a time) until you start to see more reasonable results. You may need to play with how much each loss term is weighted in the generator (your model) in order to get the correct trade-off between a correct mnemonic and an easy-to-remember sentence.


text:
Q: Set route name for POST, GET PUT, PATCH, Rails 5 I am using Devise and change its default routes like this:
devise_for :users, :path => '',skip: [:sessions]

as :user do
    get '/forgotten' => 'users/passwords#new', as: :password
    post '/forgotten' => 'users/passwords#create'
    put '/forgotten' => 'users/passwords#update'
    get '/password/edit' => 'users/passwords#edit'
end

The generated URL (form action attribute) for new.html.erb (view for sending email with new password instructions) is /forgotten.user, which is not correct. The correct URL is /forgotten and it is used with different HTTP verbs GET/POST/PUT.
 In request new password form (new.html.erb):
<%= form_for(resource, as: resource_name,
             url: password_path(resource_name), html: { method: :post})

Without my custom routes with rake routes, I see for these routes:

user_password | PATCH  |  /password(.:format)       | users/passwords#update
PUT | /password(.:format)  |             users/passwords#update
POST |     /password(.:format) | users/passwords#create

How to make this route custom and used for different HTTP verbs ?

A: Try to delete as :user do
get '/forgotten' => 'users/passwords#new', as: :password
post '/forgotten' => 'users/passwords#create'
put '/forgotten' => 'users/passwords#update'
get '/password/edit' => 'users/passwords#edit'

If you need to url be like /user/forgotten use scope 'user' do


text:
Q: how many custom attributes type in magento $setup->addAttribute('catalog_category', 'image1', array(
'input'         => 'image',
'type'          => 'varchar',
'group' => 'Slider Image',
'label'         => 'Image 1',
'visible'       => 1,
'required'      => 0,
'user_defined' => 1,
'backend'  => 'catalog/category_attribute_backend_image',
'frontend_input' =>'',
'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible_on_front'  => 1,
));

how many input type for custom attribute like text,textarea
'input' => 'text',

can we add button as custom attribute and set action on it

A: There are some issue in your installer please try below
$installer->addAttribute("catalog_category", "image1",  array(
    "type"     => "varchar",
    "backend"  => "catalog/category_attribute_backend_image",
    "frontend" => "",
    "label"    => "Image one",
    "input"    => "image",
    "class"    => "",
    "source"   => "",
    "global"   => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    "visible"  => true,
    "required" => false,
    "user_defined"  => false,
    "default" => "Image",
    "searchable" => false,
    "filterable" => false,
    "comparable" => false,
    'group' => 'Slider Image',

    "visible_on_front"  => true,
    "unique"     => false,
    "note"       => ""

    ));


text:
Q: How to grab one random item from a database in Django/postgreSQL? So i got the database.objects.all() and database.objects.get('name') but how would i got about getting one random item from the database. I'm having trouble trying to figure out how to get it ot select one random item.

A: Aamir's solution will select all objects before discarding all but one. This is extremely wasteful and, besides, this sort of calculation should be done in the database.
model.objects.all().order_by('?')[0]

Read more here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
Edit: lazerscience's answer is indeed faster, as shown here.

A: Selecting a random element from a list of all database objects isn't a goog solution as retrieving all elements of the database can have a big impact on performance, neither is using    order_by('?') as mentioned in the django documentation.
The best solution should be to retrieve an element with a random index:
import random

random_idx = random.randint(0, Model.objects.count() - 1)
random_obj = Model.objects.all()[random_idx]

A: I would do it slightly different. Querysets are lazy anyway in django.
import random

def get_my_random_object():
    object = random.choice(model.objects.all())
    return object

https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy
https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated


text:
Q: Python3 - Have a list with elements inside with `b` and `\n` characters, such as "b"5.1. Please try\n5.1.1". Is there an easy way to decode/fix this? In python3, I currently have a list with elements of the list being like:
'b"5.1. Please try\n5.1.1 the recipient's email address or\n5.1.1 unnecessary spaces. Learn more at\n5.1.1  https://support.google.com/mail/?p=NoSuchUser 1-v6si3763255qtb.106 - gsmtp"'

There appears to be a byte element in the front and sproadically I see \n's everywhere.
Is there a way to make this clean text? Would it require a function that goes into each element like this of my list or is there a function that can be applied to a list without looping? Thanks!

A: Try this on your list:
[e[2:-2].replace("\n",' ') for e in yourlist]

A: Looks like you somehow got the repr of a bytestring inside a string. It would be best to figure out the root cause of where that happened, otherwise you can clean it up with regex.
import re
re.sub(r'\n', ' ', re.sub(r'^b"(.*)"$', r'\1', dirty_string))


text:
Q: How to install wso2 products on pure wso2 carbon My requirement is need to install (ESB,Application Server,Data Service Server,Api Manager,BAM) on pure wso2 carbon 4.2.0.
Is it possible to install all these products on Carbon?
I want to install multiple products on same carbon instance . I downloaded the P2_REPO from this site http://wso2.com/projects/carbon/provisioning-wso2-carbon-with-equinox-p2 and tried feature installation using UI,but it is not allowing me.
Can anyone tell me the best possible way to do this. I want multiple products on same carbon
Your soon reply will be highly appreciated

A: This can be easily install features through UI following this documentation, https://docs.wso2.org/display/Carbon420/Installing+Features+via+the+UI
It will be easy for you to go by product by product rather than selecting all feature group at once.

A: *

*Download wso2 manually in direct wso website either deb or rpm package

a)check command: whereis wso2
b) move wso2 folder to /opt directory

*/opt/wso2/wso2am/2.6.0/repository/conf/api-manager.xml
a)check and add the domain in gatewayendpoint
b)https://xxxxxxxxxx
  disable comment line     below

 http://${carbon.local.ip}:${http.nio.port},https://${carbon.local.ip}:${https.nio.port}-->

*/opt/wso2/wso2am/2.6.0/repository/conf/carbon.xml
a) Add below line hostname
uncomment www.wso2.org
xxxxxxx
xxxxxxxxxx

*start with below command
JAVA_HOME=/path/jdk1.8.0_192 /path/wso2am-2.6.0/bin/wso2server.sh &
Reference mutual ssl:
https://docs.wso2.com/display/AM210/Mutual+SSL+Support+for+API+Gateway


text:
Q: Best way to load long image list in Flutter I have a ListView for load a list of images using advanced network image plugin like this:
@override
  Widget build(BuildContext context) {
    super.build(context);

    return CachedNetworkImage(
      imageUrl: parseURLImageFromService(productImageURL),
      height: screen.width * ratio,
      placeholder: Container(
        alignment: AlignmentDirectional.center,
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation(
            CompanyColors.green[500],
          ),
        ),
      ),
      errorWidget: defaultLogoImage(screen, ratio),
      width: screen.width * (ratio * 0.75),
    );
  }
}

But when i render the app, all image try to load at the same time, i would like to load the images ony by one waiting the previous.

A: I found a way to solve this, but the solution isn't related with Flutter. The main problem is the size of the images and the network speed of download, I solve this adding a function on the backend, that function resize the image when it's uploaded. So when I display the list of image I use the miniature image and when the user open the details I load the original size image.


text:
Q: TypeError: not all arguments converted during string formatting (while running unit tests) I started getting this error in PyDev on eclipse luna, in Linux environment, after rebooting my computer:
Traceback (most recent call last):
  File "/usr/lib64/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/usr/lib64/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file post_worker.py, line 105
Traceback (most recent call last):
  File "/usr/lib64/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/usr/lib64/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file post_worker.py, line 105

It happens when I try to run unit tests, any one of them. Moreover, it only happens in the IDE, when I run the tests from the command line, I've got no issues.


text:
Q: Discord.py Rewrite: How to get the guild when member joins When a member joins a server, the on_member_join function is executed, according to the docs:

Called when a Member joins a Guild.

Is there a way to get the Guild which the member has joined inside the on_member_join function?
async def on_member_join(member):
    guild_that_member_joined = ???

A: Every Member object has a guild attribute, which is a Guild object: https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.guild


text:
Q: Cannot hide property: Windows.Forms.TabControl.DrawMode I have a custom tab control deriving from System.Windows.Forms.TabControl with the following code:
[Browsable(false)]
private new TabDrawMode DrawMode
{
    get { return base.DrawMode; }
    set { base.DrawMode = value; }
}

I can still see DrawMode in the Properties view - what else can I try?

A: Since your property is private, the designer binds to the Parent (TabControl), which does have a public DrawMode property. By setting your property to public, it will look for the property inside your derived TabControl and will not appear inside the designer:
[Browsable(false)]
public new TabDrawMode DrawMode
{
    get { return base.DrawMode; }
    set { base.DrawMode = value; }
}


text:
Q: top in batch mode, need CPU% for every core I know that after running top, I can press 1 and get a list of the CPUs with their utilization percentages. I suspect I can do this in batch mode too with the -b option, but I don't know how, and I cannot find it in the manual.
I need to read it periodically from a python program, so it must be in batch mode.

A: You can use a configuration file for this.  The easiest way is to open top, and configure it the way you want.  In this case, that means using 1 to get the per-CPU listing.  Then have it write a configuration file with Shift+W. After that, it will use that config file whenever that user runs top, and keep the same appearance, even in batch mode.
Note that you'll probably need a $HOME variable defined, if you're using this via cron, or some other environment lacking the standard login definitions.

A: I am not familiar with a way to do that with top, but you might have a look at mpstat which will show cpu utilization per core.

A: # mpstat -P ALL 1

10:54:41 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
10:54:42 PM  all    8.20    0.12    0.75    0.00    0.00    0.00    0.00    0.00   90.93
10:54:42 PM    0   24.00    0.00    2.00    0.00    0.00    0.00    0.00    0.00   74.00
10:54:42 PM    1   22.00    0.00    2.00    0.00    0.00    0.00    0.00    0.00   76.00
10:54:42 PM    2    2.02    1.01    0.00    0.00    0.00    0.00    0.00    0.00   96.97
10:54:42 PM    3    2.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   98.00
10:54:42 PM    4   14.15    0.00    1.89    0.00    0.00    0.00    0.00    0.00   83.96
10:54:42 PM    5    1.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   99.00
10:54:42 PM    6    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
10:54:42 PM    7    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00


text:
Q: Error when enterting this command ALTER TABLE `report` AUTO_INCREMENT = 1 I get an error when using this command to alter my SQL table
Error message:
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right
syntax to use near 'ALTER TABLE `report` AUTO_INCREMENT = 1, 30' at line 2`

Any idea of that?

A: So why would you say AUTO_INCREMENT=1,30  ?
It has to be one number, and not a comma separated list of numbers.
ALTER TABLE report AUTO_INCREMENT=1

or
ALTER TABLE report AUTO_INCREMENT=30

Reference: MySQL


text:
Q: Computing float to 2 digits only (not formatting/rounding off 6 digits after decimal to 2) I am running a computation on an embedded processor which involves a float operation like this:
a = (float)23 / (float)3;  // a = 7.666....7

This is a long computation, and my app is OK with a certain amount of rounding error; I mean 7.67 or 7.66 doesn't matter.  Is there a way to cut down the amount of computation time spent in computing the float, or telling math.h to 2 digits ?
Any idea how to do this ?
PS:
Now I know many will suggest using fixed point, but I have specific requirements.

A: Precision is determined by the data type, common types like float and double have a fixed precision that can't change, but there are libraries like libfixmath that let you perform fast non-integer maths (in this case using int32_t)

A: There is nothing you can 'tell' math.h (in this regard); float does not have precision options.
If you want less computational intensive calculations you must use other types or methods.
You already mention the best candidate: fixed-point.  But, for obscure reasons, you say that you can't use it.
Other idea is to scale up your calculations by for example a factor 10,000, and keep everything as int (or longer).  Then, only scale down to float when needed.  But of course, it depends on your problem if you can do this.