text:
Q: jQuery template not using JSON passed from Classic ASP The problem
My jQuery template does not seem to be reading and/or building the html from the json that is passed to it. I cannot see, at which stage, the problem occurs.
The html

        <img src="<%= rsProd("Image") %>" alt="<%= rsProd("Description") %>" width="120" height="80" />

            Order: <input type="text" style="width:100px" id="txtOrder-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" name="txtOrder-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" value="<%= rsProd("ImageOrder") %>" class="listorder" maxlength="5" />

            <% if rsProd("ImageID") = rs("MainImage") then %>
            <button id="btnSetMain-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" name="btnSetMain-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" class="btn btn-primary btn-inverse btnSetMain" disabled="disabled">Current</button>
            <% else %>
            <button id="btnSetMain-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" name="btnSetMain-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" class="btn btn-primary btnSetMain">Set main</button>
            <% end if %>
            <button id="btnOrderRemove-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" name="btnOrderRemove-<%= rsProd("ImageID") %>-<%= rsProd("ImageOrder") %>" class="btn btn-warning btnOrderRemove">Remove</button>

The jQuery template

The returned JSON
{"result":
    {"0": {
          "imageurl": "\u002Fimages\u002Fmainimages\u002Fimage-01.jpg",
          "description": "",
          "imageid": 25,
          "imageorder": 1,
          "extracss": "",
          "Disabled": "",
          "text": "Set Main"
          },
     "1": {"imageurl": "\u002Fimages\u002Fmainimages\u002Fimage-02.jpg","description": "test","imageid": 17,"imageorder": 2,"extracss": "","Disabled": "","text": "Set Main"},
     "2": {"imageurl": "\u002Fimages\u002Fthumbnails\u002Fimage-03.jpg","description": "test","imageid": 15,"imageorder": 4,"extracss": "","Disabled": "","text": "Set Main"},
     "3": {"imageurl": "\u002Fimages\u002Fmainimages\u002Fimage-04.jpg","description": "","imageid": 24,"imageorder": 5,"extracss": "","Disabled": "","text": "Set Main"},
     "4": {"imageurl": "\u002Fimages\u002Fmainimages\u002Fimage-05.jpg","description": "test","imageid": 16,"imageorder": 7,"extracss": "","Disabled": "","text": "Set Main"}
    }
}

The jQuery code
The jQuery code that is run when the user clicks a button, this all works apart from the populating of the template
success:function(data, textStatus, jqXHR){
    $('#prodThumbs').empty();
    thumbs = data.items;
    $.template('thumbsTemplate');
    $('#imagesTemplate').tmpl(data.result).appendTo('#prodThumbs');
}

the data.result seems to be correctly producing the right json data from a correct json response, however the applying the data to the template doesn't seem to work
For completeness, i've attached the Classic ASP server side function.
set images = server.createObject("scripting.dictionary")
i = 0
While (NOT rsProd.EOF)

    set image = server.createObject("scripting.dictionary")
    image.Add "imageurl", rsProd("Image").value
    image.Add "description", rsProd("Description").value
    image.Add "imageid", rsProd("ImageID").value
    image.Add "imageorder", rsProd("ImageOrder").value
    if rsProd("ImageID").value = request.Form("main") then
        image.Add "extracss", "btn-inverse"
        image.Add "disabled", "disabled=disabled"
        image.Add "text", "Current"
    else
        image.Add "extracss", ""
        image.Add "Disabled", ""
        image.Add "text", "Set Main"
    end if

    images.Add i, image

    i = i + 1

rsProd.MoveNext()
Wend
result = (new JSON)("result", images, false)

rsProd.Close()
response.Write result
response.End

i'm using nested dictionaries to build an object that I can (and seems to) return correctly as JSON (using Michal Gabrukiewicz's ASP JSON utility class.)
I feel like i'm missing something really simple, however i've banged my head against the desk so much now, i can't see it.
The outcome
the html starts off as

the function
$('#images').empty();

leaves me with

the function
thumbs = data.images;

correctly stores the json, but then function
$('#imagesTemplate').tmpl(thumbs).appendTo('#images');

still leaves me with

A: Well I managed to fix this by using the following code, after nested dictionaries didn't appear to work
arraySize = 0
arraySize = (rsProd.RecordCount - 1)
dim imageArrays
redim imageArrays(arraySize)
set images = server.createObject("scripting.dictionary")
i = 0
While (NOT rsProd.EOF)

    set image = server.createObject("scripting.dictionary")
    image.Add "imageurl", rsProd("Image").value
    image.Add "description", rsProd("Description").value
    image.Add "imageid", rsProd("ImageID").value
    image.Add "imageorder", rsProd("ImageOrder").value
    if rsProd("ImageID").value = request.Form("main") then
        image.Add "extracss", "btn-inverse"
        image.Add "disabled", "disabled=disabled"
        image.Add "text", "Current"
    else
        image.Add "extracss", ""
        image.Add "disabled", ""
        image.Add "text", "Set Main"
    end if
    set imageArrays(i) = image
    i = i + 1

rsProd.MoveNext()
Wend
result = (new JSON)("result", imageArrays, false)

rsProd.Close()
response.Write result
response.End

I managed to assign each image dictionary to an index in an array, and then converted that array to JSON. I had already previously tried this method before but failed at this step
set imageArrays(i) = image

principally because i wasn't using the 'set' keyword
so some credit to @SearchAndResQ for telling me to use array of dictionaries in the comments which i had previously tried, but this made me look back at it again.


text:
Q: pool game in java how to put 15 balls I want to make pool game in java, I want to form 15 balls in a shape of pyramid that face up to left in center of table, but I don't know how to. I have to find the right coordinate of (x,y) to put balls in center of the table

I see someone code, and found this solutions.
  public class cek {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        for(int i=0;i<16;i++) {
           int row = (int) Math.floor((Math.sqrt(1+8*i)/ 2)); // Using quadratic equation formula

            int x = (- (10 * (5- row)));
           System.out.println(i);
           System.out.println(Math.sqrt(1 + 8 * i));
           System.out.println(x);
        }
    }

}

result :
0
1.0
-50
1
3.0
-40
2
4.123105625617661
-30
3
5.0
-30
4
5.744562646538029
-20
5
6.4031242374328485
-20
6
7.0
-20
7
7.54983443527075
-10
8
8.06225774829855
-10
9
8.54400374531753
-10
10
9.0
-10
11
9.433981132056603
0
12
9.848857801796104
0
13
10.246950765959598
0
14
10.63014581273465
0
15
11.0
0

first ball [0]: -50

ball 1-15:
-40,-30,-30,-20,-20,-20,-10,-10,-10,-10,0,0,0,0

as you can see this could produce x coordinate for balls 1-15 like in first row 1 balls, second row 2 balls, third row 3 balls, 4th row 4 ball, 5th row 5th balls, but how can he come up with that solution and equation??
even after i see the solutions, i think it take me 1 day long to just figure out that code
and I am thinking I will never come up with that solution
especially
int row = (int) Math.floor((Math.sqrt(1+8*i)/ 2));
im trying to produce code above, this all i can think..
for(int i=0;i<5;i++){
               k=2*i+1-i;//10 20 30 40  50
               int x=-(n*10)+k*10;
               System.out.println(k);
               System.out.println(x);
               for(int r=1;r<k;r++) {
                  System.out.println(x);
              }

        }

but if i want to call ball class with parameter 1-15 and make object of new ball from it from another class, and the ball class will set (x,y) coordinate for each 1-15 balls in constructor.. this wont work..
int row = (int) Math.floor((Math.sqrt(1+8*i)/ 2)); // Using quadratic equation formula

this work..
update:
by using trigonometry to arrange the pyramid ball
i manage to make

     private double rowx(int rowNumber) {
            return rowNumber * (Math.sqrt(5) * r);
        }

     private void generateBalls(){
       balls=new ArrayList<Ball2>();
       int ballid=0;
       indexOfWhiteBall=0;
       if (balls.size()==0)
       {
          int x= Helper.BX + Helper.SW / 4 - r;
          int y = Helper.BY + Helper.SH / 2 - r;
          Ball2 balle=new Ball2(pinball,ballid,(Helper.BX + Helper.SW / 4 - r),Helper.BY + Helper.SH / 2 - r,r);
          balls.add(balle);
          balls.get(0).iswhiteball=true;
          ballid++;

       }
        for(int i=0;i<5;i++) {
          double y= rowx(i);
          for(double x:rowY(i)) {

              Ball2 balle=new Ball2(pinball,ballid,(Helper.BX + (2.5*Helper.SW)/4 ) +y,(Helper.BY + Helper.SH / 2) +x,r);
              balls.add(balle);
              ballid++;
              System.out.print(balle + " ");

          }
      }
    }
     private double[] rowY(int rownum) {

            switch(rownum) {
         case 0: return new double[] {0};
         case 1:return new double[] {-r,r};
         case 2:return new double[] {-2*r,0,2*r};
         case 3: return new double[] {-3*r, -r, r, 3*r};
         case 4: return new double[] {-4*r, -2*r, 0, 2*r, 4*r};
         case 5:return new double[] {Helper.BX + Helper.SW / 4 - r};
         default:throw new IllegalArgumentException("no more than 5");
            }
        }

A:
As you can see if you link the centres of the circles, you get equilateral triangles.
Considering the small one on top. It has sides of size 2*r, and its height h can be calculated using the Pythagoras theorem: h^2 = r^2 + (2*r)^2. So h = sqrt(5) * r, so that is the y coordinate for the second row.
Also the balls are shifted on the x axis by r
So if the first ball centre is (0, 0), the centres of 2 balls on the second row are (-r, sqrt(5)*r) and (r, sqrt(5)*r).
You can now apply the same principle and calculate the centres of the other balls.
So now, please provide some code to implement this (by editing your question). If you show effort, we can help you further to get the code right.
Implementation
Assuming you have a Ball class as follows:
class Ball {
    private final int id;
    private final double x, y;

    public Ball(int id, double x, double y) {
        this.id = id;
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Ball{ id=" + id +"(x=" + x +", y=" + y + ") }";
    }
}

You can have a setupBalls on your Pool class that reads like this: (I added printlns to help understand how it goes, all balls are added to the  balls list)
public class Pool {

    private static double r = 20;

    private void setupBalls() {
        List<Ball> balls = new ArrayList<>();
        int ballId = 0;

        // for each row
        for(int rowNumber = 0; rowNumber<5; rowNumber++) {
            System.out.print("Row "+rowNumber + ": ");

            // get the Xs of the balls in that row,
            // and create a ball for each
            double y = rowY(rowNumber);
            for(double x : rowXs(rowNumber)) {
                Ball ball = new Ball(ballId, x, y);
                balls.add(ball);
                System.out.print(ball + " ");
                ballId++;
            }

            System.out.println();
        }
    }

    // Returns the Y of a given row
    private double rowY(int rowNumber) {
        return rowNumber * (Math.sqrt(5) * r);
    }

