text:
Q: past or present tense? I'm wondering whether the boldfaced forms in the follownig should have been changed into the past tense, e.g., "were," "could," and "was."

M: How was your stay at the hotel?
W: Excellent. The pool was wonderful. And the room was clean.
M: Sounds great. Did you go anywhere else?
W: No. We just stayed there all day. There are several good coffee shops in it. We can even have meals there. It is great, right?

A: I don't think they should be changed into the past tense. The reason why W used the present tense is that she was stating facts. Facts are always true to the speaker at the time of utterance.
When W said, "there are several good coffee shops in it," it implies she saw good coffee shops when she first stayed at the hotel. And when she left the hotel, the good coffee shops still exist. If she said, "there were several good coffee shops in it," it sounds weird because it might mean that all good coffee shops are taken down and are replaced by bad ones.
The follow-up sentences "we can even have meals there" and "it is great" tells more about the fact "there are several good coffee shops in it". They are also facts, so they must be in the present tense.
Edit: As explained by @stangdon, it is wrong to say "we can even have meals there" because W is not in the hotel anymore. It is better to say "we could even have meals there" in this context.

A:
W: No. We just stayed there all day. There are several good coffee shops in it. We can even have meals there. It is great, right?

This conversation seems to be about a recent hotel stay and, though the stay is past, it is reasonable to assume that the good coffee shops are still there.  The use of present tense are in paragraph 4 should be fine.
The clause

It is great, right?

however seems to describe more of that stay rather than the presence of coffee shops, hence was should be more appropriate.
The clause

We can even have meals there

is less clear.  Coffee shops' allowing customers to have meals there is a reasonable assumption, but if it is highlighted as if it is a special arrangement, then it could be it, special.  I hence interpret that to also be describing more of that stay and hence suggest was.

There are several good coffee shops in it. We could even have meals there. It was great, right?


text:
Q: Access 2007-Search Form does not return all values because of a blank field--Can't seem to find the LIKE that matches First of all thank you for your time and sorry if some issues are unclear, this is my first message here.
I'm having a problem with a custom search form I have made on ACCESS 2007.
Here is my database:

Here is my search form:

The main issue I have is that whenever I enter values in firstname, lastername, address, etc.
It works totally fine.
But as soon as I get to work phone, mobile or email, it doesn't show me "Florence Fluflo" because her fields are blank for these categories.
Now I have tried in the "Criteria" of the field Work phone to put these:

*

*LIKE ""

*LIKE "*" & [Forms]![frm_search]![WorkPhone1] & "*" OR "IsNull"

*=" " OR =""

*LIKE " "

*LIKE "*"
Nothing works... and it's pretty weird because I have done SQL and the SQL statement looks perfectly fine:
SELECT CLIENTS.First_name,
       CLIENTS.Surname,
       CLIENTS.Address,
       CLIENTS.Suburb,
       CLIENTS.Postcode,
       CLIENTS.Home_phone,
       CLIENTS.Work_phone
FROM CLIENTS
WHERE (((CLIENTS.First_name) Like "*" & [Forms]![frm_search]![Firstname1] & "*")
    AND ((CLIENTS.Surname) Like "*" & [Forms]![frm_search]![LastName1] & "*")
    AND ((CLIENTS.Address) Like "*" & [Forms]![frm_search]![Address1] & "*")
    AND ((CLIENTS.Suburb) Like "*" & [Forms]![frm_search]![Suburb1] & "*")
    AND ((CLIENTS.Postcode) Like "*" & [Forms]![frm_search]![Postcode1] & "*")
    AND ((CLIENTS.Home_phone) Like "*" & [Forms]![frm_search]![HomePhone1] & "*")
    AND **((CLIENTS.Work_phone) Like "*" & [Forms]![frm_search]![WorkPhone1] & "*" OR (CLIENTS.Work_phone) Like ""))**;

A: If you write "IsNull" (in quotes), it will be considered as a string. So, the proper way to verify if a field is null would be like this IS NULL
That means all you need to do for your thing to work is to write
OR IS NULL

after your LIKE statement

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between "at least one out of two children is a girl" and "a random child out of two is a girl" I'm struggling with the intuition here. I'm reading the Probability book by Blitzstein, where three situations are contrasted:

*

*There are two children, the eldest is a girl, what is the probability the youngest is also a girl? (1/2)

*There are two children, at least one is a girl, what is the probability the other is also a girl? (1/3)

*There are two children, you run into a random one on the street, and it's a girl, what is the probability the other is also a girl? (1/2)

Now, I understand the difference between situation 1 and situation 2: situation 1 has sample space {GG, GB, BG, BB}, and by knowing the eldest is a girl, this reduces the conditional universe to {GG, GB}. Situation 2 has the same sample space, but the conditional universe only reduces to {GG, GB, BG}. This all makes sense. However, I don't understand the difference between situation 2 and situation 3. Intuitively, my reasoning is that in both cases at least one child is a girl, and no information is given about whether it's the eldest or the youngest child, so they should have the same probability. Where is my reasoning mistaken?

A: I'm assuming that since it says "also a girl" in 3, it means you saw the child in the street is a girl.   Given that,  the other child could be boy or girl. It's the same as in situation 1, you know the exact status of a specific child, and it has no influence on the other child


text:
Q: Can't change RVM default I have problem changing the default ruby. Running OS X Lion.
macbook:~ work$ rvm list
rvm rubies

=* ruby-1.9.2-p290 [ x86_64 ]
   ruby-1.9.2-p318 [ x86_64 ]

As you can see, 1.9.2-p290 is the default.
macbook:~ work$ rvm use --default ruby-1.9.2-p318
Using /usr/local/rvm/gems/ruby-1.9.2-p318
macbook:~ work$ rvm list

rvm rubies

* ruby-1.9.2-p290 [ x86_64 ]
=> ruby-1.9.2-p318 [ x86_64 ]

After running rvm use --default ruby-1.9.2-p318, the Ruby changed, but default is still p290. And the next time I reopen a shell, the ruby used is p290.
Any ideas?
Thanks.

A: I had the same problem and found this made my day:
sudo rvm alias create default <ruby-version>

and/or
rvm use <ruby-version> --default

This worked for me changing the default to 1.9.3

A: You have multi-user installation, but I provide also information/instructions for user installation.
For multi-user installations:
Multi-user installations use /etc/profile.d/rvm.sh - this file is sourced every time any shell is spawned, this includes when you login, anything you do is already working in context of the loaded earlier default.
You need to restart computer for this to make effect.
For user installations:
you need to update your .*rc configuration files for --default to take effect:
rvm get stable --auto

and restart your computer.
Restart required for both
Restart is required because the earlier default was loaded before/while logging in, with the updated config files the loading point moves to proper place and there should be no more problems with changing default.
Default in scripting
When RVM is used as binary from $rvm_path/bin/rvm it can not set --default as it's bound to use and use is not working in scripting mode, you can use following commands to manage default:
rvm alias delete default
rvm alias create default 1.9.3

And to make it effective (replacement for rvm use default):
source $(rvm default do rvm env --path)

A: Try rvm --default  (not rvm use --default ). It worked for me
rvm list

rvm rubies

ruby-1.9.2-p318 [ x86_64 ]
=* ruby-1.9.3-p125 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

You can see that 1.9.3 is the default now
rvm --default ruby-1.9.2-p318

rvm list

rvm rubies

=* ruby-1.9.2-p318 [ x86_64 ]
   ruby-1.9.3-p125 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

A: You get this behaviour when RVM doesn't have write permissions on ~/.rvm
Fix it like this: (after switching in your usercode / group of course)
sudo chown -R nick:staff ~/.rvm


text:
Q: What the heck is happening to my doubles? So, I'm writing a raytracer and I have a basic class to represent the viewport. It looks like this:
camera.hpp:
#define real double

class Camera
{
    // self explanatory
    Vector3 origin, destination, up;

    // camera's coordinate system
    // N    = normal to projection plane ("z-axis")
    // U, V = x- and y-axes of projection plane
    Vector3 N, U, V;

    // Directional increment vectors for screen-space X and Y
    Vector3 xInc, yInc;

    // vFOV derived from hFOV
    real    horizontalFOV, verticalFOV;

    // width and height of projection buffer in pixels
    real    width, height;

public:
    // Constructs a camera
    // pO   = point of origin (i.e., where rays are emitted)
    // pLA  = point looked at, (i.e., pLA - pO = direction looked at)
    // vUp  = Up vector relative to camera's position
    // hFOV = Horizontal field-of-view in degrees. Vertical is calculated based on
    //        aspect ratio of viewport.
    // vW   = width of viewport in pixels
    // vH   = height of viewport in pixels
    Camera(Vector3 pO, Vector3 pLA, Vector3 vUp,
           real hFOV,  real vW,     real vH);

    // Constructs a ray from pO looking in the direction of the
    // specified pixel on the viewport. Note that floating values
    // can be given, in case we want to do supersampling.
    Ray RayForPixel(const real x, const real y);

    // Prints this camera's information to stdout.
    void dump();
};

camera.cpp:
#include "raytracer.hpp"

Camera::Camera(Vector3 pO, Vector3 pLA, Vector3 vUp, real hFOV, real vW, real vH) :
    origin(pO), destination(pLA), up(vUp), horizontalFOV(hFOV), width(vW), height(vH)
{
    // Non-square aspect ratios are not yet supported!
    assert(width == height);

    N = (pLA - pO);
    normalize(N);

    U = cross(N, vUp);
    normalize(U);

    V = cross(U, N);
    normalize(V);

    real aspectRatio = (width / height);
    verticalFOV      = (horizontalFOV / aspectRatio);

    // TODO: verify this.
    real hFov2 = horizontalFOV / 2;
    real vFov2 = verticalFOV / 2;

    // TODO: implement non-square aspect ratios
    xInc = -U * ((2.0 * tan(DEG2RAD(vFov2))) / width);
    yInc = -V * ((2.0 * tan(DEG2RAD(vFov2))) / height);
}

Ray Camera::RayForPixel(const real x, const real y)
{
    Vector3 direction = N +
         (yInc * (0.5 * ((2.0 * y) - 1.0 - height) ) ) +
         (xInc * (0.5 * ((2.0 * x) - 1.0 - width ) ) );

    printf("<%f, %f, %f> ", xInc.x, xInc.y, xInc.z);
    normalize(direction);

    return Ray(origin, direction);
}