   // Returns the list of the Xs for the balls on the given row
   private double[] rowXs(int rowNumber) {
        switch (rowNumber) {
            case 0: return new double[] {0};
            case 1: return new double[] {-r, r};
            case 2: return new double[] {-2*r, 0, 2*r};
            case 3: return new double[] {-3*r, -r, r, 3*r};
            case 4: return new double[] {-4*r, -2*r, 0, 2*r, 4*r};
            default: throw new IllegalArgumentException("no more than 5 rows");
        }
    }

}

Then use it like this:
public static void main(String[] args) {
    new Pool().setupBalls();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checking if a node.js app has started properly using bash I wrote a node.js application and have written a bash script to start it and verify if it's running. I have my script run npm start & first, then I have a check to see if the ports I want open are open using netstat. The check works fine when I run it after the script is run, but during the running of the script, the check fails because the server has not fully started before the check is run. My code is below:
echo "Starting the server..."
npm start & > /dev/null 2>&1
if [[ -z $(sudo netstat -tulpn | grep :$portNum | grep node) ]] ; then
    echo -e "\tPort $portNum is not in use, something went wrong. Exiting."
else
    echo -e "\tPort $portNum is in use!"
fi

Is there a good way to take the above script and change it so that the check doesn't occur until the server is fully started? I don't want to use sleep if I can help it.

A: You can use a wait call:
echo "Starting the server..."
npm start & > /dev/null 2>&1
wait
if [[ -z $(sudo netstat -tulpn | grep :$portNum | grep node) ]] ; then
    echo -e "\tPort $portNum is not in use, something went wrong. Exiting."
else
    echo -e "\tPort $portNum is in use!"
fi

The only limitation to this is that if npm daemonizes itself then it's no longer a child of the script so the wait command will have no effect (the reason for this is that a process daemonizes itself by terminating and spawning a new process that inherits its role).


text:
Q: Existence of source/sink in directed acyclic graph with connected complement The statement I would like to prove is the following:

For any connected acyclic digraph $G=(V,E)$ there exists a
source or sink vertex $v\in V$ such that the graph complementary to
that vertex, namely $G_v=(V\setminus\{v\},E\setminus\delta(v))$, is
connected.

$\delta(v)$ is the set of edges adjacent to the vertex $v$.
The proof technique I have in mind is something on the lines of the following: we need to have a source or sink $v_1$ in the graph $G$. If its complement is connected, then we are done. If it is not, we consider the $m_1$ connected components attaching to that vertex. Each of these connected components is also an acyclic digraph. So they must have a sink or a source. Say we choose one of those, $v_2$, for one of the $m_1$ connected components, $G_2$. If its complement is connected, we are done. If it is not, then $m_2$ connected components (of $G_2$) must attach to $v_2$. We can iterate the argument, which must end because the number of vertices is finite, and we are guaranteed to end up with a source or sink satisfying the hypothesised property.
I think this argument works, but I also think it is a bit clunky, so I am wondering if anyone has an easier way to prove it.


text: Q: Qt data visualization background image and transparency support Does the data visualization module support background image especially Surface3D element , also is there any why to apply transparency to plot color. Basically I need to place an image on x-z plane and draw surface plot above it with some transparency, so the user can see the background image through the surface plot.


text:
Q: Do web browsers check the hosts file before refering to their DNS cache? On a client machine such as OSX or Windows:
Do web browsers check the hosts file before refering to their DNS cache?
I am trying to figure out the full DNS 'route' in my mind.

*

*Hosts File

*Browser DNS Cache

*Local DNS Cache

*DNS Server

*Root Hints or Forwarding

Does it differ between browsers and OSs?

A: Browsers generally do not do anything except asking the IP library of the operating system to resolve a host name. So the normal behavior of ANY IP based program applies.

A: If you are on UNIX systems like me on Debian, the first thing which is checked is the /etc/hosts file.

A: On a Windows machine, hosts file entries are loaded into the DNS cache.


text:
Q: Python 3.6 - Altair Chart Prints Object, Not Graph What can cause graph objects to not display the actual graph, but a chart? Reproducible example below.
from pydataset import data
import altair

cars = data('cars')

cars

c = altair.Chart(cars).mark_line().encode(
    x='speed',
    y='dist'
)

Outputs
Chart({
  data:     speed  dist
  1       4     2
  2       4    10
  3       7     4
  4       7    22
  5       8    16
...
encoding: FacetedEncoding({
    x: X({
      shorthand: 'speed'
    }),
    y: Y({
      shorthand: 'dist'
    })
  }),
  mark: 'line'
})

Expected output is a graph, such as the one shown here https://altair-viz.github.io/user_guide/troubleshooting.html#display-troubleshooting
Obviously I've read the trouble shooting, but it isn't clear to me this problem.  They talk about getting no output, but not about getting the object as an output.
Edit to clarify : They DO talk about that, but specifically if using Jupyter Notebook and IPython being underversioned.  I have Jupyter installed, but am not using. I have IPython installed, but not underversioned.

A:
I have Jupyter installed, but am not using.

If you are not using Jupyter notebook. JupyterLab, or a similar notebook environment, then you will need some other Javascript-enabled frontend in which to render your charts. You can find more information on this at https://altair-viz.github.io/user_guide/display_frontends.html#display-general.


text:
Q: Cant find facebook post id using js sdk Hey guys i have been trying to fetch the post id from the response. My code is
function testAPI() {

 var body = 'Reading JS SDK documentation';

FB.api('/me/feed', 'post', { message: body }, function(response) {

  if (!response || response.error) {

  } else {

console.log(response);

}

)};

}

When i check the console i didnt find the details of message object..Is it a bug ??What i need is to print the message id and the message on the console .Can i do this with facebook js-sdk ?..If am doing any wrong please help me to do this rightly ..Any help would be appreciated ..Thanks..

A: I've just tried your code - it looks like there's a syntax error. You need to remove the second to last }.
Removing that and re-formatting the code will enable you to get the id successfully - I just tried it. The fixed code is below:
function testAPI() {

var body = 'Reading JS SDK documentation';

  FB.api('/me/feed', 'post', { message: body }, function(response) {
    if (!response || response.error) {
    } else {
      console.log(response); //
    }
  });

}


text:
Q: convert java timestamp string to java timestamp object I have following timestamp string "2021010112:12:12.10:00" and I want to convert it to java.time.Instant.
The issue in parsing string through DateTimeFormatter is due to absence of time zone sign before last 4 digits. Logically it is yyyyMMddHH:mm:ss. and 10:00 is time zone offset e.g UTC+10:00, but issue is it does not have sign.
How can I parse this string to Instant object?

A: Not very elegant, but you could split the input by a dot. That would separate the datetime part from the offset and you can concatenate the desired (and required) sign with the value.
This requires you to know which sign to apply! The code cannot guess it...
Maybe write a method that takes this input String and a sign to be applied as arguments.
Since it seems not possible to parse an unsigned String representation of an offset, you would need something like the following:
public static void main(String[] args) {
    String timestamp = "2021010112:12:12.10:00";
    // provide a formatter that parses the datetime (the part before the dot)
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ss");
    // split the timestamp String by the dot to separate datetime from offset
    String[] split = timestamp.split("\\.");
    // parse the datetime part using the formatter defined above
    LocalDateTime ldt = LocalDateTime.parse(split[0], dtf);
    // and build up an offset using offset part adding a plus sign
    ZoneOffset zoneOffset = ZoneOffset.of("+" + split[1]);
    // then create an OffsetDateTime from the LocalDateTime and the ZoneOffset
    OffsetDateTime result = OffsetDateTime.of(ldt, zoneOffset);
    // finally get an Instant from it
    Instant instant = result.toInstant();  // <--- INSTANT HERE
    // and print the values
    System.out.println(result + " = " + instant.toEpochMilli());
}

This outputs
2021-01-01T12:12:12+10:00 = 1609467132000

A: The answer by deHaar is correct. This answer shows an easier way of solving this problem.
You can use the regex, (\.)(\d{1,2}:\d{1,2}) to replace the . (group#1 in the regex) before the timezone offset part (group#2 in the regex) with a +.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2021010112:12:12.10:00";
        strDateTime = strDateTime.replaceFirst("(\\.)(\\d{1,2}:\\d{1,2})", "+$2");

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ssXXX", Locale.ENGLISH);
        Instant instant = OffsetDateTime.parse(strDateTime, dtf).toInstant();
        System.out.println(instant);
    }
}

Output:
2021-01-01T02:12:12Z

ONLINE DEMO
Alternatively, you can use the regex, \.(\d{1,2}:\d{1,2}) and prepend group#1 with a + sign. Note that the DateTimeFormatter needs to be adjusted accordingly.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2021010112:12:12.10:00";
        strDateTime = strDateTime.replaceFirst("\\.(\\d{1,2}:\\d{1,2})", ".+$1");

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ss.XXX", Locale.ENGLISH);
        Instant instant = OffsetDateTime.parse(strDateTime, dtf).toInstant();
        System.out.println(instant);
    }
}

ONLINE DEMO
The benefits of using this alternative solution is as described in the following comment by Ole V.V.:

Just speculating, maybe a minus sign would be present in case of a
negative UTC offset. If so, maybe use
strDateTime.replaceFirst("\\.(\\d{1,2}:\\d{1,2})", ".+$1") to obtain
2021010112:12:12.+10:00 in the positive offset case, after which both
positive and negative offset (and zero) could be parsed.

A: ParsePosition
There are two good answers already. Here's my suggestion.
    String timestampString = "2021010112:12:12.10:00";

    ParsePosition position = new ParsePosition(0);
    TemporalAccessor parsed = PARSER.parse(timestampString, position);
    LocalDateTime dateTime = LocalDateTime.from(parsed);

    String offsetString = timestampString.substring(position.getIndex());
    if (Character.isDigit(offsetString.charAt(0))) { // no sign
        offsetString = "+" + offsetString;
    }
    ZoneOffset offset = ZoneOffset.of(offsetString);

    Instant timestamp = dateTime.atOffset(offset).toInstant();

    System.out.println(timestamp);

Output:

2021-01-01T02:12:12Z

The downside is the use of the TemporalAccessor interface, a low-level interface that we should not normally use in application code. The upsides include that the code accepts strings with and without sign before the offset and we don't need any split operation or other application of regular expressions. If the UTC offset is negative, the sign must be there, or we can't tell. Let's also try this:
    String timestampString = "2021010112:12:12.-10:00";

2021-01-01T22:12:12Z

I believe that the ParsePosition class is the only class from the old java.text package that is reused in java.time, which I personally find curious.


text:
Q: Cannot move the "Click to Name" face circle in Photos for macOS I have many photos where the macOS Photos facial recognition / people album has not recognized a face.
I press ⌘I to show the Info pallet, then press + Add Faces to add a face circle to the Photo.
The face circle says "Click to Name" and I should be able to move and resize it.
I cannot move or resize the face circle. Attempting to grab the circle or resize handle results in a thumbnail of the photo being dragged instead, as if to share it to another app. See photo.
How can I properly move the "Click to Name" circle above the face? It does not work for any photo in my library

macOS 12.5