void Camera::dump()
{
    Vector3 rfp00 = RayForPixel((real)0, (real)0).direction;
    Vector3 rfp01 = RayForPixel((real)0, height - 1).direction;
    Vector3 rfp10 = RayForPixel(width - 1, (real)0).direction;
    Vector3 rfp11 = RayForPixel(width - 1, height - 1).direction;

    Vector3 rfp50 = RayForPixel((width/2) - 1, (real)0).direction;
    Vector3 rfp05 = RayForPixel((real)0, (height/2) - 1).direction;
    Vector3 rfp55 = RayForPixel((width/2) - 1, (height/2) - 1).direction;

    printf(
    "Camera at <%+7.5f, %+7.5f, %+7.5f>\n"
      "    hFOV = %+7.5f, vFOV = %+7.5f\n"
      "    xInc = <%+7.5f, %+7.5f, %+7.5f>\n"
      "    yInc = <%+7.5f, %+7.5f, %+7.5f>\n"
      "  Coordinate system:\n"
      "    N: <%+7.5f, %+7.5f, %+7.5f>\n"
      "    U: <%+7.5f, %+7.5f, %+7.5f>\n"
      "    V: <%+7.5f, %+7.5f, %+7.5f>\n"
      "  Rays for screen-space extents:\n"
      "    < 0,  0> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    < 0,  1> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    < 1,  0> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    < 1,  1> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    <.5,  0> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    < 0, .5> -> <%+7.5f, %+7.5f, %+7.5f>\n"
      "    <.5, .5> -> <%+7.5f, %+7.5f, %+7.5f>\n",
        origin.x, origin.y, origin.z,
        horizontalFOV, verticalFOV,
        xInc.x, xInc.y, xInc.z,
        yInc.x, yInc.y, yInc.z,
        N.x, N.y, N.z,
        U.x, U.y, U.z,
        V.x, V.y, V.z,
        rfp00.x, rfp00.y, rfp00.z,
        rfp01.x, rfp01.y, rfp01.z,
        rfp10.x, rfp10.y, rfp10.z,
        rfp11.x, rfp11.y, rfp11.z,
        rfp50.x, rfp50.y, rfp50.z,
        rfp05.x, rfp05.y, rfp05.z,
        rfp55.x, rfp55.y, rfp55.z);
}

I'm creating it like this, and calling dump():
Camera camera = Camera(
        Vector3(0, 0, -5), // Look from <0, 0, -5>
        Vector3(0, 0, 0),  // Look at world-space origin
        Vector3(0, 1, 0),  // Camera is XZ axis-aligned.
        70,                // 70 degree horizontal FoV
        OUT_W, OUT_H);

raytracer.SetCamera(&camera);

// later, in raytracer::render:
camera->dump();

And I get this output:
Camera at <+0.00292, +0.99996, +0.00292>
    hFOV = +0.02527, vFOV = -0.00891
    xInc = <+0.01170, -0.00878, +0.00292>
    yInc = <+0.99996, +0.00292, +0.99964>
  Coordinate system:
    N: <+0.99996, +0.00292, -0.00875>
    U: <+0.00292, +0.99996, +0.00292>
    V: <+0.99996, +0.00292, +0.99989>
  Rays for screen-space extents:
    < 0,  0> -> <-0.00292, +0.00292, +0.99999>
    < 0,  1> -> <-0.00292, +0.00875, +0.99996>
    < 1,  0> -> <-0.00875, +0.00292, +0.99996>
    < 1,  1> -> <-0.00875, +0.00875, +0.99992>
    <.5,  0> -> <-0.00875, +0.00292, +0.99996>
    < 0, .5> -> <+0.99989, +0.01170, -0.00878>
    <.5, .5> -> <+0.99964, +0.02527, -0.00891>

I have absolutely no idea why this is happening, and this has been a major source of WTF for the past 3 days.
EDIT: I should've actually explained my problem, sorry D: (been a little stressed out over this problem, didn't stop to think that not everyone knows this code in and out :P). In my code I'm setting hFOV = vFOV, yet the output does not correspond to that. The rest of my double arithmetic went out of whack as well.
Michael Dorgan pointed out that the camera may have been a stack var going out of scope and that was exactly it!

A: Camera is (probably) a stack var and you are saving it. Is it going out of scope?  :)


text:
Q: Segmentation Fault (core dumped) infinite recursion I am getting a segmentation fault when I run my program.Someone had mentioned to me that there was some code that would cause an infinite loop and crash the program, which I assume is what is happening. However they did not tell me the part of the code that was doing this, so this is just a guess. Also, as an aside, can someone tell me if the return statements are necessary when I overload the "<<" and ">>" operators? After compiling with g++ -Wall, it warned me that there was no return statement in the function that was not of type void.
I will provide the source code from the three files I am using:
main.cc
#include <iostream>
#include "my_int.h"
using namespace std;

int main()
{
    my_int value1;
    my_int value2(5);

    // testing the constructors

    cout <<" Value 1 contains "<<value1 <<endl <<endl;
    cout <<" Value 2 contains "<<value2 <<endl <<endl;

    // testing the extraction and insertion operators
    cout <<"Enter an int value -- >  ";
    cin >> value1;
    cout <<"Value1 now contains "<<value1<<endl<<endl;

    // testing binary operators

    cout << value1 << " + " << value2 << " = " << value1 + value2 <<endl <<endl;
    cout << value1 << " - " << value2 << " = " << value1 - value2 <<endl <<endl;
    cout << value1 << " * " << value2  << " = " << value1 * value2  <<endl <<endl;
    cout << value1 << " / " << value2 << " = " << value1 / value2 <<endl <<endl;

    cout << value1 << " * " << 3  << " = " << value1 * 3  <<endl <<endl;

    // testing the % operator

    if (value1 % 2 == 0)
        cout << value1 << " is even  \n\n";
    else
        cout << value1 << " is odd \n\n";

    // testing comparison operators

    if (value1 <= value2)
        cout<<value1 << " <= "<< value2 <<endl;
    else
        cout<<value1 << " > "<< value2 <<endl;

    if (value1 == value2)
       cout<<value1 << " == "<< value2 <<endl;
    else
       cout<<value1 << " != "<< value2 <<endl;

    // testing increment and decrement operators

    ++value1;
    cout <<" increment the value1 by 1 "<< value1 << endl;

    --value2;
    cout <<" decrement the value2 by 1 "<< value2 << endl;

    // testing the set function

    value1.set(25);

    cout <<" Value1 now contains  "<< value1 <<endl;

    return 0;
}

my_int.cc
#include <iostream>
#include "my_int.h"
using namespace std;

my_int::my_int(int x){
    val = x;
}

my_int::my_int(){
    val = 0;
}

void my_int::set(int num){
    val = num;
}

my_int operator +(const my_int& num1, const my_int& num2){
    my_int temp;
    temp = num1 + num2;
    return(temp);
}

my_int operator -(const my_int& num1, const my_int& num2){
    my_int temp;
    temp = num1 - num2;
    return(temp);
}

my_int operator %(const my_int& num1, int num2){
    my_int temp;
    temp = num1%num2;
    return(temp);
}

my_int operator /(const my_int& num1, const my_int& num2){
    my_int temp;
    temp = num1/num2;
    return(temp);
}

my_int operator *(const my_int& num1, int num2){
    my_int temp;
    temp = num1*num2;
    return(temp);
}

my_int operator *(const my_int& num1, const my_int& num2);

void my_int::operator ++(){
    val += 1;
}

void my_int::operator --(){
    val -= 1;
}

bool operator ==(const my_int& num1, const my_int& num2){
    return(num1 == num2);
}

bool operator <=(const my_int& num1, const my_int& num2){
    return(num1 <= num2);
}

istream& operator >>(istream& inp, my_int& num){
    inp >> num;
}

ostream& operator <<(ostream& outp, const my_int& num){
    outp << num;
}

int my_int::get_val()const{
    return(val);
}

my_int.h
#include <iostream>
using namespace std;

class my_int
{
public:
    //constructors
    my_int(int x);
    my_int();

    // friend functions
    friend my_int operator + (const my_int& num1, const my_int& num2);

    friend my_int operator - (const my_int& num1, const my_int& num2);

    friend my_int operator % (const my_int& num1,  int num2);

    friend my_int operator *(const my_int& num1, const my_int& num2);

    friend bool operator <= (const my_int& num1, const my_int& num2);

    friend istream& operator >> (istream& inp,  my_int& num);

    friend ostream& operator << (ostream& outp, const my_int& num);

    //mutators
    void set(int num);
    void operator ++();
    void operator --();

    // accessors
    int get_val()const;

 private:
     int val;
};

// non-member operators

my_int operator * (const my_int& num1, int num2);

my_int operator / (const my_int& num1, const my_int& num2);

bool operator == (const my_int& num1, const my_int& num2);

Any help you guys could provide would be much appreciated!

A: All your operators are causing infinite loops:
my_int operator +(const my_int& num1, const my_int& num2){

    my_int temp;
    temp = num1 + num2; // this uses operator+(const my_int& num1, const my_int& num2)

    return(temp);

}

Must be:
my_int operator +(const my_int& num1, const my_int& num2){

    return my_int( num1.val + num2.val); // this uses pre-defined operator+(int num1, int num2)

}

Same comment for -, %, *, ==, ...
For your next development, I would recommend that you write one function, test it, write another, test it and so one. Then you can fix the bugs one by one ;-)

A: In this functions you forgot to return a value:
istream& operator >>(istream& inp, my_int& num){
    inp >> num;
    return inp; //You forgot this line
}

ostream& operator <<(ostream& outp, const my_int& num){
    outp << num;
    return outp; //and this one
}

Next, there is missing an implementation of the following function:
my_int operator *(const my_int& num1, const my_int& num2);

And your operators +, -, *, / and % are causing infinite loop. You need to increment a value and not call your operator again...


text:
Q: Bash sorting list by keyword I'm trying to write a bash script that takes an input stream and sorts lines containing a keyword to the top.
Starting point:
$ cat file
cat
dog
mouse
bird
cat and mouse
lorem
ipsum

Goal:
$ cat file | sort-by-keyword mouse
mouse
cat and mouse
cat
dog
bird
lorem
ipsum

I've tried to implement this using sort but failed. Is another tool/way I'm not aware of?