text:
Q: What is the English equivalent for the German idiom "Angstgegner" After seeing the soccer game against Italy I wondered what the correct equivalent for the German Angstgegner is (Angst=fear, Gegner=opponent).
Explanation:
The word itself does not say anything about the general quality of your Angstgegner. He/she can be extremely competent against other opponents, but very, very often it is not the case and this sets him apart from
standard, competent antagonists in stories and contests.
So an example with an underdog case:
You are under the Top Ten of your discipline. You are self-confident and noone defeats you without a hard fight.
So you meet John Doe which has the current number 1054. Piece of cake, right?
Well, you play against him and everything goes south quickly. He is a perfect match for your abilities, but not in the positive sense. He easily defends your best shots and his attacks penetrate your defenses easily. What is especially infuriating is that other players with approximately the same rank have no clue what is so special about him, they can defeat him easily.
You are playing tennis and your opponent on the other hand has a specific lob or return which only works for formidable serves...like yours. In karate he has perfected a powerful kick which can be easily countered...but you are unable to learn this specific counter.
In effect, every time you meet he has fun and you lose. And lose and lose and lose. It is always extremely hard to fight your Angstgegner and almost impossible to win. The result is naturally that you begin to fear any encounter and pray to <insert deity/positive influence here> that someone else take him out.

A: A good English equivalent of Angstgegner is bogey team. Here is a definition from encyclo.co.uk:

Bogey team is British sports slang for a team which usually manages to
  win despite an apparent weakness.

And here is an extract from the explanation of bogey by one stop english:

Most football clubs have a bogey team, meaning a team that either
  always beats them or against which they habitually enjoy bad luck, as
  in "Bolton are rapidly becoming Arsenal's bogey team".

.
Webpages with the term "bogey team" in the title include:
Devising a Game Plan for Germany to Finally Beat Bogey Team Italy
Can Germany overcome its bogey team in Italy?
Gareth Bale: we know Belgium, we might even be their bogey team
Revealed! Your Premier League club's bogey team
I am not aware of a common term for when the Angstgegner is an individual and not a team, although HotLicks' suggestion of nemesis fits pretty well here.

A: I don't think there is a suitable counterpart in English. The closest I can think of is (the most) feared opponent in a sense that you are afraid of competing with that particular opponent to the point you need to pray to God.
Actual usage:

It is the fundamental nature of sport than one must beat someone or
  something. Golf is the only sport in which the most feared opponent
  is you.

[Golf Guide for Parents and Players]
You could also consider using toughest opponent (to beat).


text:
Q: Не обновляется Field в Redux-form Вот такой код:
components/Component.jsx
import React from 'react';
import EventCalendarModal from './EventCalendarModal';

export default ({data: { eventList, matchesList }, handleAdd, handleRemove, handleSubmit}) => (
  <div className="event-calendar">
    <EventCalendarModal handleSubmit={handleSubmit}/>
  </div>
);

components/Modal.jsx
import React from 'react';
import { Field } from 'redux-form';
import { Button } from 'react-bootstrap';

export default ({handleSubmit}) => (
  <form>
    <Field name="name" component="input" type="text"/>
    <Button onClick={handleSubmit}>Submit</Button>
  </form>
);

containets/reduxForm.js
import { reduxForm } from 'redux-form';

export default reduxForm({
  form: 'modalEditForm',
  initialValues: {
    eventDate: 'gsdfgsdfgsdfgsdfg',
    name: ''
  }
})

index.js
import EventCalendarComponent from "./components/EventCalendarComponent";

import EventCalendarContainer from "./containers";

import { compose } from 'ramda';
import withHandlers from "./containers/withHandlers";
import lifecycleComponent from "./containers/lifecycle";
import reduxForm from "./containers/reduxForm";

export default compose(
  EventCalendarContainer,
  lifecycleComponent,
  withHandlers,
  reduxForm,
)(EventCalendarComponent);

../---../rootReducer.js
import {combineReducers} from 'redux';
import matches from './Matches/reducer';
import tournaments from './Tournaments/reducer';
import accreditationsList from './Requests/reducer';
import files from './FilesUploading/reducer';
import editAccreditation from './EditRequests/reducer';
import eventCalendar from './Requests/components/EventCalendar/reducer';
import { reducer as formReducer } from 'redux-form'

export default combineReducers({
    accreditationsList,
    tournaments,
    matches,
    files,
    editAccreditation,
    eventCalendar,
    form: formReducer
});

redux-devtools

При вводе в Field в консоли логгируются экшены, но значение не меняется. Оно всегда пустое, даже если добавить initialValues.
В чем может быть проблема?

A: Первое, что хотелось бы переписать это форма, сделаем на ней обработчик onSubmit, с кнопки при этом уберем onClick и добавим кнопке тип submit, обращаем внимание на филд, у него появился компонент - renderField:
export default ({handleSubmit}) => (
  <form onSubmit={handleSubmit}>
    <Field name="name" component={renderField} type="text" />
    <Button type="submit">Submit</Button>
  </form>
);

Также, тут рядышком объявим константу, в которой опишем наш input, чтобы в нем была некая логика (просто в этом же файле перед экспортом формы добавить эту константу):
const renderField = ({ input, label, type }) => (
  <input {...input} type={type} className="form-control" />
);

Далее ваш контейнер reduxForm вот внутри него нужно импортировать созданную вами форму из компонент и передать в качестве параметра, то есть должно быть как-то так:
import { reduxForm } from 'redux-form';
import Modal from './components/Modal'; // вот тут нужен правильный импорт (это я навскидку)

export default reduxForm({
  form: 'modalEditForm',
  initialValues: {
    eventDate: 'gsdfgsdfgsdfgsdfg',
    name: ''
  }
})(Modal); // вот тут передали нашу форму

Хотел написать комментарий, но он не поместился по размеру текста, поэтому дал ответ. Попробуйте внести эти правки в ваш код.


text:
Q: Autocomplete doesn't work in add row Autocomplete doesn't working in rows , please help me..
This is a code(JavaScript)
$(document).ready(function() {
        var count = 0;

        $("#add_btn").click(function(){
                count += 1;
            $('#container').append(
                         '
'
                     + '
' + count + '
	'
                     + '<input class="code" id="code' + count + '" name="code_' + count + '" type="text">	'
                     + '<input class="nama" id="nama' + count + '" name="nama_' + count + '" type="text">	'
                     + '<input class="qty" id="qty' + count + '" name="qty_' + count + '" type="text">	'
                      + '<input class="price" id="price' + count + '" name="price_' + count + '" type="text">	'
                     + '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden">
'
                );

            });

A:

$(document).ready(function() {
   var count = 0;

 var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];

        $("#add_btn").click(function(){
                count += 1;
            $('#container').append(
                         '
'
                     + '
' + count + '
	'
                     + '<input class="code" id="code' + count + '" name="code_' + count + '" type="text">	'
                     + '<input class="nama" id="nama' + count + '" name="nama_' + count + '" type="text">	'
                     + '<input class="qty" id="qty' + count + '" name="qty_' + count + '" type="text">	'
                      + '<input class="price" id="price' + count + '" name="price_' + count + '" type="text">	'
                     + '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden">
'
                );

     $("#code"+count).autocomplete({
            source: availableTags,
            minLength:1,
            select:function(event,data){
                $('.nama').val(data.item.nama_);
                $('.price').val(data.item.price_);
            }

        });

            });

    });

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

  <button id="add_btn">Add </button>

use below code, attach autocomplete call event after row appends into container
$(document).ready(function() {
    var count = 0

    $("#add_btn").click(function() {
      count += 1;
      $('#container').append(
        '
' +
        '
' + count + '
	' +
        '<input class="code" id="code' + count + '" name="code_' + count + '" type="text">	' +
        '<input class="nama" id="nama' + count + '" name="nama_' + count + '" type="text">	' +
        '<input class="qty" id="qty' + count + '" name="qty_' + count + '" type="text">	' +
        '<input class="price" id="price' + count + '" name="price_' + count + '" type="text">	' +
        '<input id="rows_' + count + '" name="rows[]" value="' + count + '" type="hidden">
'
      );

        $("#code" + count).autocomplete({
          source: "do.php",
          minLength: 1,
          select: function(event, data) {
            $('.nama').val(data.item.nama_);
            $('.price').val(data.item.price_);
          }
        });

    });

});

A: this is code from do.php
<?php
$conn = @mysql_connect('localhost','root','');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('coba', $conn);

$q = $_GET['term']; // variabel $q untuk mengambil inputan user
$sql = mysql_query("SELECT * FROM obat_farmasi WHERE kode_obat LIKE '%".$q."%'");

while ($data = mysql_fetch_array($sql)){

        $row['value']    =$data['kode_obat'];
        $row['nama_']    =$data['nama_obat'];
        $row['price_']    =$data['harga_satuan'];
        $row_set[]        =$row;
}
//echo json_encode($result);
echo json_encode($row_set);
?>


text:
Q: get position of point given distance from other points? I have a 2 points i know the distance between them with a 3rd points. how to get the position of the 3rd point given other distances with the other two points ?

A: Given only this information, you generally can't know the specific point. That third point will be at an intersection of two circles--one centered around each of the other two points. In particular, let's call your first two points $a,b$ and the point you're looking for $c.$ Let $r_{ab}$ be the distance from point $a$ to point $b$, and let $r_{ac},r_{bc}$ be the desired respective distances from $a,b$ to $c$. What we're dealing with, then, is circles around $a$ and $b$ of respective radii $r_{ac}$ and $r_{bc}$.
Now, if two of $r_{ab},r_{ac},r_{bc}$ add up to the third, then there is exactly one point of intersection of the two circles--and that is our point $c$. If two of $r_{ab},r_{ac},r_{bc}$ add up to some number that is less than the third, then the circles don't intersect at all, and there is no such point $c$. Otherwise, there will be two points of intersection of the circles, and $c$ will be one of those, but (as I said) there's no way to know which, given only this information.


text:
Q: Read data effectively in AWS EMR Spark cluster I am trying to get acquainted with Amazon Big Data tools and I want to preprocess data from S3 for eventually using it for Machine Learning.
I am struggling to understand how to effectively read data into an AWS EMR Spark cluster.
I have a Scala script which takes a lot of time to run, most of that time is taken up by Spark's explode+pivot on my data and then using Spark-CSV to write to file.
But even reading the raw data files takes up too much time in my view.
Then I created a script only to read in data with sqlContext.read.json() from 4 different folders (data sizes of 0.18MB, 0.14MB, 0.0003MB and 399.9MB respectively). I used System.currentTimeMillis() before and after each read function to see how much time it takes and with 4 different instances' settings the results were the following:
           m1.medium (1) | m1.medium (4) | c4.xlarge (1) | c4.xlarge (4)
1. folder   00:00:34.042 |  00:00:29.136 |  00:00:07.483 |  00:00:06.957
2. folder   00:00:04.980 |  00:00:04.935 |  00:00:01.928 |  00:00:01.542
3. folder   00:00:00.909 |  00:00:00.673 |  00:00:00.455 |  00:00:00.409
4. folder   00:04:13.003 |  00:04:02.575 |  00:03:05.675 |  00:02:46.169

The number after the instance type indicates how many nodes were used. 1 is only master and 4 is one master, 3 slaves of the same type.
Firstly, it is weird that reading in first two similarly sized folders take up different amount of time.
But still how does it take so much time (in seconds) to read in less than 1MB of data?
I had 1800MB of data a few days ago and my job with data processing script on c4.xlarge (4 nodes) took 1,5h before it failed with error:
controller log:
INFO waitProcessCompletion ended with exit code 137 : hadoop jar /var/lib/aws/emr/step-runner/hadoop-...
INFO total process run time: 4870 seconds
2016-07-01T11:50:38.920Z INFO Step created jobs:
2016-07-01T11:50:38.920Z WARN Step failed with exitCode 137 and took 4870 seconds

stderr log:
16/07/01 11:50:35 INFO DAGScheduler: Submitting 24 missing tasks from ShuffleMapStage 4 (MapPartitionsRDD[21] at json at DataPreProcessor.scala:435)
16/07/01 11:50:35 INFO TaskSchedulerImpl: Adding task set 4.0 with 24 tasks
16/07/01 11:50:36 WARN TaskSetManager: Stage 4 contains a task of very large size (64722 KB). The maximum recommended task size is 100 KB.
16/07/01 11:50:36 INFO TaskSetManager: Starting task 0.0 in stage 4.0 (TID 5330, localhost, partition 0,PROCESS_LOCAL, 66276000 bytes)
16/07/01 11:50:36 INFO TaskSetManager: Starting task 1.0 in stage 4.0 (TID 5331, localhost, partition 1,PROCESS_LOCAL, 66441997 bytes)
16/07/01 11:50:36 INFO Executor: Running task 0.0 in stage 4.0 (TID 5330)
16/07/01 11:50:36 INFO Executor: Running task 1.0 in stage 4.0 (TID 5331)
Command exiting with ret '137'

This data was doubled in size over the weekend. So if I get ~1GB of new data each day now (and it will grow soon and fast) then I hit big data sizes very soon and I really need an effective way to read and process the data quickly.
How can I do that? Is there anything that I am missing? I can upgrade my instances, but for me it does not seem normal that reading in 0.2MB of data with 4x c4.xlarge (4 vCPU, 16ECU, 7.5GiB mem) instances take 7 seconds (even with inferring data schema automatically for ~200 JSON attributes).


text:
Q: Integral of exponential function with trigonometric identities I need help in solving the following definite integral. I could not find any example like this
$$\int_{0}^{2\pi}\int_{0}^{d}\exp\!\Big(\frac{-r^2 +2\alpha\; r\cos\theta}{4\;\sigma^2}\Big)r\; dr\; d\theta$$

A: Integration with respect to $\theta$ can be carried out explicitly in terms of modified Bessel  function of the first kind.
$$
  \int_0^{2 \pi} \exp\left( \frac{ \alpha r}{2 \sigma^2} \cos \theta \right) \, \mathrm{d} \theta = 2 \pi I_0 \left( \frac{ \alpha r}{2 \sigma^2} \right)
$$
The remaining integral
$$
 \mathcal{I}_d = 2 \pi \int_0^d r \cdot \mathrm{e}^{-\frac{r^2}{4 \sigma^2}} \cdot I_0 \left( \frac{ \alpha r}{2 \sigma^2} \right) \mathrm{d} r = 4 \pi \sigma^2 \exp\left( \frac{\alpha^2}{4 \sigma^2} \right) \left(1 - Q_1\left( \frac{\alpha}{\sqrt{2} \sigma}, \frac{d}{\sqrt{2} \sigma} \right)\right)
$$
where $Q_1(a,b)$ is the Marcum Q-function.
Notice that
$$
  \lim_{d \to \infty} \mathcal{I}_d = 4 \pi \sigma^2 \exp\left( \frac{\alpha^2}{4 \sigma^2} \right)
$$


text:
Q: is there a way to put a possible cooldown on this  dmGuild.members.forEach(member => {
        setTimeout(function(){
            if(member.id == bot.user.id) return;
            console.log(`DMing ${member.user.username}`);
            member.send(`${msg}  ${Math.floor(Math.random() * 9999)}`);
        }, 0);
    });

I need help finding a way to limit each time this is used. ex: i use the command and they are all messaged at once, is there anyway to send a dm with a 5000ms ratelimit in between?

A: You can take the index from the forEach callback and use it when specifying the setTimeout delay.
dmGuild.members.forEach((member, i) => {
    setTimeout(function(){
      if(member.id == bot.user.id) return;
      console.log(`DMing ${member.user.username}`);
      member.send(`${msg}  ${Math.floor(Math.random() * 9999)}`);
    }, (i+1) * 5000);
});

If the error TimeoutOverflowWarning occurs, try to create timeouts gradually using recursion.
function fn(members, i = 0) {
  var member = members[i];

  if(member.id != bot.user.id) {
    console.log(`DMing ${member.user.username}`);
    member.send(`${msg}  ${Math.floor(Math.random() * 9999)}`);
  }

  if (i < members.length) {
    setTimeout(() => fn(members, i + 1), 5000);
  }
}

fn(dmGuild.members);


text:
Q: Why/how is $au_x + bu_y$ the directional derivative of $u$ in the direction of the vector $\mathbf{V} = (a, b) = a \mathbf{i} + b \mathbf{j}$? I am currently studying the textbook Partial Differential Equations: An Introduction, second edition, by Walter A. Strauss. Chapter 1.2 First-Order Linear Equations says the following:

Let us solve
$$au_x + bu_y = 0,$$
where $a$ and $b$ are constants not both zero.
Geometric Method The quantity $au_x + bu_y$ is the directional derivative of $u$ in the direction of the vector $\mathbf{V} = (a, b) = a \mathbf{i} + b \mathbf{j}$. It must always be zero. This means that $u(x, y)$ must be constant in the direction of $\mathbf{V}$.

The author states that the quantity $au_x + bu_y$ is the directional derivative of $u$ in the directions of the vector $\mathbf{V} = (a, b) = a \mathbf{i} + b \mathbf{j}$, but offers no justification. Why/how is the quantity $au_x + bu_y$ the directional derivative of $u$ in the direction of the vector $\mathbf{V} = (a, b) = a \mathbf{i} + b \mathbf{j}$?

A: It is because,
$$ D_{V}(u) = V \cdot \nabla u =  (a, b) \cdot (u_x, u_y) = a u_x + bu_y $$

A: It's really just a special case of the chain rule. The directional derivative measures how a function changes when going in the specified direction. The "direction" being along the line $\mathbf{r}_0+t\mathbf V$. So it's the derivative of the function $u(\mathbf r_0+t\mathbf V)$ at $t=0$. But this function is a composition of $u(\mathbf r)$ and $\mathbf r_0+t\mathbf V$. If you apply the chain rule, you will get that the derivative is $(\nabla u^T) \mathbf V$, which, when written in coordinates, is exactly your formula.


text:
Q: clone select box in 5 number of times jquery if click on add button clone select box in 5 number of times jquery

$('.clkadd').click(function() {
  $('.twoselect:last').clone().appendTo('.appendtwo');
});

  <select class="twoselect"><option>element</option><option>Next Level</option></select>

Add

A: The .length property returns the no of elements in DOM. Use it in the condition to restrict the elements to be cloned.

$('.clkadd').click(function() {
  var select = $('.twoselect');
  if (select.length <= 5) {
    select.filter(':last').clone().appendTo('.appendtwo');
  }
});

  <select class="twoselect"><option>element</option><option>Next Level</option></select>

Add

A: You could restrict the click with count of the click below 5

var c=0;
$('.clkadd').click(function() {
if(c<5){
  $('.twoselect:last').clone().appendTo('.appendtwo');
  }
  c++
});

  <select class="twoselect"><option>element</option><option>Next Level</option></select>

Add


text:
Q: How do I delete ProtonVPN connections with Network Manager? On Ubuntu 18.04.  I upgraded my ProtonVPN CLI client from 2.2.6 to 3.7.2, which was a gigantic mistake. In troubleshooting the resulting issues, ProtonVPN support has asked me to delete connections related to ProtonVPN, but they haven't been able to tell me how.
These are my connections:
$ nmcli d
DEVICE          TYPE      STATE        CONNECTION
wlp3s0          wifi      connected    WifiAP
enp2s0          ethernet  unavailable  --
pvpnroutintrf0  dummy     unmanaged    --
lo              loopback  unmanaged    --
proton0         tun       unmanaged    --

They want me to delete pvpnroutintrf0 and proton0.  They suggested the commands
$ nmcli c delete pvpnroutintrf0 dummy

and
$ nmcli c delete proton0 tun

but these result in "unknown connection" errors:
$ nmcli c delete pvpnroutintrf0 dummy
Error: unknown connection 'pvpnroutintrf0'.
Error: unknown connection 'dummy'.
Error: cannot delete unknown connection(s): 'pvpnroutintrf0', 'dummy'.

$ nmcli c delete proton0 tun
Error: unknown connection 'proton0'.
Error: unknown connection 'tun'.
Error: cannot delete unknown connection(s): 'proton0', 'tun'.

I've tried using sudo with these, and it makes no difference.  I've also tried
$ nmcli c delete pvpnroutintrf0
$ nmcli c delete id pvpnroutintrf0
$ nmcli c delete id pvpnroutintrf0 dummy
$ nmcli connection delete pvpnroutintrf0
$ nmcli connection delete pvpnroutintrf0 dummy
$ nmcli connection delete id pvpnroutintrf0 dummy

They return the same "unknown connection" error.
This Unix SE page exists with a similar question but no relevant answers beyond what I've tried.  The man page for nmcli was similarly unhelpful, as one would expect.
How do I delete these two connections?

A: You have listed the output of nmcli d which lists the managed devices. However, you are trying to delete connections which are a different item for nmcli. From the man-page:

NetworkManager stores all network configuration as "connections", which are collections of data (Layer2 details, IP addressing, etc.) that describe how to create or connect to a network. A connection is "active" when a device uses that connection's configuration to create or connect to a network.

If you look at nmcli c show, you will find output as in
NAME      UUID                                  TYPE             DEVICE
<name>    <some uuid>                           <type info>      <device>

The value of the NAME column is the expected argument to a nmcli c delete command. You should therefore use the connection names used by devices pvpnroutintrf0 and proton0 in your delete command to achieve what the ProtonVPN support suggested. (Sometimes, these are chosen to coincide with device names, but it seems not to be the case in your setup.)


text:
Q: Issue with RDD - list index out of range I am using values obtained from one RDD in another. I use the first RDD to calculate averages and do a .collect() to fetch it into a variable called z.
When accessing z however, I get an error, list index out of range.
What am I doing wrong?
avgtuples = summedtuples.map(lambda (ct, (Sx, Sy)): (((Sx*1.0)/ct), ((Sy*1.0)/ct)))
z = avgtuples.collect()
newmap = reducedhostbyte.map(lambda (h, (x, y)): (n, get_vals(x, y, z[0], z[1])))

The value of z is [(24.910157132138149, 474512.76637794758)].

A: If z is [(24.910157132138149, 474512.76637794758)], it is a list with a single element. So z[1] causes an IndexError.
That single element (z[0]) is a two-element tuple, so presumably you want to access those two elements as z[0] and z[1]. If so, this is what you need:
z = avgtuples.collect()[0]

(Note the [0] at the end. It takes the first (and only) element of the list.)
It's strange that you would have a single-row RDD (summedtuples) in the first place. There is probably more that could be improved in your code, but that's outside of the scope of the question.


text:
Q: Using Gmail with Mail, Google Calendar with iCal I currently use Gmail and Google Calendar for my primary email and calendar system. I've been using them both through the web interface so I can best take advantage of all the features. However I'm considering switching to Mail & iCal, and I'm trying to figure out what I will and won't be able to do. (I already set up syncing with Mail & Calendar on my iPhone, and Address Book on both my iPhone and Mac.)
Here are the features I use:

*

*Keyboard shortcuts in Gmail

*Several alternate email addresses that are forwarded to and fetched by my primary Gmail account

*

*When I reply to an email that was sent to one of these addresses, Gmail automatically picks that address to send from

*Sending mail from plus-addresses (e.g. me+test@gmail.com)

*Priority Inbox ("Important" messages, as determined by Gmail's algorithm, appear at the top of my inbox)

*Labels, which appear next to the message subject in my inbox

*In Google Calendar, I have added a couple public calendars that I can view events from.

Are all of these features easy to sync with Mail and iCal? In particular, how do I set up the ability to send from my other addresses? Will I have to add my other accounts separately in Mail (and if so, will I still be able to view them when I visit gmail.com on another device)?

A: Keyboard shortcuts: Mail has it's own keyboard shortcuts, which you may have to learn.
Alternate email addresses/multiple accounts: works fine. Don't know about plus-addresses.
Priority inbox: this is not supported.
Labels work, as does flagging.
Public calendars work in iCal.
Syncing is very easy to set up - via IMAP in Mail, and in Preferences in iCal. In Lion it's even simpler.
Yes, you add each account separately in mail. You can still visit them in any browser or device.


text:
Q: Koala gem get_picture with params I want retrieve JSON with information about user picture. With simple:
@graph.get_picture('some_user_id')

I got only link to picture. And I want get JSON with some data (like described here). But when I do next:
@graph.get_picture('some_user_id', {redirect: false})

I always get nil instead of JSON.
Moreover, this construction:
@graph.get_picture('some_user_id', {type: 'large'})

works fine. I get my large image. But with redirect argument something wrong.


text:
Q: What is the width argument in position_dodge? The documentation of position_dodge does not explain what exactly is this width argument

*

*Whose width does it specify?

*What's the "unit"?

*What's the default value?

The default value is width = NULL, but trial and error shows that width = 0.9 seems to produce the default effect (see postscript). However, I couldn't find where such default value is set in ggplot2 source code. Thus,

*Could you explain how the default dodge is implemented in ggplot2 code?

The spirit of the question is to allow ggplot2 users to find appropriate width values without trial and error.
PS:
ggplot(data = df) +
  geom_bar(aes(x, y, fill = factor(group)),
           position = position_dodge(), stat = "identity")

ggplot(data = df) +
  geom_bar(aes(x, y, fill = factor(group)),
           position = position_dodge(0.9), stat = "identity")

A: I will first give very brief answers to your three main questions. Then I walk through several examples to illustrate the answers more thoroughly.

*

*Whose width does it specify?
The width of the geom elements to be dodged.

*What's the "unit"?
The actual or the virtual width in data units of the elements to be dodged.

*What's the default value?
If you don't set the dodging width explicitly, but rely on the default value, position_dodge(width = NULL) (or just position = "dodge"), the dodge width which is used is the actual width in data units of the element to be dodged.

I believe your fourth question is too broad for SO. Please refer to the code of collide and dodge and, if needed, ask a new, more specific question.

Based on the dodge width of the element (together with its original horizontal position and the number of elements which are stacked), new center positions (x) of each element, and new widths (xmin, xmax positions) are calculated. The elements are shifted horizontally just far enough not to overlap with adjacent elements. Obviously, wide elements needs to be shifted more than narrow elements in order to avoid overlap.
To get a better feeling for dodging in general and the use of the width argument in particular, I show some examples. We start with a simple dodged bar plot, with default dodging; we can use either position = "dodge" or the more explicit position = position_dodge(width = NULL)
# some toy data
df <- data.frame(x = 1,
                 y = 1,
                 grp = c("A", "B"))

p <- ggplot(data = df, aes(x = x, y = y, fill = grp)) + theme_minimal()
p + geom_bar(stat = "identity",
             position = "dodge")
           # which is the same as:
           # position = position_dodge(width = NULL))

So (1) whose width is it in position_dodge and (2) what is the unit?
In ?position_dodge we can read:

width: Dodging width, when different to the width of the individual        elements

Thus, if we use the default width, i.e. NULL, the dodging calculations are based on the width of the individual elements.
So a trivial answer to your first question, "Whose width does it specify?", would be: the width of the individual elements.
But of course we then wonder, what is "the width of the individual elements"? Let's start with the bars. From ?geom_bar:

width: Bar width. By default, set to 90% of the resolution of the data

A new question arises: what is resolution? Let's check ?ggplot2::resolution:

The resolution is is the smallest non-zero distance between adjacent values. If there is only one unique value [like in our example], then the resolution is defined to be one.

We try:
resolution(df$x)
# [1] 1

Thus, the default bar width in this example is 0.9 * 1 = 0.9
We may check this by looking at the data ggplot uses to render the bars on the plot using ggplot_build. We create a plot object with a stacked barplot, with bars of default width.
p2 <- p +
  geom_bar(stat = "identity",
           position = "stack")

The relevant slot in the object is $data, which is a list with one element for each layer in the plot, in the same order as they appear in the code. In this example, we only have one layer, i.e. geom_bar, so let's look at the first slot:
ggplot_build(p2)$data[[1]]

#      fill x y label PANEL group ymin ymax xmin xmax colour size linetype alpha
# 1 #F8766D 1 1     A     1     1    0    1 0.55 1.45     NA  0.5        1    NA
# 2 #00BFC4 1 2     B     1     2    1    2 0.55 1.45     NA  0.5        1    NA

Each row contains data to 'draw' a single bar. As you can see, the width of the bars are all 0.9 (xmax - xmin = 0.9). Thus, the width of the stacked bars, to be used in the calculations of the new dodged positions and widths, is 0.9.

In the previous example, we used the default bar width, together with the default dodge width. Now let's make the bar slightly wider than the default width above (0.9). Use the width argument in geom_bar to explicitly set the (stacked) bar width to e.g. 1. We try to use the same dodge width as above (position_dodge(width = 0.9)). Thus, while we have set the actual bar width to be 1, the dodge calculations are made as if the bars are 0.9 wide. Let's see what happens:
p +
  geom_bar(stat = "identity", width = 1, position = position_dodge(width = 0.9), alpha = 0.8)
p

The bars are overlapping because ggplot shifts bars horizontally as if they have a (stacked) width of 0.9 (set in position_dodge), while in fact the bars have a width of 1 (set in geom_bar).
If we use the default dodge values, the bars are shifted horizontally accurately according to the set bar width:
p +
  geom_bar(stat = "identity", width = 1, position = "dodge", alpha = 0.8)
                                   # or: position = position_dodge(width = NULL)

Next we try to add some text to our plot using geom_text. We start with the default dodging width (position_dodge(width = NULL)), i.e. dodging is based on default element size.
p <- ggplot(data = df, aes(x = x, y = y, fill = grp, label = grp)) + theme_minimal()
p2 <- p +
  geom_bar(stat = "identity", position = position_dodge(width = NULL)) +
  geom_text(size = 10, position = position_dodge(width = NULL))
                  # or position = "dodge"

p2
# Warning message:
#  Width not defined. Set with `position_dodge(width = ?)`

The dodging of the text fails. What about the warning message, "Width is not defined"? Slightly cryptic. We need to consult the Details section of ?geom_text:

Note the "width" and "height" of a text element are 0,
so stacking and dodging text will not work by default,
[...]
Obviously, labels do have height and width, but they are physical units, not data units.

So for geom_text, the width of the individual elements is zero. This is also the first 'official ggplot reference' to your second question: The unit of width is in data units.
Let's look at the data used to render the text elements on the plot:
ggplot_build(p3)$data[[2]]
#       fill x y label PANEL group xmin xmax ymax colour size angle hjust vjust alpha family fontface lineheight
# 1 #F8766D 1 1     A     1     1    1    1    1  black   10     0   0.5   0.5    NA               1        1.2
# 2 #00BFC4 1 1     B     1     2    1    1    1  black   10     0   0.5   0.5    NA               1        1.2

Indeed, xmin == xmax; Thus, the width of the text element in data units is zero.
How to achieve correct dodging of the text element with width zero? From Examples in ?geom_text:

ggplot2 doesn't know you want to give the labels the same virtual width as the bars [...] So tell it:

Thus, in order for dodge to use the same width for geom_text elements as for the geom_bar elements when new positions are calculated, we need to set "the virtual dodging width in data units" of the text elements to the same width as the bars. We use the width argument of position_dodge to set the virtual width of the text element to 0.9 (i.e. the bar width in the example above):
p2 <- p +
  geom_bar(stat = "identity", position = position_dodge(width = NULL)) +
  geom_text(position = position_dodge(width = 0.9), size = 10)

Check the data used for rendering geom_text:
ggplot_build(p2)$data[[2]]
#      fill     x y label PANEL group xmin xmax ymax colour size angle hjust vjust alpha family fontface lineheight
# 1 #F8766D 0.775 1     A     1     1 0.55 1.00    1  black   10     0   0.5   0.5    NA               1        1.2
# 2 #00BFC4 1.225 1     B     1     2 1.00 1.45    1  black   10     0   0.5   0.5    NA               1        1.2

Now the text elements have a width in data units: xmax - xmin = 0.9, i.e. the same width as the bars. Thus, the dodge calculations will now be made as if the text elements have a certain width, here 0.9. Render the plot:
p2

The text is dodged correctly!

Similar to text, the width in data units of points (geom_point) and error bars (e.g. geom_errorbar) is zero. Thus, if you need to dodge such elements, you need to specify a relevant virtual width, on which dodge calculations then are based. See e.g. the Example section of ?geom_errorbar:

If you want to dodge bars and errorbars, you need to manually specify the dodge width [...] Because the bars and errorbars have different widths we need to specify how wide the objects we are dodging are

Here is an example with several x values on a continuous scale:
df <- data.frame(x = rep(c(10, 20, 50), each = 2),
                 y = 1,
                 grp = c("A", "B"))

Let's say we wish to create a dodged barplot with some text above each bar. First, just check a barplot only using the default dodging width:
p <- ggplot(data = df, aes(x = x, y = y, fill = grp, label = grp)) + theme_minimal()

p +
  geom_bar(stat = "identity", position = position_dodge(width = NULL))
                         # or position = "dodge"

It works as expected. Then, add the text. We try to set the virtual width of the text element to the same as the width of the bars in the example above, i.e. we "guess" that the bars still have width of 0.9, and that we need to dodge the text elements as if they have a width of 0.9 as well:
p +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(width = 0.9), size = 10)

Clearly, the dodging calculation for the bars is now based on a different width than 0.9 and setting the virtual width to 0.9 for the text element was a bad guess. So what is bar width here? Again, bar width is "[b]y default, set to 90% of the resolution of the data". Check the resolution:
resolution(df$x)
# [1] 10

Thus, the width of the (default stacked) bars, on which their new, dodged position is calculated, is now 0.9 * 10 = 9. Thus, to dodge the bars and their corresponding text 'hand in hand', we need to set the virtual width of also the text elements to 9:
p +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(width = 9), size = 10)