A: You can not sorting rest of the records. Based on input. please try
awk '{if ($0 ~ /mouse/) {print} else {a[NR]=$0}} END {for (i in a) print a[i]}'

Demo:
$cat file.txt
cat
dog
mouse
bird
cat and mouse
lorem
ipsum
$awk '{if ($0 ~ /mouse/) {print} else {a[NR]=$0}} END {for (i in a) print a[i]}' file.txt
mouse
cat and mouse
bird
lorem
ipsum
cat
dog
$

A: One dirty way to achieve it:
grep mouse file && grep -v mouse file

A: Using sed:
script file sort-by-keyword:
#!/bin/bash
input="$(cat)"
echo "$input" | sed "/$1/p;d"
echo "$input" | sed "/$1/!p;d"

Usage:
chmod +x sort-by-keyword

cat file | ./sort-by-keyword mouse


text:
Q: How to use like clause query in rails? I wanted to get a json format of the data when searching for the keyword so I use LIKE clause and query like this
"select * from employees where fname like ? or mname like ? or lname like ? or username like ? or id like ?", str, str, str, str, str

but I want to code it using rails. I have this code in my controller
def showemployees
  str = params[:str]
  render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or
    (Employee.employees[:mname].matches("%#{str}%")) or
    (Employee.employees[:lname].matches("%#{str}%")) or
    (Employee.employees[:id].matches("%#{str}%"))
end

and this code in my config/routes.rb
get 'employees/showemployees'
root :to => 'employees#new'
resources :employees
post 'employees/update_info'

when i type this, http://localhost:3000/employees/showemployees?str=samplename, a json format of the record should appear yet I got this error message
undefined method `employees' for #<Class:0x8e38900>
app/controllers/employees_controller.rb:6:in `showemployees'

where line 6 has this code
render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or

A: You can chain where queries, but this AND each where query results
Employee.where('fname LIKE ?', "%#{str}%").where('lname LIKE ?', "%#{str}%").where('mname LIKE ?', "%#{str}%").where('username LIKE ?', "%#{str}%").where('id LIKE ?', "%#{str}%")

or to use OR clause
Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")


text:
Q: getting compile time error while converting string to set? I'am getting error in the last assert statement but i don't no why please help me
def test_set_creation():
    """
    sets can be created from any sequence like list or a tuple.
    """
    test_list = [1, 2, 1, 3]
    set1 = set(test_list)
    assert {1,2,3} == set1

    test_string = "apple"
    set2 = set(test_string)
    assert {} == set2

A: {} creates an empty dictionary, not an empty set. Your assertion will always fail.
Use set() to create an empty set object, and you probably should test that set2 is not empty:
assert set() != set2

From the set displays reference documentation:

A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values
[...]
An empty set cannot be constructed with {}; this literal constructs an empty dictionary.

A: You are asserting dictionary and set which is wrong in the last line.
>>> type({})
<type 'dict'>
>>> type(set())
<type 'set'>
>>>


text:
Q: Combination of Angular & React to streamline I'm currently making the change from Angular routing & client-side rendering to React & Flux for isomorphic builds. I've just started learning React so bear with me.
Here's my problem. To render a simple list, it would look like this.
HTML, component & render in React:

Or in Angular, with a controller and HTML:

{{item}}

Now to me, the Angular code looks a lot shorter and more readable. The HTML where data is injected is not infiltrated by javascript code. I'm not trying to start a React v Angular debate. Instead, I'm wondering if there is a way to combine the best properties of both? i.e. have the stateful component concept from React but instead of using raw javascript in the JSX, using things like Angular's ng-repeat. If not, is there another way to approach writing the JSX in my example?

A: IMHO, the React code is better and more readable because it is just javascript. It doesn't require (hardly) any extra knowledge to understand what's going on. You read the angular one, and if you're not familiar at all with angular, you're immediately wondering: what's $scope? what's app? what's controller do? why do i pass it an array and why is the second argument a function? what calls this function? what's an ng-repeat? this list goes on ...
Now, on to your question: No.
The JSX you've written is perfect (well, sort of, I'll add my modifications below). Why is it perfect? It's perfect because nearly any programmer on the planet can figure out what it does: it maps over a list of items.
Now, if I were to rewrite it, I'd do something like this:
var List = React.createClass({

    ...

    renderItem: function(item, key) {
        return
{item}
;
    },

    render: function() {
        return
{this.state.items.map(this.renderItem)}
;
    }
}

Creating a separate renderItem function to render the item will make this a lot more future-proof (and readable IMO). Also, you shouldn't put your key as the item itself, because (in this example) that would prevent two items from having the same value (ie, two "Apple"s)
It seems like maybe what you're really asking is, "directives in angular are cool! why doesn't react have directives? and can/should I add directives to React?"
If I were to address that, I'd say... directives do seem cool in angular. Although, there's clearly some big problems with them, even the angular team abandoned them (custom ones anyway) in angular 2. There is some react library on github floating around right now that adds ng-like directives to JSX, but I highly advise against it. It's really just a bad idea. I'm going to repeat this for double extra super clarity: It's a bad idea. What's wrong with writing plain old javascript and rendering it with JSX handlebars? Do you really need an ng-repeat because writing list.map is too hard? The added complexity and learning curve, however slight, far outweighs the benefits. render() is a beautiful pure function, let's leave it that way.

A: You can actually interoperate Angular and React using https://github.com/bcherny/ngimport. We've used it successfully on a 10k file hybrid Angular+React project - let me know if I can answer any questions!


text:
Q: Dynamically refreshing the ListView with changes done to database android I am most concerned about Performance issue and don't want users to wait for progress.
I have a chatActivity, where i show a ListView.
Here i send a chatMessage
Chats chat = new Chats(chatBox.getText().toString(),Chats.TYPE_MINE, dt.format(now));
chat.personId = chatee.getMyId();
chat.isDelievered = Chats.DELIEVERED_NONE;
chats.add(chat);
mAdapter.notifyDataSetChanged();

Notice that Chat delievery is set to NONE Right now. So basically the message is being added to the Chat List even its not delivered yet.
Now on back thread here is what's happening
It takes few seconds to send message where i do this
  boolean bool = sendMessage(m);
  if (bool)
     chatee.isDelievered = Chats.DELIEVERED_DONE; (MESSAGE SENT)

  if (chatee.isDelievered == Chats.DELIEVERED_DONE)
  {
     app.mDbHelper.saveMessage(chatee); // SAVING TO DATABASE
     Intent i = new  Intent(Constants.REFRESH_NOTIF).putExtra("refresh",Constants.REFRESH_NOTIF);
     context.sendBroadcast(i);
  }

It will send a broadcast to the activity.
Now here is the problem.
Broadcast call this function
public void callUIMethodForRefresh(Intent intent)
{
    String ref = intent.getStringExtra("refresh");
    if (ref == null)
    {

    }
    else if (ref.equals(Constants.REFRESH_NOTIF))
    {
    }
}

Here i am confused of how can I reset that previous Chat object added to my List.
Points to be noted , i can be sending messages at a very fast speed and the refresh could be called for an old message whereas a new message is already typed.

*

*ONE way is i make a For loop and check for all the "ChatList" array for the message sent and then replace its delivery notice, but again this is very low performance incase i have 1000+ objects in the list.

*Is there any way, i can attach the sqlite database with my listView adapter that automatically detects the changes and reset the listView etc and etc?

What could be the best strategies here to avoid performance issues.

A: I would suggest looking into ContentProviders and Loaders (specifically a CusorLoader). Combining these with a CursorAdapter, you can use the ContentProvider which inserts/deletes/updates your sqlite database and notifies your loader to reload it's dataset and update the CursorAdapter/ListView.


text:
Q: Замена dictionary c# я использую dictionary в C# для быстрой проверки существования элемента в массиве по ключу, по факту значение ключа мне не нужно, выглядит это так:
public void update_object_select_contour(MyObject myObject)
    {
        List<Vector2i> list_position_tmp = myObject.list_position;
        Dictionary<string, byte> dictionary_position_tmp = new Dictionary<string, byte>();
        for (int i = 0; i < list_position_tmp.Count; i++)
        {
            dictionary_position_tmp.Add(list_position_tmp[i].ToString(), 0);
        }
        if(dictionary_position.ContainsKey(new Vector2i(5, 5).ToString()))
        {
            //Поиск элемента по ключу
        }
    }

То есть я закидываю координаты точек в dictionary и потом проверяю есть ли они там по нужному мне поиску и у меня есть 2 вопроса:
1) Какую структуру хранения данных можно использовать для этого?(пытался найти деревья в C#, так и не нашел) Хотелось бы чтобы выглядело это примерно так:
Dictionary<string>

2) Какой лучше использовать ключ для хранения положений координат? Как я знаю преобразовывать пары к тексту и хранить как текст не лучшая идея

A: Вы используете словарь. Словарь - это когда у вас есть ключ и есть значение, ассоциированное с ключом.
То, что вам нужно, называется HashSet<T>.
Если вы хотите хранить в HashSet<T> координаты, то тогда координаты желательно должны быть целыми числами, так как дробные числа могут быть не равны даже если они были посчитаны по одной и той же формуле просто из за наличия погрешности.
Но вот с целыми числами проще. Но тут нужно иметь ввиду, так как, если вы будете хранить координаты в HashSet<T>, который использует хеш функцию для хранения и хеш функцию и функцию эквивалентности для поиска элементов, вас в классе координат надо перегрузить методы Equals и GetHashCode. Вот пример:
public class Coordinates2D
{
    public int X { get; }
    public int Y { get; }

    public Coordinates2D(int x, int y)
    {
        X = x;
        Y = y;
    }

    protected bool Equals(Coordinates2D other)
    {
        return X == other.X && Y == other.Y;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Coordinates2D) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (X * 397) ^ Y;
        }
    }
}

Теперь этот класс можно использовать в HashSet<Coordinates2D>
var set = new HashSet<Coordinates2D>();

set.Add(new Coordinates2D(10, 25));

Console.WriteLine(set.Contains(new Coordinates2D(1, 1))); // false
Console.WriteLine(set.Contains(new Coordinates2D(10, 25))); // true

Вывод очевиден


text:
Q: INNER JOIN HQL Query from Grails I am trying to figure out how to make this snip of code work:
def searchString = unchecked.join(",");
        searchString = searchString.replace("\"", "'")
        println("searchString: " + searchString);

        def matches=Employee.executeQuery("select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name  in (" +searchString + ")");