In our final example, we have a categorical x axis, just a 'factor version' of the x values from above.
df <- data.frame(x = factor(rep(c(10, 20, 50), each = 2)),
                 y = 1,
                 grp = c("A", "B"))

In R, factors are internally a set of integer codes with a "levels" attribute. And from ?resolution:

If x is an integer vector, then it is assumed to represent a discrete variable, and the resolution is 1.

By now, we know that when resolution is 1, the default width of the bars is 0.9. Thus, on a categorical x axis, the default width for geom_bar is 0.9, and we need to set the dodging width for geom_text accordingly:
ggplot(data = df, aes(x = x, y = y, fill = grp, label = grp)) +
  theme_minimal() +
  geom_bar(stat = "identity", position = "dodge") +
  # or: position = position_dodge(width = NULL)
  # or: position = position_dodge(width = 0.9)
  geom_text(position = position_dodge(width = 0.9), size = 10)


text:
Q: pandas DataFrame - find max between offset columns Suppose I have a pandas dataframe given by
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5,2))
df

    0           1
0   0.264053    -1.225456
1   0.805492    -1.072943
2   0.142433    -0.469905
3   0.758322    0.804881
4   -0.281493   0.602433

I want to return a Series object with 4 rows, containing max(df[0,0], df[1,1]), max(df[1,0], df[2,1]), max(df[2,0], df[3,1]), max(df[3,0], df[4,1]). More generally, what is the best way to compare the max of column 0 and column 1 offset by n rows?
Thanks.