This is the query string passed to executeQuery
select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name  in ('AA','BS')

which I can run in SQL Server and it returns the right results, however my grails code complains:
Stacktrace follows:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ON near line 1, column 59 [select e.id from Employee as e INNER JOIN Education as ed ON e.id = ed.employee_id INNER JOIN education_type AS et ON et.id = ed.type_id WHERE et.name  in ('AA','BS')]

So what am I doing wrong? Is it the wrong domain object executing the query?

A: Consider doing it like this:
def employee = Employee.withCriteria {
    education {
        educationType {
            in("name", ["AA", "BS"])
        }
    }
}

A: HQL is slightly/enough different than standard SQL. Assuming Hibernate knows about the relationship between these objects you can simplify your query to
List<String> typeNames = unchecked.collect { it.replace("\"", "") }
String query = """FROM Employee e
                  WHERE e.education.educationType.name IN (:typeNames)"""
List<Employee> = Employee.executeQuery(query, [typeNames: typeNames])

It's really important to use either named params or positional params with your query to prevent sql injection. Also if you really just want a list of employee id's rather than instances you can put the SELECT e.id back in there. There is also no reason to include the quotes since when the params are bound they will use the correct quotes for the database you are working with, given that the above code snippet also stripts out the quotes but you might rethink even letting them be included in the first place.


text:
Q: Ошибка PSQLException: ERROR: syntax error at or near "value" при записи данных в БД Создал метод для записи данных в БД postgresql при помощи jdbc, но при попытке выполнения запроса выдает ошибку:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "value"
  Позиция: 28

Код метода :
try {
    stat = conn.createStatement();
    stat.execute("insert into users (chatid) value + ("+chat_id+");");
} catch (SQLException e) {
    e.printStackTrace();
}

A: Потому что values, а не value. И лучше не использовать конкатенацию строк для формирования запросов, это небезопасно. Применяйте подготовленные запросы:
String query = "insert into users (chatid) values (?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
    preparedStatement.setInt(1, chat_id);
    preparedStatement.executeUpdate();
}


text:
Q: EmberJS Execute JS after Render on all Views I'm trying to run this code:
var width = 0;
$('.photos article').each(function(){ width = width + $(this).width();});
$('.photos').width(width);

After the views render and can't figure out how to do that, here's the code with all the views and content:
http://jsbin.com/okezum/6/edit
I want to run my code on all views, can someone help me?

A: What you are trying to do can be achieved by defining the didInsertElement hook on all your view's and after getting the DOM element's id you can execute what ever jQuery code you might need. Since you want this to be executed on 'all' your view's you could write a general view from which all the view's that need the code to be executed do extend from.
Example:
App.GeneralView = Ember.View.extend({
  didInsertElement: function() {
    var width = 0;
    $('.photos article').each(function(){
      width = width + $(this).width();
    });
    $('.photos').width(width);
  }
});

App.IndexView = App.GeneralView.extend();
...

Note if need to get the view's id you can access it with this.get('elementId'), I've also modified your jsbin, see here for a working version.
Hope it helps.

A: Fixed with this:
App.GeneralView = Ember.View.extend({
    didInsertElement: function() {
        if (this.$().find(".post img").length > 0) {
            var WIDTH = 0, HEIGHT = $(window).height(), SIDEBAR_WIDTH =   $('#sidebar').outerWidth();
            this.$().find(".post").each(function(){
                WIDTH += parseInt($(this).find('img').attr('width'));
                $(this).find('img').height(HEIGHT - 80).removeAttr('width');
            });
            $('body').children('.ember-view').innerWidth(WIDTH);
        } else {
            Ember.run.next(this, function() {
                this.didInsertElement();
            });
        }
    }
});

Dont know if it's the best approach, but works ;s


text:
Q: Hyphae simulation fungus using python: terminal problem I am trying to run the hyphae (fungus) using the code provided here : https://github.com/petercollingridge/code-for-blog/blob/master/hyphae/hyphae.py
But, when I run the code I get this error in terminal:  Blocking request with no referer...
Furthemore, does anyone have any simulations on hypahe ?
Thanks again


text:
Q: How Can 2 onload() JavaScript Scripts be Loaded? With this function:
function start() {
MONDUX();
Biggie();
}

function MONDUX executes, and the AJAX call returns good data and is displayed correctly.
However, Biggie() is a.w.a.l.
The result of this :
function start() {
Biggie();
MONDUX();
}

is the opposite.  Biggie() works as expected, MONUX() fails.
This doesn't do any good, down in the body:
<script type="text/JavaScript">
window.onload= start();
</script>

and, this dodge is not helpful:
<body onload="start()">

and that was tried like so also
Detest cargo~cult programming and running out of ideas here.  Suggestions?
These resources were all related // near hits // no cigar.
Loading javascript in body onload with 2 functions
JS and Body(Window) Onload event
JavaScript: How is "function onload() {}" different from "onload = function() {}"?    That one
was fascinating but way deep waters for me...
How to onload two javascript files?     meh...  good, but...
??  :/~
<script type="text/javascript" >

 function MONDUX(){
if (window.XMLHttpRequest)
 { // code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
  { // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementById("WhatThexBobby").innerHTML=xmlhttp.responseText;
  }
 }
xmlhttp.open("POST","000 8 KISS 22solo PHP.php?figure1=5&figure2=33", true);
xmlhttp.send();

 alert(WhatThexBobby);

}
 </script>
 <script type="text/javascript" >

function Biggie(){

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
 document.getElementById("FreakinEh").innerHTML=xmlhttp.responseText;
 }
 }
 xmlhttp.open("POST","000 8 KISS solo PHP.php?figure1=5&figure2=10", true);
xmlhttp.send();

alert(FreakinEh);
 }

 </script>

A: You're assigning the request to the global variable xmlhttp, and then reassigning that variable to another request before the first one has returned. I don't know if that is causing your problem, but it's definitely going to cause a problem. It's also very bad JavaScript practice.
Simple fix is to put the line 'var xmlhttp;' at the beginning of both functions.
Edit: Just in case you didn't know this: xmlhttprequest is asynchronous. You call 'send', and your remaining statements in the script and document continue to run while the request is being sent to the server. Only after the server returns do the various callback methods (onreadystatechange, and the like) get called, and this is long after your alerts were shown.

A: Considering one of them is throwing some error, would it not be good idea to put them in Try Catch ? Something like,
function start() {
  try
  {
    MONDUX();
  }
  catch(err)
  {
   // handle error
  }
  try
  {
    Biggie();
  }
  catch(err)
  {
    //Handle error
  }
  finally
  {
   // cleanup
  }
}

This will ensure both runs even if one of them mis-fires.


text:
Q: How to run async form in background without deadlocking Run Async Form in Background without deadlocking
FormA (see example below) is old and loads slowly due to lots of lazy-loading EF6 code etc. We've managed to speed it up with some async methods that allow the form to at least be displayed whilst loading data. Async all the way up to the event handlers is working nicely - UNTIL: the same form is loaded in the background by a second form (FormB) that loops through and loads the form for multiple records in order to run some checks over the data as it loads (yeah not at all ideal, but not going there now).
Before the async changes, FormA was being created in a method on FormB started using Thread.Start(...) - now we've reworked to be async all the way up to the Button_Click event handler that started the mass update process, but FormA is now hogging the UI thread so FormB never updates any progress indicators until everything is finished.
We've tried using Task.Run(...) to create instances of FormA and do its work, but we always get a deadlock on the first await asyncMethod(...) in FormA. The lowest level of those async methods do use ConfigreAwait(False), but the upper levels don't because there are UI Components that need to be updated after retrieving data from the database which must happen on the same thread that created the form and its controls.
FormA has this sort of code
    public partial class FormA : Form
    {
        private int _counter;

        public FormA(int counter)
        {
            InitializeComponent();

            _counter = counter;
        }

        private async void formDoWork_Load(object sender, EventArgs e)
        {
            this.Text = "Loading...";
            await Task.Delay(5000); // Various async tasks happen here
            this.Text = "Loaded";
        }

        public async Task LoadDataAsync()
        {
            this.workingLabel.Text = "Working...";
            string result = await GetDataAsync(); // Get the data but can't ConfigureAwait(false) because we need to update UI components afterwards
            this.workingLabel.Text = "Finished! " + result;
        }

        private async Task<string> GetDataAsync()
        {
            // Get the data from the database - we can ConfigureAwait(false) here because no UI components are updated at this level (in real code this would be in a separate data layer library)
            await Task.Delay(3000).ConfigureAwait(false);
            return $"Loading #{_counter}";
        }
    }

Then in FormB we do something like this:
public partial class FormB : Form
{
    public FormB()
    {
        InitializeComponent();
    }

    private async void GoButton_Click(object sender, EventArgs e)
    {
        this.GoButton.Enabled = false;
        var activeTasks = new List<Task>();

        for (int i = 0; i < 10; i++)
        {
            // Start processing form asynchronously and keep track of the task for later
            Task processTask = ProcessFormAsync(i);
            activeTasks.Add(processTask);
            this.ProgressLabel.Text = $"Started #{i}";
            await Task.Delay(1000);
        }

        // Wait for all the tasks to be finished, then update progress on UI
        await Task.WhenAll(activeTasks);

        this.ProgressLabel.Text = "Finished.";
        this.GoButton.Enabled = true;
    }

    private async Task ProcessFormAsync(int counter)
    {
        using (var newForm = new FormA(counter))
        {
            // Show the form to trigger form_Load event handler and then hide it again
            newForm.Show();
            newForm.Hide();

            // Now call the main Load function which is also async.
            await newForm.LoadDataAsync();
            newForm.Close();
        }
    }
}

And all works well, except that everything (besides the continuation of FormA.GetDataAsync) is running on the Main UI thread
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 0 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 0 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 0 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 1 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 1 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 1 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 2 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 2 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 2 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 0 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 0 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 3 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 3 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 3 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 1 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 1 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 4 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 4 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 4 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 0 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 2 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 2 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 5 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 5 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 5 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 1 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 3 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 3 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 6 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 6 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 6 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 2 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 4 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 4 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 7 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 7 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 7 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 3 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 5 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 5 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 8 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 8 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 8 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 4 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 6 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 6 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244)  | 9 >>>
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 9 >>>
AsyncWinForms.FormA.GetDataAsync() | Main Thread(7244) | 9 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 5 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 7 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 7 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 6 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 8 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 8 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 7 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13984) | 9 <<<
AsyncWinForms.FormA.LoadDataAsync() | Main Thread(7244) | 9 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 8 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Main Thread(7244) | 9 <<<
The program '[17808] AsyncWinForms.exe' has exited with code 0 (0x0).

In our real scenario  FormA is so busy doing UI work it means that nothing on FormB is updated until the end of the processing which defeats the purpose of updating progress. So we've tried to change it to run FormA on a bacgkround thread like this:
Task processTask = Task.Run(async () => await ProcessForm(i).ConfigureAwait(false)));

And FormB now gets to update progress, but FormA deadlocks on any await ...Async method calls.
Deadlocking Output:
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 0 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 0 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 0 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 1 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 1 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 1 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 2 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 2 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 2 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 3 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 3 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 3 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 0 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 4 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 4 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 4 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(12084) | 1 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 5 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 5 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 5 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(12084) | 2 <<<
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 6 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 6 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(12084) | 3 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 6 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(11596)  | 7 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(11596) | 7 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 4 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(11596) | 7 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(13184)  | 8 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(13184) | 8 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(12084) | 5 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 8 >>>
AsyncWinForms.FormA.formDoWork_Load(object, System.EventArgs) | Worker Thread(11596)  | 9 >>>
AsyncWinForms.FormA.LoadDataAsync() | Worker Thread(11596) | 9 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(13184) | 6 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(11596) | 9 >>>
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(11596) | 7 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(1548) | 8 <<<
AsyncWinForms.FormA.GetDataAsync() | Worker Thread(12084) | 9 <<<
The thread 0x60c has exited with code 0 (0x0).
The thread 0x2f34 has exited with code 0 (0x0).
The thread 0x2d4c has exited with code 0 (0x0).
The thread 0x3380 has exited with code 0 (0x0).
The program '[6036] AsyncWinForms.exe' has exited with code 0 (0x0).

Why is this happening? We can't see anything that is blocking the new worker threads, but it deadlocks everytime. What alternatives do we have?


text:
Q: P2 Autoupdate from web repository I have some problems with P2's autoupdate, when I do locally, from a local repository all work fine and I can do my autoupdates at restart but when I try to update from a web repo I have these errors:
An internal error occurred during: "Install download0".
org.eclipse.swt.SWTException: Invalid thread access

Really, I don't understand what the difference is.
In my ApplicationWindowWorkbenchAdvisor I have this post window open method:
private static final String JUSTUPDATED = "justUpdated";

public void postWindowOpen() {
    final IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper
            .getService(Activator.bundleContext,
                    IProvisioningAgent.SERVICE_NAME);
    if (agent == null) {
        LogHelper
                .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                        "No provisioning agent found.  This application is not set up for updates."));
    }
    final IPreferenceStore prefStore = Activator.getDefault()
            .getPreferenceStore();
    if (prefStore.getBoolean(JUSTUPDATED)) {
        prefStore.setValue(JUSTUPDATED, false);
        return;
    }

    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
            IStatus updateStatus = P2Util.checkForUpdates(agent, monitor);
            if (updateStatus.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
                PlatformUI.getWorkbench().getDisplay()
                        .asyncExec(new Runnable() {
                            public void run() {
                                MessageDialog.openInformation(null,
                                        "Updates", "No updates were found");
                            }
                        });
            } else if (updateStatus.getSeverity() != IStatus.ERROR) {
                prefStore.setValue(JUSTUPDATED, true);
                PlatformUI.getWorkbench().restart();
            } else {
                LogHelper.log(updateStatus);
            }
        }
    };
    try {
        new ProgressMonitorDialog(null).run(true, true, runnable);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
    }

}

And in my P2Util this:
    public static IStatus checkForUpdates(IProvisioningAgent agent,
        IProgressMonitor monitor) {
    ProvisioningSession session = new ProvisioningSession(agent);
    UpdateOperation operation = new UpdateOperation(session);
    SubMonitor sub = SubMonitor.convert(monitor,
            "Checking for application updates...", 200);
    IStatus status = operation.resolveModal(sub.newChild(100));
    if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
        return status;
    }
    if (status.getSeverity() == IStatus.CANCEL)
        throw new OperationCanceledException();

    if (status.getSeverity() != IStatus.ERROR) {
        ProvisioningJob job = operation.getProvisioningJob(null);
        status = job.runModal(sub.newChild(100));
        if (status.getSeverity() == IStatus.CANCEL)
            throw new OperationCanceledException();
    }
    return status;
}

In my PreferenceInitializer this:
node.putBoolean(PreferenceConstants.PREF_AUTO_UPDATE_ENABLED, true);
node.putBoolean(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE, true);
node.putBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY, true);

I repeat myself: from local repo I can perform autoupdates but from web repo I can't.
Thank for reading.

A: the problematic code is
new ProgressMonitorDialog(null).run(true, true, runnable);

this is called outside the ui-thread which throws the error...you have to wrap this also in a asyncExec Call


text:
Q: Quotes, italics, parentheses, and/or regular for translations Okay Stack Exchange, here's the big ask:
What do you all recommend? My manager wants to know if this is stylistically appropriate. No specific manual we're looking at here. Just what would you guys think if you saw this on a business card. I'm using another Latin phrase instead of the actual company name, per my boss' direction, but the question is still the same. The name of the company is, in medias res. Below is how the text looks now on a business card.
in medias res
"in the middle"
I'm pretty certain the Latin words italicized is common; however, I'm skeptical about the quotes around the translation. The company's name is the Latin phrase, not the English translation. The goal is just to make sure that people who've never heard of the Latin phrase understand it.

A: The short answer is yes. And no.
This comes down completely to style and personal opinion—and what one person believes may be completely different from what another person believes.
Even the two most common style guides in North America give different guidance.
According to The Chicago Manual of Style (17th ed.), 7.53:

Use italics for isolated words and phrases from another language unless they appear in Webster's or another standard English-language dictionary.

And, from an example, the English translation is in parentheses in roman type:

The word he used, Kaffeetasse (coffee cup), was just accurate enough to gain the desired result.

But according to the Associated Press Stylebook:

AP does not italicize words in news stories. Italics are used in Stylebook entries to highlight examples of correct and incorrect usage.

And this:

I have a book review that refers to Castro as El Presidente. Would AP cap that term? And, since we use italics to indicate foreign words that are italicized in Webster's, would this get italicized?
from Farmington, Maine on March 08, 2013
AP Spanish language stories lowercase el presidente preceding a name. Your call on italics. AP doesn't use italics in news stories.

Also this, which is related to the translation:

When quoting a text message, how should the spelling and capitalization be rendered? As it was sent? (Her last text to him was "cu l8ter.") In normal English? (Her last text to him was "See you later.") Or a combination? (Her last text to him was "cu l8ter," shorthand for "see you later.")
from New York, NY on July 09, 2009
We don't see many of these yet. But I like the last solution with a translation.

Based purely on those style guide entries, the phrase might appear styled in one of two ways.
Chicago:

in medias res (in the middle)

AP:

"In medias res," Latin for "in the middle."

But italics aside (which is treated different by each guide), neither guide gives specific guidance on how to present or style the English translation that follows the Latin—they simply give an example, which may or may not be taken as authoritative according to them.
This also doesn't mention the fact that your company name is presented in lowercase rather than in title caps (which would make it In Medias Res, either in italics or roman text).
In your case, you're not even talking about narrative text (as would Chicago mainly refer to) or news stories (as would covered by AP). Instead, you're talking about business cards. I don't know of any style guide that covers business cards specifically.
In short, there is no answer that can be given here that really helps you decide what you should be doing for your own company's business cards.

For what it's worth, here is my personal opinion: have it match whatever is on your letterhead and other correspondence.
I'm assuming that you're using in media res rather than In Media Res because your company already decided to use lowercase for the company name. Since you're using the same capitalization on the business cards as is used elsewhere, I would maintain consistency when it comes to the type on your business cards.
If the name of the company is in roman type on your letterhead, then keep it in roman type on your business cards. I think it would be strange to have it styled differently from one medium to the next.
Similarly, and for the same reasoning, if the translation of the phrase doesn't appear on your letterhead, then don't have appear on your business cards.
However, that's far from any kind of authoritative statement. I've seen many companies put things on their business cards that aren't used elsewhere. So, if a translation makes sense in your case, you should provide one. I just can't say how you should style it.
Perhaps at the very least, a business card it should be catchy. So, everything else being equal, if a particular style isn't catchy, it's probably not a style you should use.


text:
Q: django: how to know if a model is created with a m2m field not None So basically I am trying to override the save method of a model to tell if a certain non-required field, which is a m2m field, is specified. If so, then update one of its own Boolean field to True. Currently I have something like this:
class Flag(models.Model):
    name = models.CharField(max_length=300)
    def __str__(self):
        return self.name

class Model(models.Model):
    BooleanField = models.BooleanField(default = False)
    m2mField = models.ManyToManyField(Flag)

    def save(self, *args, **kwargs):
            super(Model, self).save(*args, **kwargs)
            if Model.objects.filter(id = self.id, m2mField = None).exists():
                Model.objects.filter(id = self.id).update(BooleanField = True)

And this is not working for me now. I don't really care what is in the m2m field, just trying to know if that field is specified by user when creating this instance.
TIA
Edit: I update with a more realistic definition.

A: You could try checking if the m2mField count is more than 0, like so:
class Model(models.Model):
    BooleanField = models.BooleanField(default = False)
    m2mField = models.ManyToManyField(Flag, blank=True)

    def save(self, *args, **kwargs):
        self.BooleanField = True if self.pk is not None and self.m2mField.count() > 0 else False
        super(Model, self).save(*args, **kwargs)

It would probably a good idea to pass the blank=True argument to the m2mField.


text:
Q: What is the correct way to obtain (-1)^n? Many algorithms require to compute (-1)^n (both integer), usually as a factor in a series. That is, a factor that is -1 for odd n and 1 for even n. In a C++ environment, one often sees:
#include<iostream>
#include<cmath>
int main(){
   int n = 13;
   std::cout << std::pow(-1, n) << std::endl;
}

What is better or the usual convention? (or something else),
std::pow(-1, n)
std::pow(-1, n%2)
(n%2?-1:1)
(1-2*(n%2))  // (gives incorrect value for negative n)