A: You want to apply max to rows after having shifted the first column.
pd.concat([df.iloc[:, 0].shift(), df.iloc[:, 1]], axis=1).apply(max, axis=1).dropna()


text:
Q: List prints multiple times instead of once Hello I have a code here.
datasets = []
datasets.append([14.2, 32.5, 42.1, 74.5, 43.5])
datasets.append([25.7, 34.1, 48.7, 50.3])
datasets.append([11.2, 26.9, 95.1, 52.1, 23.5, 5.6, 45.7, 37.8])
datasets.append([54.7, 25.3])

# Function
def summary_function(datasets):
    for k in datasets:
        summary_value = min(datasets)/len(datasets)
    return summary_value

# Create Summary List
summary_list = []
for i in range(len(datasets)):
    summary_value = summary_function(datasets[i])
    summary_list.append(summary_value)
    print('Summary List:',summary_list)

This code prints the list like this:
Summary List: [2.84]
Summary List: [2.84, 6.425]
Summary List: [2.84, 6.425, 0.7]
Summary List: [2.84, 6.425, 0.7, 12.65]

How do I make the print output to look like this:
Summary List: [2.84, 6.425, 0.7, 12.65]

A: Code
datasets = []
datasets.append([14.2, 32.5, 42.1, 74.5, 43.5])
datasets.append([25.7, 34.1, 48.7, 50.3])
datasets.append([11.2, 26.9, 95.1, 52.1, 23.5, 5.6, 45.7, 37.8])
datasets.append([54.7, 25.3])

# Function
def summary_function(datasets):
    for k in datasets:
        summary_value = min(datasets)/len(datasets)
    return summary_value

# Create Summary List
summary_list = []
for i in range(len(datasets)):
    summary_value = summary_function(datasets[i])
    summary_list.append(summary_value)
print('Summary List:',summary_list) # no longer in the for loop

If you move the last line print('Summary List:',summary_list) to be outside of the loop it will only print after the loop has finished and not while it is iterating.
Output
Summary List: [2.84, 6.425, 0.7, 12.65]


text:
Q: How can i group by date output from sql? How can i group by date  all values ?
My sql table
id |date        | price | description
1  | 2019-01-01 | 30      price 1
2  | 2019-01-04 | 50      price 2
3  | 2019-01-01 | 60      price 3
4  | 2019-01-04 | 20      price 4
5  | 2019-01-01 | 10      price 5

My query :
$result = mysql_query("SELECT * FROM newcosts  ORDER BY id DESC ");

If i will do GROUP BY date , I will loose all my prices and descriptions.
while( $row = mysql_fetch_array($result)){
    echo $row['date']."
";
    echo $row['price']."
";
    echo $row['description']."
";
}

My output : https://ibb.co/zN7zRTR.
How can i do something like this ?
2019-01-01
price 1      30
price 3      60

2019-01-04
price 2      50
price 4      20

A: I think you just need to sort by the date.  Something like this should work:
$query = "SELECT * FROM newcosts ORDER BY date";
$date = NULL;

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $curr_date = $row['date'];
        if ($date != $curr_date) {
            $date = $curr_date;
            echo $date . "
";
        }
        echo $row['description']. "  " . $row['price'] . "
";
    }
}

The idea behind the above presentation logic is that we only print the date once, per group of dates.  But for each record, we always print a description and price.
Note: You are mysql_query which is a deprecated API.


text:
Q: Decipephering Notation and plugging in values for ellipse formula Premise
I had asked a question on stats exchange about calculating error ellipses for a given scatter plot. I got an answer that seems acceptable, but I'm having trouble implementing it because my math notation literacy is very weak, and I think it would be undue burden for the answerer to painstakingly explain the formula. Thus I decided to make deciphering the formula into a question in and of itself. Math SE seems to be most appropriate for this.
The descriptive stats are:

*

*$n = 321$

*$\mu_{x} = 7.60$

*$\mu_{y} = 11.38$

*$\sigma_{x} = .34$

*$\sigma_{y} = .44$

*covariance matrix ${} = \begin{bmatrix} .12 & .10 \\ .10 & .19 \end{bmatrix}$

*ordered eigenvalues ${}= 1.66,~ 0.34$
And I was told that the formula for creating the ellipse was:
$$z_y = \rho z_x\pm \sqrt{1-\rho^2}\sqrt{2\ln(\frac{1}{1-q})-z_x^2}$$
where $z_y = (y-\mu_y)/\sigma_y~,~z_x = (x-\mu_x)/\sigma_x~$, and $\rho = .10 /\, (.34 \ast .44)$.  Which should result in something that looks like this:

What I tried to do is plug in my descriptive stats for each part of the formula. Some parts left me scratching my head however. Here is what I have:
$$(y-11.38) = (.10)*(x-7.6) \pm \sqrt{1-(.10)^2)} \sqrt{2\ln(\frac{1}{1-q})-(x-7.6)^2}$$
Question
I'm not sure what $q$ supposed to be. I tried to research common notation for $q$ but only found that: $q$ denotes sample elements that do not have attributes. I don't see how that applies to my situation. Given my descriptive stats at the top of the post, how do I find $q$ for this formula? And is my plugging in right so far?
I have a hunch, but I'm also not totally sure what I'm subtracting the x and y means from in the term $z_y = (y-\mu_y)/\sigma_y$. Let's look at the case for y for instance: Is $y$ here the sample y from my actual sample observations, or something else?
Optional side question: Is there anything in this formula that has bearing on the orientation of the ellipse? Or is this only the equation for an axis-aligned ellipse?


text:
Q: ClickOnce vs. a shortcut I have seen some application whose "deploy" strategy is to have an .exe file in a server and access it via a shortcut from different "clients", and it works fine. They only worry about keeping that EXE file updated when a new version arrives. Why could this approach be wrong and what would be the advantage of using ClickOnce instead of this old fashioned style?

A: What happens when disgruntled Joe decides he wants to spread a massive virus throughout the organization and replaces your friendly .exe with a malicious virus?  ClickOnce deters this through certificate validation.
Also...
ClickOnce has a system of prerequisite checking.  You don't have Data Access Components? You don't even have .NET Framework 2.0? No problem! It installs the prerequisite quietly.
Can't think of any other reasons off hand but those are the big ones.
Edit: Also, ClickOnce installs a local copy that can be ran while disconnected from the network.  When the local copy is ran, it automatically checks for any updates, offers the user the choice to update to the new version or run the current version. This can be configured to be done at the startup of the program or at the shutdown of the program if my memory serves me correctly.
Hmm.. what else..
By running an .exe across the network like that, you'll probably run into problems modifying the file system of the PC the .exe is running on. ClickOnce does not have any problems with this since it is ran locally.

A: Sharing the file on a network drive could cause you file locking griefs and possibly not work at all, depending on the security policy and Windows version.


text:
Q: Insert TextBox into Border how to insert textbox or textblock to border in c#?
Now I have this:
        Border notificationBorder1 = new Border();
        LayoutGrid.Children.Add(notificationBorder1);
        TextBlock notificationTxt1 = new TextBlock();

But I don't know how to insert textbox into border.
I tried to google, but found nothing, just how to change textbox border color.
Thanks

A: Just place it inside xaml
<Border>
      <TextBlock></TextBlock>
</Border>

If you want to do it in the code then just
notificationBorder1.Child = notificationTxt1;


text:
Q: "module.js:557 throw err" when running npm from terminal when I run npm from terminal I get this error and nothing else. no npm command is working, all of them are giving the same error and I can't even install programs that are depending on nodejs.

$ npm module.js:557 throw err; ^
Error: Cannot find module 'semver'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object. (/usr/lib/node_modules/npm/lib/utils/unsupported.js:2:14)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)