EDIT:
In addition, user @SeverinPappadeux proposed another alternative based on (a global?) array lookups. My version of it is:
const int res[] {-1, 1, -1}; // three elements are needed for negative modulo results
const int* const m1pow = res + 1;
...
m1pow[n%2]

This is not probably not going to settle the question but, by using the emitted code we can discard some options.
First without optimization, the final contenders are:
   1 - ((n & 1) << 1);

(7 operation, no memory access)
  mov eax, DWORD PTR [rbp-20]
  add eax, eax
  and eax, 2
  mov edx, 1
  sub edx, eax
  mov eax, edx
  mov DWORD PTR [rbp-16], eax

and
   retvals[n&1];

(5 operations, memory --registers?-- access)
  mov eax, DWORD PTR [rbp-20]
  and eax, 1
  cdqe
  mov eax, DWORD PTR main::retvals[0+rax*4]
  mov DWORD PTR [rbp-8], eax

Now with optimization (-O3)
   1 - ((n & 1) << 1);

(4 operation, no memory access)
  add edx, edx
  mov ebp, 1
  and edx, 2
  sub ebp, edx

.
  retvals[n&1];

(4 operations, memory --registers?-- access)
  mov eax, edx
  and eax, 1
  movsx rcx, eax
  mov r12d, DWORD PTR main::retvals[0+rcx*4]

.
   n%2?-1:1;

(4 operations, no memory access)
  cmp eax, 1
  sbb ebx, ebx
  and ebx, 2
  sub ebx, 1

The test are here. I had to some some acrobatics to have meaningful code that doesn't elide operations all together.
Conclusion (for now)
So at the end it depends on the level optimization and expressiveness:

*

*1 - ((n & 1) << 1); is always good but not very expressive.

*retvals[n&1]; pays a price for memory access.

*n%2?-1:1; is expressive and good but only with optimization.

A: First of all, the fastest isOdd test I do know (in an inline method)
/**
* Return true if the value is odd
* @value the value to check
*/
inline bool isOdd(int value)
{
return (value & 1);
}

Then make use of this test to return -1 if odd, 1 otherwise (which is the actual output of (-1)^N )
/**
* Return the computation of (-1)^N
* @n the N factor
*/
inline int minusOneToN(int n)
{
return isOdd(n)?-1:1;
}

Last as suggested @Guvante, you can spare a multiplication just flipping the sign of a value (avoiding using the minusOneToN function)
/**
* Example of the general usage. Avoids a useless multiplication
* @value The value to flip if it is odd
*/
inline int flipSignIfOdd(int value)
{
return isOdd(value)?-value:value;
}

A: You can use (n & 1) instead of n % 2 and << 1 instead of * 2 if you want to be super-pedantic, er I mean optimized.
So the fastest way to compute in an 8086 processor is:
1 - ((n & 1) << 1)
I just want to clarify where this answer is coming from. The original poster alfC did an excellent job of posting a lot of different ways to compute (-1)^n some being faster than others.
Nowadays with processors being as fast as they are and optimizing compilers being as good as they are we usually value readability over the slight (even negligible) improvements from shaving a few CPU cycles from an operation.
There was a time when one pass compilers ruled the earth and MUL operations were new and decadent; in those days a power of 2 operation was an invitation for gratuitous optimization.

A: Usually you don't actually calculate (-1)^n, instead you track the current sign (as a number being either -1 or 1) and flip it every operation (sign = -sign), do this as you handle your n in order and you will get the same result.
EDIT: Note that part of the reason I recommend this is because there is rarely actually semantic value is the representation (-1)^n it is merely a convenient method of flipping the sign between iterations.

A:
Many algorithms require to compute (-1)^n (both integer), usually as a
  factor in a series. That is, a factor that is -1 for odd n and 1 for
  even n.

Consider evaluating the series as a function of -x instead.

A: If it's speed you need, here goes ...
int inline minus_1_pow(int n) {
    static const int retvals[] {1, -1};
    return retvals[n&1];
}

The Visual C++ compiler with optimization turned to 11 compiles this down to two machine instructions, neither of which is a branch. It optimizes-away the retvals array also, so no cache misses.

A: What about
(1 - (n%2)) - (n%2)

n%2 most likely will be computed only once
UPDATE
Actually, simplest and most correct way would be using table
const int res[] {-1, 1, -1};

return res[n%2 + 1];

A: Well if we are performing the calculation in a series, why not handle the calculation in a positive loop and a negative loop, skipping the evaluation completely?
The Taylor series expansion to approximate the natural log of (1+x) is a perfect example of this type of problem. Each term has (-1)^(n+1), or (1)^(n-1). There is no need to calculate this factor. You can "slice" the problem by either executing 1 loop for every two terms, or two loops, one for the odd terms and one for the even terms.
Of course, since the calculation, by its nature, is one over the domain of real numbers, you will be using a floating point processor to evaluate the individual terms anyway. Once you have decided to do that, you should just use the library implementation for the natural logarithm. But if for some reason, you decide not to, it will certainly be faster, but not by much, not to waste cycles calculating the value of -1 to the nth power.
Perhaps each can even be done in separate threads. Maybe the problem can be vectorized, even.


text:
Q: How to plot dotted lines \begin{tikzpicture}
  \begin{axis}[
      axis x line = middle,
      axis y line = center,
      axis line style = {-},
      xlabel = $$,
      ylabel = $$,
      xmin = -2*pi,
      xmax = 2*pi,
      clip=false,
      xtick = {-6.2832, -4.7124, -3.1416, -1.5708, 0, 1.5708, 3.1416, 4.7124, 6.2832},
      xticklabels = {${-2\pi}$, ${-\frac{3\pi}2}$, ${-\pi}$, ${-\frac{\pi}2}$, ${0}$, ${\frac\pi2}$, ${\ \ \pi}$, ${\frac{3\pi}2}$, ${2\pi}$},
      ymin = -1,
      ymax = 1,
      ytick={-1,0,1},
      yticklabels={,,},
      height = 10em,
      width = 28em,
    ]
    \addplot+[
      black,
      mark=none,
      const plot,
    ]
    coordinates {(-2*pi,1) (-pi,1) (-pi,-1) (0,-1) (0,1) (pi,1) (pi,-1) (2*pi,-1)};
    \path (axis cs:0,0)
      node [anchor=south west,yshift=-0.65em,xshift=-0.585em,font=\normalsize] {0};
  \end{axis}
\end{tikzpicture}

Generates this square wave:

But I'd like to make the vertical lines dotted or dashed, to get something like

(Sorry for the terrible illustration)
How can I accomplish this?

A: You can group your coordinates, insert empty lines and use empty lines = jump. Then draw two plots, one for the horizontal lines and one for the vertical ones. Add dotted for the second plot.

\documentclass[border=1mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      axis x line = middle,
      axis y line = center,
      axis line style = {-},
      % no y axis
      %y axis line style = {draw=none},
      xlabel = $$,
      ylabel = $$,
      xmin = -2*pi,
      xmax = 2*pi,
      clip=false,
      xtick = {-6.2832, -4.7124, -3.1416, -1.5708, 0, 1.5708, 3.1416, 4.7124, 6.2832},
      xticklabels = {${-2\pi}$, ${-\frac{3\pi}2}$, ${-\pi}$, ${-\frac{\pi}2}$, ${0}$, ${\frac\pi2}$, ${\ \ \pi}$, ${\frac{3\pi}2}$, ${2\pi}$},
      ymin = -1,
      ymax = 1,
      ytick={-1,0,1},
      yticklabels={,,},
      height = 10em,
      width = 28em,
    ]
    % horizontal parts
    \addplot+[
      red,very thick,
      mark=none,
      const plot,
      empty line=jump,
    ]
    coordinates {
        (-2*pi,1)
        (-pi,1)

        (-pi,-1)
        (0,-1)

        (0,1)
        (pi,1)

        (pi,-1)
        (2*pi,-1)
    };
    % vertical parts
    \addplot+[
      red,very thick,dotted,
      mark=none,
      const plot,
      empty line=jump,
    ]
    coordinates {
        (-pi,1)
        (-pi,-1)

        (0,-1)
        (0,1)

        (pi,1)
        (pi,-1)
    };
    \path (axis cs:0,0)
      node [anchor=south west,yshift=-0.65em,xshift=-0.585em,font=\normalsize] {0};
  \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Is the state returned from the useReducer Hook a "deep copy" or a reference of a reducers output? I'm currently implementing global state handling in React using the Context API in combination with the useReducer hook.
I have two concerns regarding mutability:

*

*When updating state in my reducers, do I need to e.g use Lodash's cloneDeep function to sever the reference between the objects going into my reducer and the stored state?

*Is it possible to ruin the global state by manually mutating it outside reducers, or will it behave like "normal React state" in the sense that manual mutations will get overwritten during the next update cycle?

For reference: docs

A: Both useState and useReducer give you the exact value reference that you saved (either by calling someSetter(newValue), or returning a value from the reducer function).
In either case, manually mutating the value is wrong.  In particular, both of them will bail out of updates if you return the identical reference as last time, so you should always update values immutably.

A: I would give this a read.
https://kentcdodds.com/blog/how-to-use-react-context-effectively
This is a really good guide of how to use react context in conjunction with useReducer the right way.
Let me know if it helps.


text:
Q: Run curl command to load data to hdfs via python/jython Unable to download the file to hdfs if the url contains spaces when we are executing the jython/python
For example : URL Contains spaces in the file name and directory path
> http://www.example.com/a bc/def/c h.csv

Command i tried with the url by escaping spaces with %20 or + symbol both didn't work.
executing below command by opening the shell in python like below. If the url doesn't contain spaces it happens correctly.
curl http://www.example.com/a bc/def/c h.csv | hadoop fs -put -f - /xyz/c h.csv

A: What about escaping the spaces with backslashes? Or surrounding the URL with quotation marks? Try:
http://www.example.com/a\ bc/def/c\ h.csv or "http://www.example.com/a bc/def/c h.csv"


text:
Q: Computer graphing utilities I have developed a system in R for graphing large datasets obtained from wind turbines. I am now porting the process into Java. The results I get between the two systems are inconsistent.
As shown below:

*

*The dataset is first plotted using using R, and secondly using JFreeChart.

*The red line in both graphs correspond to my respective calculations in each language (which are detailed below).

*The brown dashed line in #1 corresponds to the blue line in #2, there are no discrepancies here, they are provided for reference

*The shaded area represent the data points, grey in #1 and red in #2.

I can explain the discrepancies between the (red) calculated lines and that is due to the fact that I am using different calculation methods.
In R the data is processed as follows, I wrote this code with a little help and have no idea what is going on here (but hey, it works).
df <- data.frame(pwr = pwr, spd = spd)
require(mgcv)
mod <- gam(pwr ~ s(spd, bs = "ad", k = 20), data = df, method = "REML")
summary(mod)
x_grid <- with(df, data.frame(spd = seq(min(spd) + 0.0001, maxi, length=100)))
pred <- predict(mod, x_grid, se.fit = TRUE)
x_grid <- within(x_grid, fit <- pred$fit)
lines(fit ~ spd, data = x_grid, col = "red", lwd = thickLineWidth)

In Java (SQL infact) I am using the method of bins to calculate the average at every 0.5 on the x-axis. The resulting data is plotted using a  org.jfree.chart.renderer.xy.XYSplineRenderer I do not know too much about how the line is rendered.
SELECT
    ROUND( ROUND( x_data * 2 ) / 2, 1)   AS x_axis, # See https://stackoverflow.com/questions/5230647/mysql-rounding-functions
    AVG( y_data )                        AS y_axis
FROM
    table
GROUP BY
    x_axis

My take on the variance between the two graphs:

*

*Presence of a single outlier at 18 on the x_axis (most visible on the R graph) seems to have an enormous impact on the shape of the curve.

*Even between 5 and 15 on the x-axis it seems that the line in the R graph is more continuous, it doesn't change trajectory as readily as that produced by Java.

*The 'crater' evident at 18 on the java x-axis has to 'mounds' each side of it, I believe this is due to polynomial effects in the rendering system.

These are things that I would like to eliminate.
So in an effort to understand the difference between the two graphs I have a few questions:

*

*Exactly what is going on in my R script?

*How can I, or, do I want to port the same process to my Java code?

*Can anyone explain the spline system used by JFreeCharts, is there another?

A: In the R code, you are (well I was when I showed the example) fitting an additive model to the power and speed data, where the relationship between the variables is determined from the data themselves. These models involve the use of splines to estimate the response function. In particular here I used an adaptive smoother with k = 20 the complexity of the smoother fitting. The more complex the smoother, the more wiggly the fitted function can be. An adaptive smoother is one where the degree of smoothness varies across the fitted function.
Why is this important? Well, from your data, there are periods where the response does not vary with the speed variable, and periods where the response changes rapidly with a change in speed. We have an "allowance" of wigglyness to use up over the curve. With ordinary splines the wigglyness (or smoothness) is the same across the entire function. With an adaptive smooth we can use more of our wigglyness allowance in the parts of the function where the response is changing/varying most, and not spend any of the allowance where it is not needed in the parts where the response isn't changing.
Below I annotate the code to explain what is being done at each step:
## here we create a data frame with the pwr and spd variables
df <- data.frame(pwr = pwr, spd = spd)

## we load the package containing the code to fit the additive model
require(mgcv)

## This is the model itself, saying pwr is modelled as a smooth function of spd
## and the smooth function of spd is generated using an adaptive smoother with
## and "allowance" of 20. This allowance is a starting point and the actual
## smoothness of the curve will be estimated as part of the model fitting,
## here using a REML criterion
mod <- gam(pwr ~ s(spd, bs = "ad", k = 20), data = df, method = "REML")

## This just summarise the model fit
summary(mod)

## In this line we are creating a new spd vector (in a data frame) that contains
## 100 equally spaced spd values over the entire range of the observed spd
x_grid <- with(df, data.frame(spd = seq(min(spd) + 0.0001, maxi, length=100)))

## we will use those data to get predictions of the response pwr at each
## of the 100 values of spd we just created
## I did this so we had enough data to plot a nice smooth curve, but without
## having to predict for all the observed values of spd
pred <- predict(mod, x_grid, se.fit = TRUE)

## This line stores the 100 predicted values in the prediction data object
x_grid <- within(x_grid, fit <- pred$fit)

## This line draws the fitted smooth on to a plot of the data
## this assumes there is already a plot on the active device.
lines(fit ~ spd, data = x_grid, col = "red", lwd = thickLineWidth)

If you are not familiar with additive models and smoothers/splines then I recommend Ruppert, Wand and Carroll (2003) Semiparametric Regression. Cambridge University Press.


text:
Q: Powershell script halting and not working as expected I have written a script to get system variables and copy of several folders ,I wanted to create a directory for copy of several folders,to prevent duplication of folders we wanted a check condition so each time we run the script it is not creating folders. Like an example
     $nfle=New-Item -ItemType "Directory" -Path "D:\Temp\" -Name "foo"
        [bool]$checkfle=Test-Path "D:\Temp\foo" -PathType Any
         if ( $checkfle -eq $True)
    {
      Write-Output "$nfle Exists"
    }
    else
    {
   $bnfle=New-Item -ItemType "Directory" -Path "D:\Temp\" -Name ("boo")
    }
  $cpypste=Copy-Item "D:\Temp\foo" -destination "D:\Temp\boo"
  Write-Host "Succesful Copy of Folders"

So when we run the script it is creating folder foo,again when we run the script , it is displaying foo exists, and stopping the script is not going to next line, not even displaying the message.Is there a way in powershell to find out why the script is stopping or shall i add more information statements. TIA

A: It best to start with test-path to see if the folder is there. A "Container" is a folder/directory. Then check if you need to write the folder.
 # This should allow your script to continue of error.
 $ErrorActionPreference = "Continue"

 # check if "C:\Temp\Foo" exist. if not make C:\Temp\foo"

 $nfle = 'C:\Temp\foo'

 [bool]$checkfle = Test-Path $nfle -PathType Container
 if ( $checkfle -eq $True)
    {
        Write-Output "$nfle Exists"
    }
 else
    {
        New-Item -ItemType "Directory" -Path "C:\Temp\" -Name "foo"
    }

# check if "C:\Temp\boo" exist. if not make C:\Temp\boo"

$BooFilePath = "C:\Temp\boo"

[bool]$checkboo = Test-Path $BooFilePath -PathType Container

 if ( $checkboo -eq $True)
    {
        Write-Output " $BooFilePath Exists"
    }
 else
    {
        New-Item -ItemType "Directory" -Path "C:\Temp\" -Name "boo"
    }

# This makes the folder C:\Temp\boo\foo.
# $cpypste = Copy-Item -Path "C:\Temp\foo\" -destination "C:\Temp\boo\"

# If you want copy the contents of foo into boo you will need * or -recurse
$cpypste = Copy-Item -Path "C:\Temp\foo\*" -destination "C:\Temp\boo\" -PassThru

Write-Host "Succesful Copy of Folders"
$cpypste.FullName

A: I have tried the demo provided and it works from my side, multiple times, so I was not able to re-create the problem.
If you would like to debug scripts in PowwerShell, you may follow this link:
https://learn.microsoft.com/en-us/powershell/scripting/components/ise/how-to-debug-scripts-in-windows-powershell-ise?view=powershell-6
I am not sure, why you are storing the result of Copy-Item into a variable, as it is null?
Hope it helps!


text:
Q: Tkz-fct can't run in another drive (Windows User) I try to run tkz-fct in drive D with location
D:\latexrun but it can not work. Then I notice that package only run well in drive C as my Miktex location in C:\Program Files\MiKTeX 2.9 and in C:\Users\user\AppData\Roaming\MiKTeX .
In drive D the message show :
! Undefined control sequence.
l.10 \tkzSetUpColors
! Undefined control sequence.
l.17 \tkzAxeY
!  Undefined control sequence.
l.19 \tkzDefPoint
Undefined control sequence.
\pgfutil@reserved@c ->\tkzActivOff
! File ended while scanning use of \pgfkeys@code.

This is sample I got from    author's site which is run well in drive C but not in drive D.
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
 \usepackage[upright]{fourier}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{fullpage,amsmath,tkz-fct}
\definecolor{fondpaille}{cmyk}{0,0,0.1,0}
\pagecolor{fondpaille}
\color{Maroon}
\tkzSetUpColors[background=fondpaille,text=Maroon]
\thispagestyle{empty}

\begin{document}

\begin{tikzpicture}[scale=3]
\tkzInit[xmax=3,ymax=2];
\tkzAxeX
\tkzAxeY
\tkzGrid(0,0)(3,2)
\tkzFct[color  = red, domain = 1./3:3]{0.125*(3*\x-1)+0.375*(3*\x-1)/(\x*\x)}
\tkzDefPointByFct[draw](2)
\tkzDefPointByFct[draw](3)
\tkzDrawTangentLine[color = blue,line width = .8pt](1)
\tkzFct[color   = green, domain  =  1./3:3]{0.125*(3*x-1)}
\tkzSetUpPoint[size=8,fill=orange]
\tkzDefPointByFct[draw](3)
\tkzDefPointByFct[draw](1/3)
\tkzDefPoint(1,1){f}
\tkzDrawPoint(f)
\tkzText[draw,fill = red!20,text=red!50!black](1,1.5)%
{$f(x)=\dfrac{1}{8}(3x-1)+\dfrac{3}{8}\left(\dfrac{3x-1}{x^2}\right)$}
\tkzText[draw,fill = green!20,text=green!50!black](2,0.4){$g(x) = \dfrac{3x-1}{8}$}
\end{tikzpicture}
\end{document}

I have no problem calling gnuplot or another packages in drive D previously. I use Windows Vista Japanese Version SP2. Please help what should I do to make tkz-fct can run in another drive.


text:
Q: identify Blank Image Using Java Hi How can we identify Blank Image(White Image),
BufferReaderImage im = ImageIO.read("samplePath");

the image iam passing is empty with some height and width, i want to identify it