A: This did the trick for me (I'm using OSX)
sudo rm -rf /usr/local/lib/node_modules
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node


text:
Q: How to get internal/external available space in Android Application? I'm writing an android program to check available space of internal phone memory or external sd card. But i don't know how to do this. Any one can help me how to do it in Android?

A: I think you're looking for this class: http://developer.android.com/reference/android/os/StatFs.html


text:
Q: JQuery DELETE Ajax request does what it has to but then raises error Something is wrong with my AJAX request.
$.ajax({
    type : "DELETE",
    url : deleteUrl,
    success : function(result) {
        alert("Done!");
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Fail!");
    }
});

This request accomplishes its work on the server-side, but then it goes to the 'error: ' part of the code instead of 'success: '. The reason is "400 bad request". Please, let me know if you have any suggestions how to fix it.


text:
Q: read from file and add numbers I have text file with entries like
123
112
3333
44
2
How to add these numbers and get the sum of these.

A: A Bash-only (no cat) variation on MYYN's answer.
sum=0; for i in $(<number_file); do ((sum += i)); done; echo $sum

Also, note the simpler arithmetic statement.

A: just one awk command does it. It doesn't break when you have decimals to add as well.
awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' file

A: Example:
$ cat numbers.txt
123 112 3333 44 2

$ SUM=0; for i in `cat numbers.txt`; do SUM=$(($SUM + $i)); done; echo $SUM
3614

See also: Bash Programming Introduction, section on arithmetic evaluation
Another way would be to use bc, an arbitrary precision calculator language:
$ echo '123 112 3333 44 2' | tr ' ' '\n' | paste -sd+ | bc
3614

Paste usually works on lines, so we need tr.

A: Alternatively in Awk
echo "123 112 3333 44 2" | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

Or if it's in a file
cat file.txt | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

I find Awk much easier to read/remember. Although "Dave Jarvis" solution is particular neat!


text:
Q: node.js error after switching to Windows - Error: %1 is not a valid Win32 application I switched from OSX to Windows 7. A project I'm coding is throwing an error which I believe to be related to the switch.
The first line below is the line causing the error to be thrown:
  if (!/not find/i.test(e.message)) {
    throw e
  }

The error is:
Error: %1 is not a valid Win32 application.

Could somebody tell me how to get this line working in Windows?

A: If you copy a project from one platform to another or you switch CPU architectures (e.g. x86 to ARM or x86 to x86_64), you'll need to recompile any addons that your project may have been using, either directly or indirectly.


text:
Q: Can we write an if statement backwards in javascript? What is the difference between these two expressions?
if (userStatus === 'OFFLINE') document.forms.newMessage.fields.disabled = true;

and
document.forms.newMessage.fields.disabled = (userStatus === 'OFFLINE');

A: document.forms.newMessage.fields.disabled = (userStatus === 'OFFLINE')

is equivalent to

if (userStatus === 'OFFLINE') {
    document.forms.newMessage.fields.disabled = true;
} else {
    document.forms.newMessage.fields.disabled = false;
}

Notice the else statement. If there is no else statement then your first piece of code only sets document.forms.newMessage.fields.disabled when the condition (userStatus === 'OFFLINE') is met.

Consider the case  in which
document.forms.newMessage.fields.disabled is already true but userStatus is "ONLINE".
With your first piece of code, document.forms.newMessage.fields.disabled will remain true (because of the lack of else statement) , but with the second piece of code, it will be set to false.


text:
Q: how to add column to manage customers grid and it should work as filter? I want to add news letter subscribed or not as column.
but I dont have idea from which table i have to join.
can you any one help me on this?

class Gumbrands_Customergrid_Block_Adminhtml_Customer_Grid extends Mage_Adminhtml_Block_Customer_Grid{
    /**
     * override the _prepareCollection to add an other attribute to the grid
     * @return $this
     */
    protected function _prepareCollection(){
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->addAttributeToSelect('email')
            ->addAttributeToSelect('created_at')
            ->addAttributeToSelect('group_id')
            //if the attribute belongs to the customer, use the line below
            ->addAttributeToSelect('news_letter')
            //if the attribute belongs to the customer address, comment the line above and use the one below
            //->joinAttribute('mobile', 'customer_address/mobile', 'default_billing', null, 'left')
            ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
            ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
            ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
            ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
            ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

        $this->setCollection($collection);
        //code from Mage_Adminhtml_Block_Widget_Grid::_prepareCollection()
        //since calling parent::_prepareCollection will render the code above useless
        //and you cannot call in php parent::parent::_prepareCollection()
        if ($this->getCollection()) {

            $this->_preparePage();

            $columnId = $this->getParam($this->getVarNameSort(), $this->_defaultSort);
            $dir      = $this->getParam($this->getVarNameDir(), $this->_defaultDir);
            $filter   = $this->getParam($this->getVarNameFilter(), null);

            if (is_null($filter)) {
                $filter = $this->_defaultFilter;
            }

            if (is_string($filter)) {
                $data = $this->helper('adminhtml')->prepareFilterString($filter);
                $this->_setFilterValues($data);
            }
            else if ($filter && is_array($filter)) {
                $this->_setFilterValues($filter);
            }
            else if(0 !== sizeof($this->_defaultFilter)) {
                $this->_setFilterValues($this->_defaultFilter);
            }

            if (isset($this->_columns[$columnId]) && $this->_columns[$columnId]->getIndex()) {
                $dir = (strtolower($dir)=='desc') ? 'desc' : 'asc';
                $this->_columns[$columnId]->setDir($dir);
                $this->_setCollectionOrder($this->_columns[$columnId]);
            }

            if (!$this->_isExport) {
                $this->getCollection()->load();
                $this->_afterLoadCollection();
            }
        }

        return $this;
    }

    /**
     * override the _prepareColumns method to add a new column after the 'email' column
     * if you want the new column on a different position just change the 3rd parameter
     * of the addColumnAfter method to the id of your desired column
     */
    protected function _prepareColumns(){
        $this->addColumnAfter('news_letter', array(
            'header'    => Mage::helper('customer')->__('Mobile'),
            'index'     => 'mobile'
        ),'email');
        return parent::_prepareColumns();
    }
}

A:
 /**
 * Preparing customer collection
 */
public function setCollection($collection)
{

    $collection->addAttributeToSelect('newsletter_subscribed');
    parent::setCollection($collection);
}

/**
 * Adding columns to customer grid
 */
protected function _prepareColumns()
{

    parent::_prepareColumns();

    $this->addColumnAfter('newsletter_subscribed', array(
        'header' => Mage::helper('sales')->__('Newsletter Subscribed'),
        'index' => 'origin',
        'type' => 'text',
        'width' => '100px',
            ), 'entity_id');
    return parent::_prepareColumns();
}

you can join newsletter_subscriber


text:
Q: numba-pro unable to load CUDA device I'm trying to se if GPU computation will dramatically speed up my code.
I have installed numba-pro through the conda package manager.
However, the module does not seem to able to detect the CUDA device:
 In [1]: import numbapro ; numbapro.check_cude()
Vendor:  Continuum Analytics, Inc.
Package: numbapro
Message: trial mode expires in 30 days
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-0448b95a9b9c> in <module>()
----> 1 import numbapro ; numbapro.check_cude()

AttributeError: 'module' object has no attribute 'check_cude'

In [2]: import numbapro ; numbapro.check_cuda()
---------------------------------------------------------------------------
CudaSupportError                          Traceback (most recent call last)
<ipython-input-2-f7c0deebb46f> in <module>()
----> 1 import numbapro ; numbapro.check_cuda()

/home/phys/users/jonathan.kadmon/anaconda/envs/adam/lib/python2.7/site-packages/numbapro/__init__.pyc in check_cuda()

/home/phys/users/jonathan.kadmon/anaconda/envs/adam/lib/python2.7/site-packages/numba/cuda/device_init.pyc in is_available()
     19     This will initialize the driver if it hasn't been initialized.
     20     """
---> 21     return driver.driver.is_available and nvvm.is_available()
     22
     23

/home/phys/users/jonathan.kadmon/anaconda/envs/adam/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.pyc in is_available(self)
    187     def is_available(self):
    188         if not self.is_initialized:
--> 189             self.initialize()
    190         return self.initialization_error is None
    191

/home/phys/users/jonathan.kadmon/anaconda/envs/adam/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.pyc in initialize(self)
    182         except CudaAPIError as e:
    183             self.initialization_error = e
--> 184             raise CudaSupportError("Error at driver init: \n%s:" % e)
    185
    186     @property

CudaSupportError: Error at driver init:
Call to cuInit results in CUDA_ERROR_NO_DEVICE:

Some background:

*

*The anaconda was installed as a user on a linux machine. I don't have superuser.

*the filesystem is part of a NAS that holds all the home folders in my institution.

*the anaconda was originally installed on the NAS through a different machine with same architecture but probably without a GPU.

*On the computer with the GPU I have created a new environment and installed numbapro, which installed also all the dependencies, including cudatoolkit

*I am ssh'ing into the machine from a remote laptop (maybe the driver is not initialised when I use ssh

*I don't have lspci installed so i can't check the the GPU however I can see the device through:
cat /proc/driver/nvidia/version
NVRM version: NVIDIA UNIX x86_64 Kernel Module  355.11  Wed Aug 26 16:35:41 PDT 2015
GCC version:  gcc version 4.8.5 (Gentoo 4.8.5 p1.3, pie-0.6.2)
Any help would be highly appreciated. Is that an ssh issue (I will not have access to the machine itself for a few days)? Is that a problem with the build and link of the packages?

A: Indeed it was a problem with ssh.
The problem was solved by the IT adding my username that initialises the GPU on each logon.


text:
Q: Injected fields becoming Null after Self Injection I have a use case where i need to call methods inside my Bean using Bean instance and not directly to execute some actions on every method, So after searching for some suggestions I found that self injecting a Bean into itself and calling methods can work but every time I refer some other injected field, i get a Null pointer exception. I am calling ServiceA.methodA() from some other Bean for testing.
Code:
@Component
public Class ServiceA {

@Autowired
ServiceB serviceB;

@Autowired
ServiceA dummyService;

public void methodA(){
dummyService.methodB();
}
public void methodB(){
serviceB.getData();  //Service B is null here;
 }

}

I get null pointer exception when trying to access serviceB bean inside self injected Bean, I tried several solutions like getting dummyService from applicationContext , using @PostConstruct but none seems to work. Can anyone help me understand whats incorrect in this approach?


text:
Q: @EndpointsAliasProperty and @Model.query_method causes BadRequestError(Key path element must not be incomplete:...) Hey so right now I'm developing backend api using Google ProtoRPC and Endpoints. I'm using the endpoints-proto-datastore library.
So strange things happen here, here is the EndpointsModel class
class AssetData(EndpointsModel):
    type = msgprop.EnumProperty(AssetType, indexed=True)

    def auth_id_set(self, value):
        if ApplicationID.get_by_id(value) is None:
            raise endpoints.UnauthorizedException('no auth_id')

        self._auth_id = value

    @EndpointsAliasProperty(required=True, setter=auth_id_set, property_type=messages.IntegerField)
    def auth_id(self):
        return self._auth_id

    def app_id_set(self, value):
        if ApplicationID.query(ApplicationID.app_id == value).get() is None:
            raise endpoints.UnauthorizedException('wrong app_id')

        self._app_id = value

        if self.check_auth_app_id_pair(self.auth_id, value):
            self._app_id = value
        else:
            raise endpoints.BadRequestException('auth_id and app_id mismatch')

    @EndpointsAliasProperty(required=True, setter=app_id_set)
    def app_id(self):
        return self._app_id

    @staticmethod
    def check_auth_app_id_pair(authen_id, applic_id):
        dat = ApplicationID.get_by_id(authen_id)
        if dat.app_id != applic_id:
            return False
        else:
            return True

and this is the API class
@endpoints.api(...)
class AssetDatabaseAPI(remote.Service):

    @AssetData.query_method(query_fields=('limit', 'order', 'pageToken', 'type', 'auth_id', 'app_id'),
                            path='assets', http_method='GET', name='assets.getAssetMultiple')
    def assets_get_multiple(self, query):
        return query

When I deploy this, everytime I tried to access assets.getMultipleAssets it just gives me this error
raised BadRequestError(Key path element must not be incomplete: [ApplicationID: ]). Strangely enough this only happen to method using @Model.query_method, I have other methods using the same system but using @Model.method and it just runs ok.
If I tried it in development server, sometimes it just gives me RuntimeError: BadRequestError('missing key id/name',) then if I just re-save the .py file and retry it, it will work (sometimes not and another re-save can also make the error happens again).
Can anyone tell me my mistake?
Thanks

A: I think your problem is how you call this method - it's a static method, so you have to access it through class, not the instance (self):
    if AssetData.check_auth_app_id_pair(self.auth_id, value):
        self._app_id = value
    else:
        raise endpoints.BadRequestException('auth_id and app_id mismatch')


text:
Q: Connection of branches
*

*I can't understand the meaning of kernel function in a Fourier space. What is the relation between the Fourier kernel $K(w,t)$ and homomorphism?

*Please explain the connection of Mathemetics with: the Fourier, group, Linear-Algebra and Integral calculus.

A: The connection between branches of mathematics you are seeking is best given as a response to your second question. Alas, I will provide a response to both questions to clear up, what seems to be, confusion due to terminology.
question 1). First, lets refresh ourselves of the defintion of a homomorphism. A homomorphism is a map between two algebraic structures of the same type, that preserves the operations of the structures. This means a map
$f$ : $A \to B$
between the sets $A$ and $B$ equipped with the same structure such that, if $\bullet$ is an operation of the structure (which we will assume, for simplification, to be a binary operation), then
$f(a_{1} \bullet a_{2}) = f(a_{1}) \bullet f(a_{2})$, $\forall a \in A$.
With that in mind, the kernel of a homormpism is the subet $Ker_{f} :=$ {$a \in A$: $f(a) = e_{B}$} $\subseteq A$ where $e_{B}$ is the identity element in $B$. I can see how this idea of the kernel as a set can be confused with the kernel of an integral since this terminology overlaps with the fact that, for example, the definite integral is is a homomorphism. Observe: let $P$ be a set whose elements are polynomials, therefore there exists a map $I : P \to \mathbb{R}$ such that $I(p)$ $:= $$\int_0^1$$p(x)dx$. However, some authors call the argument $p(x)$ of the integral $I$ the kernel of the integral. Therefore with our definition of the map $I$, there exists a subset $Ker_{I} \subseteq P$ such that
$Ker_{I}:=$ {$p \in P$: $\int_0^1$$p(x)dx$ $= 0$}.
The overlap in terminology here is that $Ker_{I}$ is the kernel of the homomorphism $I$, but the argument of the integral (that defines $I$) according to some literature is considered "the kernel of the integral".
So in the context of the the Fourier integral transform $T$ of the following form
$(Tf)(u)$ $:= $$\int_{t_{1}}^{t_{2}}$$f(t)K(t,u)dt$
by the explanation above, there is no real connection between the Fourier kernel $K(t,u)$ and the kernel of a homomorphism besides a sloppy use of terminology.
question 2). The connection between linear algebra, group theory, and integral calculus is that in all three branches we study homomorphisms. Whether or not its between vector spaces or algebraic structures. In particular, in integral calculus we study maps like $I$ that we defined above from the set $P$ to the real numbers. One thing to obviously note is, as i'm sure you've noticed, we use integral calculus when studying Fourier transformations.


text:
Q: Delete any row from DataGridView as well as from database I want to delete the selected row from DataGridView as well as the database. My code works only for the first row, for every other row it gives exception "Index was out of Range".
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand();
        string itemId;
        if (dgPartyDetails.SelectedCells.Count > 0)
        {
            int selectedrowindex = dgPartyDetails.SelectedCells[0].RowIndex;
            try
            {
                DataGridViewRow selectedRow = dgPartyDetails.SelectedRows[selectedrowindex];
                if (selectedRow.Selected == true)
                {
                    dgPartyDetails.Rows.RemoveAt(selectedrowindex);
                    itemId = Convert.ToString(selectedRow.Cells[0].Value);
                    con.Open();
                    cmd.CommandText = "DELETE FROM tblParty WHERE Id=" + itemId + "";
                    cmd.Connection = con;
                    int count = cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

A: It appears that you removed the DataGridRow before obtaining it's value.
dgPartyDetails.Rows.RemoveAt(selectedrowindex);
itemId = Convert.ToString(selectedRow.Cells[0].Value);

Reversing the order of these statement would fix your problem.
itemId = Convert.ToString(selectedRow.Cells[0].Value);
dgPartyDetails.Rows.RemoveAt(selectedrowindex);

A: maybe u can try sqldatasource. for example:
<asp:SqlDataSource ID="sdsJur" runat="server"
           ConnectionString="<%$ ConnectionStrings:NilaiConnectionString %>"
           DeleteCommand="DELETE FROM [Jurusan] WHERE [Kd_Jurusan] = @Kd_Jurusan"
           InsertCommand="INSERT INTO [Jurusan] ([Jurusan]) VALUES (@Jurusan)"
           SelectCommand="SELECT * FROM [Jurusan]"
           UpdateCommand="UPDATE [Jurusan] SET [Jurusan] = @Jurusan WHERE [Kd_Jurusan] = @Kd_Jurusan">
           <DeleteParameters>
               <asp:Parameter Name="Kd_Jurusan" Type="Int32" />
           </DeleteParameters>
           <InsertParameters>
               <asp:FormParameter FormField="tbJurusan" Name="Jurusan" />
           </InsertParameters>
           <UpdateParameters>
               <asp:Parameter Name="Jurusan" Type="String" />
               <asp:Parameter Name="Kd_Jurusan" Type="Int32" />
           </UpdateParameters>
</asp:SqlDataSource>`

and then u can use Gridview(I think similar to datagrigview). for example:
<asp:GridView ID="gvJurusan" runat="server" AllowPaging="True"
     AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Kd_Jurusan"DataSourceID="sdsJur">
     <Columns>
         <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
         <asp:BoundField DataField="Kd_Jurusan" HeaderText="Kd_Jurusan" InsertVisible="False" ReadOnly="True" SortExpression="Kd_Jurusan" />
         <asp:BoundField DataField="Jurusan" HeaderText="Jurusan" SortExpression="Jurusan" />
     </Columns>
</asp:GridView>`

hope it usefull


text:
Q: Coded-UI-Tests: record button is disabled I'm trying to create Coded-Ui tests for a WPF application, I'm following the msdn tutorial.
My problem: the "record" button is available, but disabled, so I'm not able to start recording.
Any idea?
My environment: Windows 10 / MSVS Entreprise 2015

A: I was launching a Windows Store Coded UI and not a Windows Desktop one.
Problem fixed.


text:
Q: Filter data sets with LINQ by year of a date Here is my LINQ Statement:
var query = from s in ctx.location
    join b in ctx.order on s.locationID
    equals b.ID
    join e in ctx.offerdata on b.OrderID
    equals e.OrderID

    where e.delDate.Value.Year == 2013

   orderby e.identity_no
   select new Order
   {
...

   };

  return query.ToList();

My delDate is a ?DateTime, and for example it looks like 2013-05-15 14:10:00 (yyyy-MM-dd hh:mm:ss).
But I want to receive all data sets e.g. for the year 2013. (or any other year I choose).
But the where e.delDate.Value.Year  statement do not offer a .Contains Method, so how can I do this?
Thanks a lot!

A: Your best bet here would be to construct a range, i.e.
var start = new DateTime(2013,1,1), end = new DateTime(2014,1,1);
...
    where e.delDate.Value >= start && e.delDate.Value < end

You could also use the date-part utilities, but that then depends on what the LINQ provider supports; pretty much any provider will support a basic range.


text:
Q: Browsers are requesting twice on load I have a script that plays music and because of the nature of the script it seems to be running 2 connections for every 1 listener.
What that means is it is creating 2 documents inside Mongodb.
I am wondering is there a way to tell mongoose to not insert document within 5 seconds if the insert has already ran?
I have run a console.log(req.url)
and I get the following
/dance?uuid=6f70c645-4ef4-4042-854d-a6e87b61e45f

/dance?uuid=6f70c645-4ef4-4042-854d-a6e87b61e45f

Which means it is requesting the file twice on load.
Is there away to only allow 1 request to go through and discard the other?
I have tried
router.get('/:stationname', (req, res, next) => {
  console.log(req.url)
});

Also tried the following
var doCSUpdateAlreadyCalled = false;
router.get('/:stationname', (req, res, next) => {
  if (!doCSUpdateAlreadyCalled) {
    doCSUpdateAlreadyCalled = true
    console.log(req.url)
  }
});

But it still runs twice.


text:
Q: Parse Column Data in SQL Server Management Studio I have a column of events that are formatted as shown:
Production-PMPO_1-2017-02-14 15:30:00.000

Can I parse out the beginning either in SQL Server Management Studio or in VS (vb.net) to make it have DateTime only?
Such as 2017-02-14 15:30:00

A: Since the datetime part is always 23 characters long you can use RIGHT
SELECT RIGHT(x.Col, 23) as dt
FROM (SELECT 'Production-PMPO_1-2017-02-14 15:30:00.000' as Col) x

With VB.NET you could use Substring:
Dim dt As String = str.Substring(str.Length - 23)

A: If Production-PMPO_1- is fixed,then you can do it by just replacing it with empty string.
DECLARE @a VARCHAR(100)='Production-PMPO_1-2017-02-14 15:30:00.000'
SELECT REPLACE(@a,'Production-PMPO_1-','');


text:
Q: cant return value out of closure I cant seem to get this value to pass the isValid value back out of the ajax call in the snippet below:
    function isShortUrlAvailable(sender, args) {
        var isValid = false;
        $.ajax({
            type: "POST",
            url: "/App_Services/ShortUrlService.asmx/IsUrlAvailable",
            data: "{url: '" + args.Value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                isValid = response.d;
            },
            error: function (msg) {
                isValid = false;
            }
        });

        args.IsValid = isValid;
    }

I'm sure its just something simple to do with closures that i'm overlooking. Can anyone help please?
Its for an asp.net custom validator.
This is what's happening:

*

*isValid is set to false in the first line

*.ajax() request fires correctly and if its valid returns true

*isValid is set to true (response.d) correctly

*when it comes back out to the last line it thinks isValid is false again

A: AJAX methods are asynchronous meaning that you're value is set to false, the AJAX call is started, but whilst it's happening the args.IsValid line is called. Just remove the variable and set the args.IsValid value in each scenario:
function isShortUrlAvailable(sender, args) {
    $.ajax({
        type: "POST",
        url: "/App_Services/ShortUrlService.asmx/IsUrlAvailable",
        data: "{url: '" + args.Value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            args.IsValid = response.d;
        },
        error: function (msg) {
            args.IsValid = false;
        }
    });
}


text:
Q: Auto-refresh calendar list / web part (SharePoint 2010) How can you auto-refresh a SharePoint 2010 calendar list / web part, without needing to refresh the whole page? Tasks and other list types seem to have this option (under 'AJAX Options'), but not calendars.

A: modify master page and add Java-script simple code to that refresh it every N seconds.
you can search with Google and using those JS codes.
this is helpful for those pages that contains these web parts >> like charts and calendar and etc. that we haven't those options.
after this answer i search here in this stack and found similar question and answer:
https://sharepoint.stackexchange.com/a/27489/5170

A: I would recommend using content web part instead of modifying master page to store JS. But in other steps I agree with "saber tabatabaee yazdi".