A: This link should help you get started:
Get RGB values of a BufferedImage
In particular, this is the relevant part:
BufferedImage image = ImageIO.read(
     new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

int w = image.getWidth();
int h = image.getHeight();

int[] dataBuffInt = image.getRGB(0, 0, w, h, null, 0, w);

Color c = new Color(dataBuffInt[100]);

System.out.println(c.getRed());   // = (dataBuffInt[100] >> 16) & 0xFF
System.out.println(c.getGreen()); // = (dataBuffInt[100] >> 8)  & 0xFF
System.out.println(c.getBlue());  // = (dataBuffInt[100] >> 0)  & 0xFF
System.out.println(c.getAlpha()); // = (dataBuffInt[100] >> 24) & 0xFF

Then go through all the entries and make sure there are some different values.


text:
Q: How to deploy Django application to EC2 of AWS Premise · What you want to realize
I would like to deploy django application to EC2 of AWS.
The server uses nginx.
I am also trying to do with uWSGI.
The virtual environment is made with virtualenv.
Thank you.
Problems occurring · Error messages
The process of nginx, wsgi is running, but localhost can not run the application.
If I hit curl it will get Internal Server Error.
log
!!! no internal routing support, rebuild with pcre support !!!
chdir() to /opt/app/apolo_api
your processes number limit is 3896
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: enabled
uWSGI http bound on :5001 fd 3
uwsgi socket 0 bound to UNIX address /tmp/uwsgi.sock fd 6
Python version: 3.5.1 (default, Sep 13 2016, 18:48:37)  [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)]
Set PythonHome to /opt/app/venv/
Python main interpreter initialized at 0x225ace0
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 166112 bytes (162 KB) for 2 cores
* Operational MODE: threaded *
added /opt/app/apolo_api/api/ to pythonpath.
unable to load app 0 (mountpoint='') (callable not found or import error)
* no app loaded. going in full dynamic mode *
* uWSGI is running in multiple interpreter mode *
spawned uWSGI master process (pid: 22526)
spawned uWSGI worker 1 (pid: 22527, cores: 2)
* Stats server enabled on /tmp/uwsgi.stats.sock fd: 12 *
spawned uWSGI http 1 (pid: 22528)

Probably
* No app loaded. Going in full dynamic mode *

It seems that it has stopped starting at the part of.
What I tried
Create /etc/init/uwsgi_myproject.conf file
Create /etc/init/uwsgi_myproject.conf file
description "uWSGI starter for myproject"

start on (local-filesystems and runlevel [2345])
stop on runlevel [016]

respawn

exec /usr/local/bin/uwsgi /etc/init/myproject.ini

Create /etc/init/myproject.ini file
[uwsgi]
chdir=/opt/app/myproject
module='myproject.wsgi:application'
socket = /tmp/uwsgi.sock
env DJANGO_SETTINGS_MODULE=myproject.settings
master = true
uid = nginx
gid = nginx
http = :5001
venv = /opt/app/venv/
python-path = /opt/app/apolo_api/api/
wsgi = app:app
processes = 1
threads = 2
stats = /tmp/uwsgi.stats.sock
memory-report = true
thunder-lock = true
max-requests = 500
max-requests-delta = 30
touch-reload=/tmp/.uwsgi_reload

Thank you.


text:
Q: WSO2 V3.0 CORS Issue When I am trying to integrate my react js application with the gateway I am facing CORS issue as below
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://IP:port/userme. (Reason: header 'access-control-allow-credentials' is not allowed according to header 'Access-Control-Allow-Headers' from CORS preflight response).
everything is working from curb & postman request but not from browser.
Curb request (successful request)
HTTP/1.1 200
X-Frame-Options: DENY
Access-Control-Expose-Headers:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: HEAD, DELETE, POST, GET, PATCH, PUT
X-Content-Type-Options: nosniff
Set-Cookie: JSESSIONID=37C2604B133C7B9D1345A9E13A878A36; Path=/; HttpOnly
Expires: 0
Pragma: no-cache
X-XSS-Protection: 1; mode=block
Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction,Authorization
Content-Type: application/json;charset=UTF-8
Date: Tue, 17 Mar 2020 16:26:14 GMT
Transfer-Encoding: chunked

A: Try
1) enabling access-control-allow-credentials and
2) adding access-control-allow-credentials to the Access-Control-Allow-Headers list in the configuration.

A: CORS is enabled by default for all APIs but you need to send following values in header earlier i was sending Access-Control-Allow-Headers and other values too which was causing issue....
    'Accept': 'application/json',
    'content-Type':'application/json',
    'Access-Control-Allow-Origin': '*',
    'Authorization' : 'Bearer '+token,


text:
Q: Dynamically change cell height programmatically I've tried plenty of answers on SO but nothing really worked. I'm probably doing something wrong so I need someone to point out what I'm doing wrong..
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"text : %@", self.cell.comment.text);

    NSString *text = self.cell.comment.text;
    CGFloat width = self.cell.frame.size.width;
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
    NSAttributedString *attributedText =
    [[NSAttributedString alloc] initWithString:text
                                    attributes:@{NSFontAttributeName: font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    CGFloat height = ceilf(size.height);

    return height;
}

I get "NSInvalidArgumentException" with reason "NSConcreteAttributedString initWithString:: nil value" because self.cell.comment.text isn't getting anything by the time I set cell height but it does come through just not when heightForRowAtIndexPath gets called.
Many people have commented on that answer that this method works just fine so I guess I'm missing something?
Edit
I'm setting self.cell.comment.text here -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{
static NSString *simpleTableIdentifier = @"cell";

self.cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (self.cell == nil) {
    self.cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

// Configure the cell

self.cell.comment.text = [object objectForKey:@"comment"];
[self.cell.comment sizeToFit];

return self.cell;}

A: Your problem as you already comment is that function heightForRowAtIndexPath is called before cells are populated.
For every cell that become visible it first call

*

*get height of this cell

*populate cell

So you know that
a) your text is not yet populated on the cell
b) some other text might be inside, because apple use reusable cells, so UITableView can grab some cell (with different text) and try to resize it and then populate it.
In your case it will grab some other text, resize cell to its size and then populate it with some other text that is (probably) different size then previous text.
But inside cell populations you set text from some business logic (maybe array?), and you can get same text in this method.
if cell population you call
cell.comment.text = [self.someArray getObjectAtIndex:index.row];

you call this in your heightForRowAtIndexPath method.
NSString *text = [self.someArray getObjectAtIndex:index.row];

I see your edit just call :
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

NSLog(@"text : %@", self.cell.comment.text);

NSString *text = [object objectForKey:@"comment"];;
CGFloat width = self.cell.frame.size.width;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
                                attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
CGSize size = rect.size;
CGFloat height = ceilf(size.height);

return height;
}

ADDITION :
Tel say you would like to have cells like this :
-------------------------
|  bla bla bla         |
------------------------
| second longer text   |
| over more line       |
------------------------

You need to have texts bla bla and "second longer text over more line" somewhere saved.
Let say you have array with size 2.
NSArray * myTextArray = @[@"bla bla", @"second longer text over more line"];

and when populating cells
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{
   static NSString *simpleTableIdentifier = @"cell";

   self.cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
   if (self.cell == nil) {
        self.cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault         reuseIdentifier:simpleTableIdentifier];
    }

    // Configure the cell

    self.cell.comment.text = [myTextArray objectAtIndex:indexPath.row];
    [self.cell.comment sizeToFit];

    return self.cell;
 }

because heightForRowAtIndexPath is called before cellForRowAtIndexPath we need to check text from business (array) side and not visual.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

   NSLog(@"text : %@", self.cell.comment.text); // -> this is null because cell is not populated yet.

   NSString *text = [myTextArray objectAtIndex:indexPath.row]; -> this is same text as we will take when populating cell and is not random.
   CGFloat width = self.cell.frame.size.width;
   UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
   NSAttributedString *attributedText =
   [[NSAttributedString alloc] initWithString:text
                                attributes:@{NSFontAttributeName: font}];
   CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
   CGSize size = rect.size;
   CGFloat height = ceilf(size.height);

   return height;
}

EXAMPLE :
#import "ViewController.h"

@interface ViewController ()

@property NSArray * myArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.myArray = @[@"Some short text",@"Some longer text that take some more space throw more lines",@"bfusdbfjdsfjs fj yfsdy fgsydu fyudsfy fyudsyu fdsy fuysdyuf ydsug fyu sdgyfgsuyff ius fhs fiusdhi ufdshu uifsd ufsdh hfiuds uifdsh fsduih ufdshu hfsd ifshui"];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *text = self.myArray[indexPath.row];
    CGFloat width = 300;
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
    NSAttributedString *attributedText =
    [[NSAttributedString alloc] initWithString:text
                                attributes:@{NSFontAttributeName: font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
    CGSize size = rect.size;
    CGFloat height = ceilf(size.height);

    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *simpleTableIdentifier = @"cell";

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    // Configure the cell

    cell.textLabel.text = self.myArray[indexPath.row];
    cell.textLabel.numberOfLines = 0;
    return cell;
}

this example works.

A: In heightForRowAtIndexPath:
For width, I think you can fix it, and don't need this line:
 CGFloat width = self.cell.frame.size.width;

For the comment text
NSString *text = self.cell.comment.text;

Try this
NSString *text = [object objectForKey:@"comment"];

A: Spent all day trying to figure this out and finally found out that the solution was super simple, I just needed to know how to use Parse better.
Thanks to Marko, I've learned how UITableView really works and that's great but the solution to my problem was a bit different.
As everyone suggested my problem was assuming that heightForRowAtIndexPath would get called after all cells are populated but I did not need an array to save objects or make any change. Parse apparently saves all retrieved objects before heightForRowAtIndexPath gets called and they're all in self.objects.
self.cell.comment.text = [self.objects objectAtIndex:indexPath.row];

And as Andy passionately suggested, I'm now using Auto-size UITableViewCell.
In your PFQueryTableViewController
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

PFObject *object = [self.objects objectAtIndex:indexPath.row];

if (object) {
    NSString *commentString = [self.objects[indexPath.row] objectForKey:@"comment"];

    NSLog(@"commentString : %@",commentString);

    CommentCell *cell = [[CommentCell alloc] init];
    cell.textLabel.text = commentString;

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    self.height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    self.height += 1;

}

return self.height;}

In your CustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {

    self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.textLabel.numberOfLines = 0;
    self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;

    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-6-[bodyLabel]-6-|" options:0 metrics:nil views:@{ @"bodyLabel": self.textLabel }]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[bodyLabel]-6-|" options:0 metrics:nil views:@{ @"bodyLabel": self.textLabel }]];

}

return self;}

 - (void)layoutSubviews{
[super layoutSubviews];

[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];

self.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.textLabel.frame);}

This definitely works.