Q: KineticJS not working in FF and IE My program works perfectly in Chrome, but with FF and IE my canvasses are gone.
The error I got with Firefox is:
SyntaxError: An invalid or illegal string was specified:
...][c].apply(this[b],args)}})(c)}}(),function(){Kinetic.Filters.Grayscale=function...
On kineticJS.js (line 28) (KineticJS JavaScript Framework v4.4.0)

The error I got with IE is:
SCRIPT5022: SyntaxError
h.addColorStop(g[i],g[i+1])
on kineticJS.js, line 28 character 7356

Does somebody know whats going on?
EDIT 3:
When I use fill: 'white' instead of
background = new Kinetic.Rect({
          x: 0,
          y: 0,
          fillRadialGradientStartPoint: 0,
            fillRadialGradientStartRadius: 0,
            fillRadialGradientEndPoint: 0,
            fillRadialGradientEndRadius: 800,
            fillRadialGradientColorStops: [0, '#262834', 1, '0f1114'],
          width: browserwidth,
          height: browserheight,
          name: 'background'
    });

That is placed in 'background' Rect that scales with the browserheight I got no erros in IE 10, 9 and FF.
But why is it happen only with fillRadialGradient and only in IE and FF? It has a connection with the error I mentioned before:
 h.addColorStop(g[i],g[i+1])
on kineticJS.js, line 28 character 7356

What it makes more strange is that I have another object with radialgradientfill which works fine in FF and IE.
var lichtrondje = new Kinetic.Circle({
                  x: 0,
                  y: 0,
                  radius: 90,
                  fillRadialGradientStartPoint: 0,
                  fillRadialGradientStartRadius: 0,
                  fillRadialGradientEndPoint: 0,
                  fillRadialGradientEndRadius: 90,
                  fillRadialGradientColorStops: [0, '#DDD', 1, 'rgba(0,0,0, 0.0)'],
                  opacity: 1,
                  id: 'lichtrondje' + x,
                  name: 'lichtrondje'
            });

I have found out that the result looks different between the Chrome version and the FF and IE version. The right one is what its intended.

A: I believe you are missing a # in the fillRadialGradientColorStops array
0f1114 --> #0f1114


Q: What is the optimal speed which minimizes the overall cost? The cost of fuel for a car is proportional to the square of the car's speed. If you drive the car at 25 mph, the cost is $25.
The other costs which are independent of speed amounts to $100. What is the optimal speed which minimizes the cost?

A: With the given information we know
$$\text{Cost from speed}(v)=av^2$$
for some constant $a$. We also know
$$25=\text{Cost from speed}(25)=a25^2$$
$$\Rightarrow a=\frac{1}{25}$$
This implies
$$\text{Total Cost}(v)=100+\text{Cost from speed}(v)=100+\frac{v^2}{25}$$
This is minimized for $v=0$.


Q: JVM crashing when using any other Hibernate inheritance strategy besides SINGLE_TABLE Ok, this is probably a longshot but here goes.
In Java (JRE 1.6.0_26-b03) I have two classes, SuperControl and its subclass SubControl. They both need to be persistent objects and I'm using Hibernate Annotations to achieve this. I have approximately 210 classes that are being persisted correctly. Except one isn't.
My problem is that SubControl refuses to inherit in any way besides SINGLE_TABLE. When I say "refuses", I mean that the entire JRE crashes.
This is a bit problematic because I'd really prefer SuperControl to be a mapped superclass of SubControl. SuperControl can also be a persistent entity in its own right. The strange thing is that I have an exactly parallel hierarchy in my code elsewhere that works correctly.
This is what I want:
@Entity
@MappedSuperclass
public class SuperControl extends ItsSuperClass {
  // ...
}

@Entity
public class SubControl extends SuperControl {
  // ...
}

but it bombs out with the error
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  Internal Error (c1_Optimizer.cpp:271), pid=5456, tid=1260
#  guarantee(x_compare_res != Constant::not_comparable) failed: incomparable constants in IfOp
#
# JRE version: 6.0_26-b03
# Java VM: Java HotSpot(TM) Client VM (20.1-b02 mixed mode, sharing windows-x86 )
# An error report file with more information is saved as:
# C:\eclipse\hs_err_pid5456.log

Without supplying any inheritance hint, Hibernate defaults to SINGLE_TABLE (which I can tell thanks to the creation of a DTYPE column). I can explicitly specify this without the JVM crashing.
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class SuperControl extends ItsSuperClass {
  // ...
}

@Entity
public class SubControl extends SuperControl {
  // ...
}

The worst part is that if I remove the SubControl class ENTIRELY, or even just its mapping in the hibernate.cfg.xml file, the JVM still crashes. This leads me to believe that there's some kind of hidden linkage between SuperControl and SubControl. Maybe something cached in Eclipse or the like. I've restarted Eclipse, done several clean-and-builds, and even restarted my machine, and the problem's still there.
Any ideas? I've been working on this for hours and have gotten nowhere.
Thanks!

A: This looks like a bug 7042153, aka 2210012 reported in early May.
Note the workaround offered by one user: using the "-server" JVM option fixed it for them.

A: Try Java 1.6.0_20, and check if that works. You have found a JVM bug, and going back 6 minor versions might be enought to get this running.
You are lucky in the way that this bug is reproducable, so create a minimal testcase and post it to the Oracle bug database.


Q: How can I make a python API to ping an ip address? So I have a discord bot and I want to add a feature where it pings an IP and tells you if it's online or not. I wanted to use an API in flask in case I use it for other projects.

A: In order to ping using python, you can use the pythonping package.
You can also easily use it in flask.
A sample of the package at play is shown below.
import flask
from pythonping import ping

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/', methods=['GET'])
def home():
    return ping('127.0.0.1', verbose=True)

app.run()

A: You can use the requests package to perform this operation as follows:
import requests
url = 'https://stackoverflow.com/'
is_up = requests.get(url).status_code == 200
print(f'{url}, up_status={is_up}')


Q: Sitecore: How to get the class entered in General Link field In the General Link field content author will set some class.
I want to change the class while rendering, so I used the reflector and got the code of Link.cs and trying to extend the PopulateParameters method and looks like this.CssStyle and this.CssClass are always blank. Is there any way to get the value of class entered in the General Link field?

A: Cast your field to LinkField class and use Class property:
LinkField field = Sitecore.Context.Item.Fields["Link"];
string cssClass = field.Class;

**EDIT: **
If you want to change behaviour of Sitecore sc:link to change css class of every link, you need to add your own processor to the renderField pipeline:
public class UpdateLinkClass
{
  public void Process(Sitecore.Pipelines.RenderField.RenderFieldArgs args)
  {
    if (args != null && (args.FieldTypeKey == "link" || args.FieldTypeKey == "general link"))
    {
      Sitecore.Data.Fields.LinkField linkField = args.Item.Fields[args.FieldName];
      if (!string.IsNullOrEmpty(linkField.Class))
      {
        args.Parameters["class"] = linkField.Class + "-custom";
      }
    }
  }
}

and register it before GetLinkFieldValue processor:
<processor type="My.Assembly.Namespace.UpdateLinkClass, My.Assembly" />
<processor type="Sitecore.Pipelines.RenderField.GetLinkFieldValue, Sitecore.Kernel" />


Q: TexStudio: Multiple Cursors in Macro however looking up my questions using the usual suspects (Google, search function etc.) I could not find an answer/solution to the following task (potentially I don't know the proper name of the task I am looking for XD ):
In Texstudio I want to create my own macro/snippet for a figure environment, where the cursor is placed at a certain position to enter the filename. However I would like to have the same text filled in another position while I type (such as in the cmd+E environment snippet).
\begin{figure}[t]
\centering
    \includegraphics{pics/%<%>}
    \caption{}
    \label{fig:%<%>}
\end{figure}

The /%<%> places my cursor at the desired position, but I am not able to figure out how to autofill this text in the label command while typing.
The second /%<%> just provides another cursor position which I can access manually.
I appreciate any help. So thanks in advance!

A: For clarification
Multiple cursors are not supported. This would be something like
% NOT SUPPORTED
\includegraphics{pics/%|}
\caption{}
\label{fig:%|}

Mirrored placeholders are supported. This is an undocumented function and may change in the future without further notice.
% THIS DOES WORK
\includegraphics{pics/%<%:id:1%>}
\caption{}
\label{fig:%<%:mirror,id:1%>}

A: I can see the problem. You are using a "/" which is only to indicate the image is in a subfolder. The code to positioning the cursor it's just conformed by %<%>. Creating a macro for inline math code, it look like
$ %<%> $
Inclusive, you can include text inside it, like a tag for reference:
$ %< tag %> $
If your macro has more than one cursor positions, with "ctrl+rightarrow" you will move the cursor to the next one position when you work with your macro. With "ctrl+leftarrow" you can reverse the position.


Q: Gödel's completeness theorem and the undecidability of first-order logic I'm working through this module, "Undecidability of First-Order Logic" and would love to talk about the two exercises given immediately after the statement of Godel's completeness theorem.
First, note Definition 2.1 from the text: A sentence $\varphi$ is valid if it is true in all models. In contrast, $\varphi$ is satisfiable if it is true in some model. Then the exercises are given as follows:

*

*Let $\varphi$ be a sentence in first-order logic. Show that $\varphi$ is valid if and only if $\neg\varphi$ is not satisfiable, and consequently that $\varphi$ is satisfiable if and only if $\neg\varphi$ is not valid.

*Suppose that we have an algorithm $\mathcal{A}$ to tell whether a sentence of first-order logic is satisfiable or not. Show that we can use this to get an algorithm $\mathcal{B}$ to tell whether a sentence of first-order logic is provable or not.
Conversely, suppose that we have an algorithm $\mathcal{B}$ to tell whether a sentence of first-order logic is provable or not. Show that we can use this to get an algorithm $\mathcal{A}$ to tell whether a sentence of first-order logic is satisfiable or not.
The first exercise seems pretty straightforward. My answer:

*

*Let $\mathscr{M}$ be a model and read "$\varphi$ is true in $\mathscr{M}$" for $\mathscr{M}\models\varphi$. Then by the definitions above and basic facts of logic (such as DeMorgan's laws for quantifiers), the equivalence $\forall \mathscr{M} (\mathscr{M}\models\varphi) \equiv \neg\exists \mathscr{M} (\mathscr{M}\models\neg\varphi)$ holds as desired. The same goes for the restatement introduced by "consequently" in the exercise, i.e. $\exists \mathscr{M}(\mathscr{M}\models \varphi) \equiv \neg\forall(\mathscr{M}\models\neg\varphi)$.

Make sense? Anybody spot any errors, or feel like suggesting improvements of any kind?
Okay. Now the second exercise is where things get more interesting, at least for me, because I don't fully grasp this idea of correspondence between "valid" and "provable," which is the core of Gödel's completeness theorem.
Looking at what Wikipedia has to say about the theorem, I feel like I basically understand the result, but am still unsure how I would apply it in terms of the second exercise.
Take the first part of the problem: all I've got is an algorithm $\mathcal{A}$ that decides satisfiability of $\varphi$. The completeness theorem establishes an equivalence between syntactic provability and semantic validity. I can't figure out how to cross the chasm from satisfiability to validity, or otherwise find the logical connection I would need to use the theorem to solve my problem.
While searching for similar questions before posting, I found this one, which offers some stimulating food for thought but deals with different givens, namely: an algorithm that takes a $\varphi$ and returns $\varphi'$ such that $\varphi$ is satisfiable iff $\varphi'$ is valid. I can see that this is getting close to what I need, but again I can't see how to adapt it to my purposes.
Can anyone offer a hint, a suggestion, or pointer of any kind? I would much appreciate it.

A: You got the right idea for part 1, but it is unusual to use the logical notation that you do: $\neg$, $\forall$, and $\exists$ are logical operators, but $\models$ is a metalogic symbol; purists will not like you mixing those up. So, it may be better to use the English 'some' and 'all' and 'not'
For part 2: here is where you use the result of part 1!  In particular, in order to decide whether $\varphi$ is valid or not, you can decide whether $\neg \varphi$ is satisfiable or not: if $\neg \varphi$ is satisfiable, then $\varphi$ is not valid, but if $\neg \varphi$ is not satisfiable, then $\varphi$ is valid. And now you just combine that with Godel's completeness result (to be precise: the theorem that a statement is provable if and only if it is valid ... the more difficult 'if' part of which is the completeness theorem): if $\varphi$ is valid, then it is provable, and if $\varphi$ is not valid, then it is not provable.
So for that first part: if you have algorithm $\mathcal{A}$ that can figure put whether $\varphi$ is satisfiable or not for any $\varphi$, then design algorithm $\mathcal{B}$ that is trying to figure out whether $\varphi$ is provable or not as follows:

*

*Take in $\varphi$

*Negate $\varphi$

*Call algorithm $\mathcal{A}$ with $\neg \varphi$
4a. If algorithm $\mathcal{A}$ says that $\neg \varphi$ is satisfiable, then print '$\varphi$ is not provable!'
4b. If algorithm $\mathcal{A}$ says that $\neg \varphi$ is not satisfiable, then print '$\varphi$ is provable!'

A: For my own purposes, I'm archiving here my best attempt at integrating, in a compact manner, everything that was mentioned in the answers to my original question. Any comments or critiques of any kind are always welcome. Thanks again to the contributors.
Definitions. A sentence $\varphi$ is valid if it is true in all models. In contrast, $\varphi$ is satisfiable if it is true in some model.
Completeness theorem with soundness. A sentence in first-order logic is provable if and only if it is valid.
Then the answers to the problems stated above can be given as follows:

*

*Let $\mathscr{M}_x$ be a model, $x\in\mathbb{N}$. Let $\varphi$ be a sentence in first-order logic. Let $P(x)$ be the predicate "$\varphi$ is true in $\mathscr{M}_x$." Then $\forall x P(x) \equiv \neg \exists x P(x)$ and $\exists x P(x) \equiv \neg \forall x \neg P(x)$ by the above definitions and De Morgan's laws.

*Suppose we have $\mathcal{A}$. Let $\mathcal{B}$ be the algorithm defined by the following procedure. Step 1: take $\varphi$ as input. Step 2: negate $\varphi$. Step 3: call $\mathcal{A}$ with input $\neg\varphi$, written $\mathcal{A}(\neg\varphi)$. Step 4, case (a): If $\mathcal{A}(\neg\varphi)$ returns "$\neg\varphi$ is satisfiable," then by the above equivalences $\varphi$ is not valid and by the completeness theorem it is not provable. Step 4, case (b): If $\mathcal{A}(\neg\varphi)$ returns "$\neg\varphi$ is not satisfiable," then by the above equivalences $\varphi$ is valid and by the completeness theorem it is provable. Thus by making use of $\mathcal{A}$ we have obtained $\mathcal{B}$ such that $\mathcal{B}$ decides whether $\varphi$ is provable or not. By a symmetric argument we can obtain $\mathcal{A}$ if given $\mathcal{B}$.


Q: Does the radius of the quadrant pass from the center of the inscribed circle? In the following picture:

The smaller circle is inscribed inside the quadrant, whose radius (OB) is 8. The original question (but not the question of this post) is that "find the radius of the inscribed circle and the area of shaded part". I managed to solve the problem using the guess that the line OT passes from the point P (P is the center of the inscribed circle). But I am not able to prove this. Can you give me a hint about how can I prove that OT passes the point P?

A: Notice that a tangent line passing through the point $T$ is tangent to both the quarter circle and the inscribed circle.  That means the radii of the inscribed circle and the quarter circle are both perpendicular to the tangent line passing through the point $T$.  That means the radius of the inscribed circle coincides with the radius from the quarter circle.

A: The  great and the small circles have a common tangent in $T$ , so the orthogonal to this tangent passes through $P$ and $O$.


Q: Adding picture linked to feature in QGIS report layout I'm trying to make a report in QGIS, in the attribute table of my layer, I have a column named "picture1" filled with the relative path of a picture, that illustrate the feature.
In the report, I did a "Field group section" with my layer and a map controlled by report. Now I would like to add the picture related to each feature, in order to have one page by feature with its location and its picture. With the button next to "image source", I tried to choose the "field type" that identify each feature and also to write concat(@project_folder, '/', "picture1.jpg") in the expression, but neither of them worked...
Do you have an idea how to resolve this?

A: It appears you need to add the image by going to the Field Group Section and clicking Edit next to Include Body, and if the little grey tab above the layout shows you're in the Body: Group element, then you can access the fields of your Group layer for the image source field list, etc.

Keep in mind though it doesn't seem to work properly at first - at least for me I needed to test export a pdf before it seemed to actually place values in the text boxes/image in the image item, etc.


Q: Read system Call I am trying my hands with unix socket programming in C. But while reading I am getting Err No as 4. I am unable to find out the description of this error code. Does anybody have any idea?

A: If you would start with looking at ultimate source of Unix error code names (/usr/include/errno.h) you'll arrive at the file which contains your error code as
#define EINTR            4      /* Interrupted system call */

(Which is this file is left for you to find out, as an exercise ;))

A: The errno values can be different for different systems (even different Unix-like systems), so the symbolic constants should be used in code.
The perror function will print out (to stderr ) a descriptive string of the last errno value along with a string you provide.
man 3 perror

The strerror function simply returns a const char * to the string that perror prints.
If 4 is EINTR on your system then you received a signal during your call to read.  There are ways to keep this from interrupting your system calls, but often you just need to:
while (1) {
   ssize_t x = read(file, buf, len);
   if (x < 0) {
       if (errno == EINTR) {
           errno = 0;
           continue;
       } else {
          // it's a real error

A: If you're getting EINTR, it probably means you've installed a signal handler improperly. Good unices will default to restartable system calls when you simply call signal, but for safety, you should either use the bsd_signal function if it's available, or call sigaction with the restartable flag to avoid the headaches of EINTR.


Q: add custom class to wysihtml5 text editor I'd like to be able to add a button that adds my own custom class. I don't see this in the documentation anywhere but seems like a common request.
For example.
Highlighting "Some Text" and pressing the button "Custom Class" will add

Some Text

A: Define new command, my example is based on ForeColor:
(function(wysihtml5) {

  wysihtml5.commands.setClass = {
    exec: function(composer, command, element_class) {
        element_class=element_class.split(/:/);
        element=element_class[0];
        newclass=element_class[1];
      var REG_EXP = new RegExp(newclass,'g');
    //register custom class
      wysihtml5ParserRules['classes'][newclass]=1;

      return wysihtml5.commands.formatInline.exec(composer, command, element, newclass, REG_EXP);
    },

    state: function(composer, command, element_class) {
        element_class=element_class.split(/:/);
        element=element_class[0];
        newclass=element_class[1];
        var REG_EXP = new RegExp(newclass,'g');
      return wysihtml5.commands.formatInline.state(composer, command, element, newclass, REG_EXP);
    }
  };
})(wysihtml5);

usage:
HTML:

   <button data-wysihtml5-command="setClass" data-wysihtml5-command-value="span:my-wysihtml5-custom-class" type="button" title="View HTML" tabindex="-1" class="btn btn-mini">
       My class
   </button>

so as you can see value is from two parts: element:class
DEMO


Q: Download URL text file directly to csv file python I have a link to a text file from US Census and I would like to download it into a directory on my computer.
I was thinking about downloading the URL into a text file and then converting the text file into a csv later on. However, I was wondering if it were possible to download directly to a csv file? If it's possible, would appreciate an example.
This is the link to the data:
https://www.census.gov/construction/bps/txt/tb2u2010.txt

A: I may be wrong here, but saving that as a .csv file would not be easy. I don't know Python very much but I'll leave my two cents here:
import urllib.request  # lib that handles URLs

target_url = "https://www.census.gov/construction/bps/txt/tb2u2010.txt"

data = urllib.request.urlopen(target_url)

with open('output.txt', 'w') as f:  # change this to .csv
    for line in data:
        f.write(str(data.read()))

This will create a .txt with everything from the website on a single line.


Q: Sprint boot: POST an entity with a foreign key I am playing around with Spring boot and I am trying to post an entity that has foreign keys
Example: product (id,code, description, category) and category(id, category)
To post a product i would post {"code":"123","description":"bananas"}
How would I specify the category?
{"code":"123","description":"bananas","category":1} doesn't seem to work
I saw a post here relating to Spring Data that sugested using the URI of the primary table https://stackoverflow.com/questions/44497114/post-an-entity-with-spring-data-rest-which-has-relations

is there a simpler way ?

A: One option is to specify category as json object like below
 {"code":"123","description":"bananas","category": { "id" : 1}}


Q: Uncaught Reference Error: draw is not defined I am trying to complete This tutorial on making a tic tac toe game using JavaScript and HTML5.
I've followed each step in the video multiple times. While my code seems to match the code in video I keep encountering an error: Uncaught Reference Error: draw is not defined. The error occurs in line 12.
I must be overlooking something. Can anyone point it out?
  <!DOCTYPE html>
    <html>
    <head>
    <title>Tic Tac Toe!</title>
        <script type="text/javascript">
var c, canvas;
var turn = 1;
window.onload = function() {
    canvas = document.getElementById("canvas");
    c = canvas.getContext("2d");

    draw();
}

var moves = [];

window.onclick = function(e) {
    if(e.pageX < 500 && e.pageY < 500) {
        var cX = Math.floor(e.pageX / (500 / 3));
        var cY = Math.floor(e.pageY / (500 / 3));

        var alreadyClicked = false;

        for(i in moves) {
            if(moves[i][0] == cX && moves[i][1] == cY) {
                alreadyClicked = true;
            }

        }
        if(alreadyClicked == false) {
            moves[(moves.length)] = [cX, cY, turn];
            turn = turn * -1;
            draw();
        }

    }

    var bg = new Image();
    var x = new Image();
    var o = new Image();
    bg.src = "ttt_board.png";
    x.src = "ttt_x.png";
    o.src = "ttt_o.png";

    function draw() {
        c.clearRect(0, 0, 500, 500);

        c.drawImage(bg, 0, 0);

        for(i in moves) {
            if(moves[i][2] == 1) {
                c.drawImage(x, Math.floor(moves[i][0] * (500 / 3) + 10), Math.floor(moves[i][1](500 / 3) + 10))
            } else {
                c.drawImage(o, Math.floor(moves[i][0] * (500 / 3) + 10), Math.floor(moves[i][1] * (500 / 3) + 10));
            }
        }
    }
};
    </script>
    </head>

    <body>
    <canvas id="canvas" width="500px" height="500px"></canvas>
    </body>
    </html>

A: The problem is that draw is defined in window.onclick, but you are trying to call it from window.onload. Are you sure you do not have a closing bracket missing before the definition of draw?

A: Try moving the draw() function out of the window.click function.
window.onclick = function(e) {
    // ...
};

function draw() {
    // ...
}

One of the major benefits of being strict with your indentation is that you can pick up these bugs very quickly.
window.click = function(e) {
    // ...
    function draw() {
        // ...
    }
};

Is the code you had.

A: As a result of draw being located inside of the window.onclick anonymous function, it is scoped there. Since window.onload does not share the scope of that anonymous function, you cannot access draw from window.onload. You should removed the draw function from your window.onclick event so that it may be called from other scopes.
function draw(){}
window.onload = function(){ /*code*/ };
window.onclick = function(){ /* code */ };


Q: Heroku ActionView::Template::Error (undefined method `name' for nil:NilClass) First time posting on here. I've got a problem with my web-app when trying to open it through heroku. The app is successfully built by Heroku but when I try to open the app I get the following error:
2017-03-13T06:15:35.778714+00:00 app[web.1]: I, [2017-03-13T06:15:35.778662 #4]  INFO -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] Completed 500 Internal Server Error in 232ms (ActiveRecord: 18.7ms)
2017-03-13T06:15:35.779870+00:00 app[web.1]: F, [2017-03-13T06:15:35.779817 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964]
2017-03-13T06:15:35.780386+00:00 app[web.1]: F, [2017-03-13T06:15:35.779874 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] ActionView::Template::Error (undefined method `name' for nil:NilClass):
2017-03-13T06:15:35.780553+00:00 app[web.1]: F, [2017-03-13T06:15:35.780501 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964]      7:

2017-03-13T06:15:35.780554+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]      8:             <% row_cities.each do |city| %>
2017-03-13T06:15:35.780555+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]      9:
2017-03-13T06:15:35.780556+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]     10:
<%= city.name if city.name %>

2017-03-13T06:15:35.780557+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]     11:
<%= city.country %>

2017-03-13T06:15:35.780558+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]     12:                     <%= link_to "See More", city_path(city) %>
2017-03-13T06:15:35.780559+00:00 app[web.1]: [773bef2b-dfb4-45a9-a15f-0de210ab6964]     13:
2017-03-13T06:15:35.780602+00:00 app[web.1]: F, [2017-03-13T06:15:35.780550 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964]
2017-03-13T06:15:35.780655+00:00 app[web.1]: F, [2017-03-13T06:15:35.780610 #4] FATAL -- : [773bef2b-dfb4-45a9-a15f-0de210ab6964] app/views/home_page/home.html.erb:10:in `block (2 levels) in _app_views_home_page_home_html_erb__1188228438750051727_70102451451540'

Here is the problematic code (views: home.html.erb):

    <% @cities.in_groups_of(3) do |row_cities| %>

            <% row_cities.each do |city| %>

<%= city.name %>

<%= city.country %>

                    <%= link_to "See More", city_path(city) %>

            <% end %>

    <% end %>

And the controller this belongs to just in case (home_page_controller.rb):
class HomePageController < ApplicationController
  def home
    @cities = City.all
  end
end

I've been at this problems for two weeks now and have looked at other questions similar to this. I've tried all answers to no success.
Any help is appreciated.
Regards,
Llausa
P.S Here is how it looks on my localhost server and how I'd like it to look on heroku
How I'd like it to look - image here

A: This is because you are using in_group_of with no option. Replace your code with this:

    <% @cities.in_groups_of(3,false) do |row_cities| %>

            <% row_cities.each_with_index do |city,index| %>

<%= city.name %>

<%= city.country %>

                    <%= link_to "See More", city_path(city) %>

            <% end %>

    <% end %>

More info here.


Q: How to make images snap to any "outline" image (using "animals on the beach" demo) I'm new to Konvasjs and new to canvas and I've been try to make a game similar to the demo "animals on the beach" I wanna keep the part where if it in the right outline the score increases but instead of the animals in the demo snapping to their specific outline I want the animal to be able to snap to any outline so the player can get a wrong answer, or get less score.
Sorry if what I'm asking is actually a lot of stuff.

A: I found an alternative solution this may not automatically allow drag objects to snap to every snap zone but it does allow you to control it with less code.
I created a function to get the object(code) and the zone(outline):
    function snapTo(code, outlineSnap) {
        var outline = outlines[outlineSnap + '_black'];
        if(isNearOutline(code, outline)) {
            code.position({
                x : outline.x,
                y : outline.y
            });

        console.log("privKey:"+ privKey);
        console.log("Key:"+ key);
        console.log(code.id());
        codeLayer.draw();
        var testKey = privKey+ "_black";

        if(code.id() == outlineSnap) {
            setTimeout(function() {
                code.draggable(false);
            }, 50);
        }
    }
}

This function has to be in created the for(var key in codes) {} and outside the drag events. I then called the function inside the dragend event.
code.on('dragend', function() {
    snapTo(code, "pstart");
    snapTo(code, "pend");
}

There's a bit of an issue with adding the score, I have found a solution that just yet other than keeping the if statement to change draggable to false for the right object outline combination, as if this it taken out the user could 'farm' the drag feature for points...


Q: How do you sort the output of a python command? Python beginner here. Let's say that I have something at the end of my script that queries info from a system and dumps it into this format:
print my_list_of_food(blah)

and it outputs a list like:
('Apples', 4, 4792320)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Pumpkins', 1, 5074944)
('more stuff', 4545, 345345)

How do I then sort that output based on the 2nd field so that it would look like this:
('Pumpkins', 1, 5074944)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Apples', 4, 4792320)

Other than importing a bash command to cut -d "," -f 2 | head 4 I'd rather use python. I know I can use sorted or sort to sort an existing tuple or dictionary but I'm not sure of how to sort the output of a print. I've done some research and everything points to implementing sort into my script instead of sorting a print output but who knows, maybe someone has a solution. Thanks.
UPDATE:
Thanks everyone. I've tried to make all of the solutions work but I keep getting this error:
File "test.py", line 18, in <lambda>
    print sorted(my_list_of_food(blah), key=lambda x: x[1])
TypeError: 'int' object is unsubscriptable

File "test.py", line 18, in <lambda>
    print(sorted(my_list_of_food(blah), key=lambda k: k[1]))
TypeError: 'int' object is unsubscriptable

I tried to include this at the beginning of the script:
from __future__ import print_function

but no luck.

A: You can use the key argument to the sort. In your case,
print(sorted(list_of_food, key=lambda k:k[1]))

will do the trick. The key function should return an integer, usually.

A: You can't sort after outputting to stdout. Well, you shouldn't, since it's heavily complicating a simple task. Instead, you sort the value and print the result:
print sorted(my_list_of_food(blah), key=lambda x: x[1])

The part where you were having difficulties is sorting by the second field; that's why that key argument is there - to override the default ordering (which would be the first item of the tuple). To learn more about key functions, check this section on the python Sorting HOW TO
If you're still wondering, technically, you could sort the stdout output if you replaced sys.stdout with a wrapper object that buffered the output then sorted and printed it (to the real stdout) periodically, but it's pointless and hard to get right, IMHO.

A: If it prints out that way, than either my_list_of_food(blah) returns a string, or it returns a class instance that has a __repr__ method that returns that string... Your best bet is to get data in the actual list format before it becomes a string.
If it returns a class instance, get the list and sort on it using key... Otherwise you need to parse the text, so I'll address that part only:
# this is assuming the structure is consistent
# function to parse a line of the form "('{text}', {int}, {int})" into tuple members using regex
import re
re_line = re.compile(r"\('(?P<name>\w*)',\s?(?P<int1>\d+)\s?,\s?(?P<int2>\d+)\)")
def ParseLine(line):
    m = re_line.match(line)
    if m:
        return (m.group('name'), int(m.group('int1')), int(m.group('int2')))
    # otherwise return a tuple of None objects
    else:
        return (None, None, None)

# final sorted output (as tuples of (str, int, int) )
sorted(
    [ParseLine(line) for line in my_list_of_food(blah).splitlines()],
    key = lambda tup: tup[1]
)

A: OK: If you really have to do it that way: capture the output of the function in
a StringIO object and sort the lines read back from that object.
import sys
try:
    from StringIO import StringIO
except:
    from io import StringIO

a = [ ('Apples', 4, 4792320),
    ('Oranges', 2, 2777088),
    ('Pickles', 3, 4485120),
    ('Pumpkins', 1, 5074944),
    ('more stuff', 4545, 345345) ]

[Step 1]
out = StringIO()    # create a StringIO object
sys.stdout = out    # and redirect stdout to it
for item in a : print (item)        # print output
sys.stdout = sys.__stdout__     # redirect stdout back to normal stdout

out.seek(0)     # rewind StringIO object
s = out.readlines() # and read the lines.

[Step 2: define a key function to split the strings at comma,
and compare the 2nd field numerically. ]
def sortkey(a):
   return int(a.split(',')[1].strip())

[Step 3: sort and print]
s.sort(key=sortkey)
for line in s: print (line)


Q: git: recover local file overwritten by a checkout Consider a local file in a git repo called foo/bar.js. The file has been changed locally, and was accidentally overwritten by a previous commit:
$ git log foo/bar.js

commit 052b65bdf19ee4c977ce4d07e9d6fda60a793e0c
Author: Adam Matan (adam@example.com)
Date:   Sun May 21 16:47:22 2017 +0300

...

$ git checkout 052b65bdf19ee4c977ce4d07e9d6fda60a793e0c foo/bar.js

Local changes seem to be lost, as the local file is overwritten by the checkout, and has no track in the git repo. Am I missing a way to recover the file?


Q: fpdf error and view table error
 $sqlinsert="SELECT * FROM imagetable ";
    $result = mysqli_query($con, $sqlinsert);

    echo "
";
    echo "

              ID
              School Code
              Category
               School name
               School Address
               School name

";

    while($row = mysqli_fetch_assoc($result)){
        $id=  $row['ID'];
        echo "

                  ";
                  echo $row['ID'];
                  echo "";
                  echo $row['category'];
                  echo "";
                  echo $row['sname'];
                  echo "";
                  echo   $row['sadd'];
                  echo "";
                  echo   $row['filename'];

                  echo "";
                 ?>

           <form name="form" method="POST" action="parentssubmit.php">
         <input  type="hidden" value="<?php echo  $id;?>" name="search">
         <input type="submit"  value="View" name="View">
       </form>
    <?php   }

         echo "
";
    echo "
";
    ========================================================================
    if (isset($_POST['View']) ){
     $pdf=new fpdf();
    $pdf->ADDPage();
    $pdf->setfont('Arial','B', 16);
    $pdf->Cell(40,10, 'sname',1,0,'c');
    $pdf->Cell(40,10, 'sadd',1,0,'c');
    $pdf->Cell(40,10, 'category',1,0,'c');
    $pdf->Cell(40,10, 'scode',1,0,'c');

         $con = mysqli_connect("localhost","root","","school");
           if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

       $file_filename=$_FILES['file']['name'];

       $target_path  =  "Newfolder1";

     $image_path = $target_path . DIRECTORY_SEPARATOR . "filename";

        $image_format = strtolower(pathinfo('filename', PATHINFO_EXTENSION));
        $sql="SELECT * FROM imagetable WHERE ID= '$_POST[search]'";
        $result = mysqli_query($con, $sql);
          if(!mysqli_query($con, $sql)){
                    die( "Could not execute sql: $sql");
                     }

    // build the data array from the database records.
    While($row = mysqli_fetch_array($result)) {
           $pdf->Cell(40,10, $row['sname'],1,0,'c');
            $pdf->Cell(40,10, $row['sadd'],1,0,'c');
            $pdf->Cell(40,10, $row['category'],1,0,'c');

    $pdf->Image($image_path,50,100,50,20,$image_format);

           $pdf->ln();}
    }
    $pdf->output();

this is two pages and error is coming out Undefined index:
file Undefined index: file so please try to point out the mistake because main error is showing when i added the image field then the error is started popping out.

*

*I am trying to fetch the image from the database and trying to show it in PDF format.

A: First, you should close all your
 and  tags. Second, you're not sending any file with your form, and hence you're getting this Undefined index: file error, so remove these lines,
$file_filename=$_FILES['file']['name'];
$target_path  =  "Newfolder1";
$image_path = $target_path . DIRECTORY_SEPARATOR . "filename";
$image_format = strtolower(pathinfo('filename', PATHINFO_EXTENSION));

So after user hits view button, you should process your form and display image like this,
// your code

if (isset($_POST['View']) ){
    $pdf=new fpdf();
    $pdf->ADDPage();
    $pdf->setfont('Arial','B', 16);
    $pdf->Cell(40,10, 'sname',1,0,'c');
    $pdf->Cell(40,10, 'sadd',1,0,'c');
    $pdf->Cell(40,10, 'category',1,0,'c');
    $pdf->Cell(40,10, 'scode',1,0,'c');

    $con = mysqli_connect("localhost","root","","school");
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql="SELECT * FROM imagetable WHERE ID= '$_POST[search]'";
    $result = mysqli_query($con, $sql);
    if(!mysqli_query($con, $sql)){
        die( "Could not execute sql: $sql");
    }

    $row = mysqli_fetch_array($result);
    $image_path = $row['file'] . DIRECTORY_SEPARATOR . $row['filename'];  // path should be like this, process/upload/8/cdv_photo_001.jpg
    $image_format = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));
    $pdf->Cell(40,10, $row['sname'],1,0,'c');
    $pdf->Cell(40,10, $row['sadd'],1,0,'c');
    $pdf->Cell(40,10, $row['category'],1,0,'c');
    $pdf->Image($image_path,50,100,50,20,$image_format);
    $pdf->ln();
    $pdf->output();
}

// your code


Q: mediarecorder addEventListener is not working in Chrome/Safari I am using mediarecorder in a vue.js app. The code snippet is below. The inline function for ondataavailable executes. However, neither of the two options to specify a function handler for onstop get invoked.
Is there a workaround to this issue?
      const options = { mimeType: "audio/webm" };
      mediaRecorder = new MediaRecorder(stream, options);

      mediaRecorder.ondataavailable = function (e) {
        console.log("in dataAvailable", e.data.size);
        if (e.data.size > 0) recordedChunks.push(e.data);
      };

      mediaRecorder.onstop = this.stopRecordingEvent;
      mediaRecorder.addEventListener("stop", this.stopRecordingEvent);

Using an inline function for the stop event like dataavailable works, however that gives error in the highlighted line:
      mediaRecorder.onstop = function () {
        console.log("recording stopped event");

        // save the recording bytes in an array

        const blob = new Blob(recordedChunks);
        const audioURL = URL.createObjectURL(blob);
        var recording = {
          blob: blob,
          url: audioURL,
          id: arrRecordings.length + 1,
        };
        console.log(recording.id, recording.url);

        //this line gives an error
        this.recordings.push(recording);
        console.log(arrRecordings);

        recordedChunks.length = 0;
      };

A: event ondataavailable works after mediaRecorder stop() function


Q: Item-by-item list comparison, updating each item with its result (no third list) The solutions I have found so far in my research on comparing lists of objects have usually generated a new list of objects, say of those items existing in one list, but not in the other.  In my case, I want to compare two lists to discover the items whose key exists in one list and not the other (comparing both ways), and for those keys found in both lists, checking whether the value is the same or different.
The object being compared has multiple properites that constitute the key, plus a property that constitutes the value, and finally, an enum property that describes the result of the comparison, e.g., {Equal, NotEqual, NoMatch, NotYetCompared}.  So my object might look like:
class MyObject
{
   //Key combination
   string columnA;
   string columnB;
   decimal columnC;

   //The Value
   decimal columnD;

   //Enum for comparison, used for styling the item (value hidden from UI)
   //Alternatively...this could be a string type, holding the enum.ToString()
   MyComparisonEnum result;
}

These objects are collected into two ObservableCollection<MyObject> to be compared.  When bound to the UI, the grid rows are being styled based on the caomparison result enum, so the user can easily see what keys are in the new dataset but not in the old, vice-versa, along with those keys in both datasets with a different value.  Both lists are presented in the UI in data grids, with the rows styled based on the comparison result.
Would LINQ be suitable as a tool to solve this efficiently, or should I use loops to scan the lists and break out when the key is found, etc (a solution like this comes naturally to be from my procedural programming background)... or some other method?
Thank you!

A: You can use Except and Intersect:
var list1 = new List<MyObject>();
var list2 = new List<MyObject>();
// initialization code
var notIn2 = list1.Except(list2);
var notIn1 = list2.Except(list1);
var both = list1.Intersect(list2);

To find objects with different values (ColumnD) you can use this (quite efficient) Linq query:
var diffValue = from o1 in list1
                join o2 in list2
                on new { o1.columnA, o1.columnB, o1.columnC } equals new { o2.columnA, o2.columnB, o2.columnC }
                where o1.columnD != o2.columnD
                select new { Object1 = o1, Object2 = o2 };

foreach (var diff in diffValue)
{
    MyObject obj1 = diff.Object1;
    MyObject obj2 = diff.Object2;
    Console.WriteLine("Obj1-Value:{0} Obj2-Value:{1}", obj1.columnD, obj2.columnD);
}

when you override Equals and GetHashCode appropriately:
class MyObject
{
    //Key combination
    string columnA;
    string columnB;
    decimal columnC;

    //The Value
    decimal columnD;

    //Enum for comparison, used for styling the item (value hidden from UI)
    //Alternatively...this could be a string type, holding the enum.ToString()
    MyComparisonEnum result;

    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is MyObject)) return false;
        MyObject other = (MyObject)obj;
        return columnA.Equals(other.columnA) && columnB.Equals(other.columnB) && columnC.Equals(other.columnC);
    }

    public override int GetHashCode()
    {
        int hash = 19;
        hash = hash + (columnA ?? "").GetHashCode();
        hash = hash + (columnB ?? "").GetHashCode();
        hash = hash + columnC.GetHashCode();
        return hash;
    }
}


Q: header menu with a logo left is not being displayed I am new with HTML & CSS, and I Am having a weird issue where the logo path is properly rendered into the page, but however doesn't display on the site. how does it happen this? e.g. the logo is a SVG format where I don't see it's an issue, but I am not sure why it behaves like this
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css'>
<link rel="stylesheet" href="./style.css">

Home

home

home

demo1

css
header {
  padding: 5% 5% 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-logo {
  margin-left: 0;
}

.header-menu ul {
  display: flex;
}

.header-menu li {
  margin-right: 40px;
  color: hsl(243, 87%, 12%);
  font-family: "Raleway", sans-serif;
  list-style: none;
  cursor: pointer;
  font-size: 16px;
}

.header-menu li:after {
  background: none repeat scroll 0 0 transparent;
  bottom: 0;
  content: "";
  display: block;
  height: 2px;
  left: 50%;
  background: hsl(260, 100%, 75%);
  transition: width 0.3s ease 0s, left 0.3s ease 0s;
  width: 0;
}

.header-menu li:hover:after {
  width: 100%;
  left: 0;
}

a{
  text-decoration: none;
}

A: Give your logo a width and height.

A: Just add this code to your CSS:
    .header-logo {
  width: 2rem;
}

If you face any problem then let me know.


Q: How Can an app take a screenshot while running in the background and save it on a server is it possible to make my App take a screenshot by code .. and then save it on server
  (I'm using parse as a backend Server)


Q: Run java classfile from terminal I have a compiled java file somefile.class, and when i cd into the right folder and do: java somefile it works but when i call it from another folder: java folder/somefile it doesn't work, it gives me java exceptions, could you help me out?
Edit: I am working on a Mac if that matters..

A: If you run java folder/somefile java tries to find a class somefile in the package folder, but your class isn't located in the package folder, it's just located in the path folder. You can adjust the search path for classes using the -cp option (meaning classpath).
For example having a class YourClass in the package your.package, this package is located in /your/path you can execute it from any location with:
java -cp /your/path your.package.YourClass

In your specific case you should run:
java -cp folder somefile

I hope it's clear enough ;-)


Q: How can I find the source file that causes the print_r display in PHP I'm wondering how would someone debug to find the source file (and perhaps line number in the code) that causes the print_r? Or is there a package that could be use for this kind of debugging during page load? Similar idea like console.log in the dev tool.

A: Probably the debug_print_backtrace() from PHP can help you.
These way you can see all the functions that have been called.
More details: http://php.net/manual/en/function.debug-print-backtrace.php


Q: Android resumes my Activity even if i call FINISH on BackButton I have an activity A that launches B with an Intent. (B is a MapActivity and has some async code)
in B i have the following code
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
 if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//          Log.d(this.getClass().getName(), "back button pressed");

     finish();
     return true;
    }

    return super.onKeyDown(keyCode, event);
}

This simply not work. I mean that when I press the back button on the phone, the current activity B disappears and the activity A that launched B is shown.
If I press again on A the button that launch B, I see B is exactly how it was when I closed it. SAME text in textboxes, same Map position... So i think the activity B is not really closed.
How can I close it for real so when I launch again it, activity B is cleas as new born?
EDIT: just to make the question clearer:
I want it to work like this: when the user is on activity B and BACK button is pressed, B has to be closed and destroyed. When the user again launches B from A, B has to be launched as a NEW activity, with blank field, reset map, etc., etc., ... just like the first time the user launches B from A.

A: Instead of returning true, try returning super.onKeyDown(keyCode, event) after finish().
You can try 1 more thing: specify android:noHistory="true" in the manifest for that activity.
Specifying this attribute doesn't keep the activity on the Activity Stack.
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist

A: Have you tried lauching B by calling startActivityForResult() in A?
Do all your processing in B and then ensure you call finish on it and this should clear all data in it.
Please let me know if it works.

A: It's obvious. OnSaveState is called when finishing activity, and this activity is popped out of the stack. Best practice for you to clear the situation is to log all the lifecycle events in both activities, it will help to figure out where to put initializing your B activity.
Yes, and one more thing try researching onNewIntent method in B activity i suppose it will be really helpfull

A: As i stated in my last comment to the post, @Jianhong given me the correct answer (aslso if as a comment). As he don't copied the comment as answer in time, i add this answer and mark it as the ACCEPTED. Thanks @Jianhong!
Answer:
@Jianhong OMG! you completely right! i checked for this problem in past days but i couldn't find it as... i've not UPDATED from SVN. my coworker inserted lines of code that prefill fields by some static var!


Q: Condition within JOIN or WHERE Is there any difference (performance, best-practice, etc...) between putting a condition in the JOIN clause vs. the WHERE clause?
For example...
-- Condition in JOIN
SELECT *
FROM dbo.Customers AS CUS
INNER JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND CUS.FirstName = 'John'

-- Condition in WHERE
SELECT *
FROM dbo.Customers AS CUS
INNER JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE CUS.FirstName = 'John'

Which do you prefer (and perhaps why)?

A: Most RDBMS products will optimize both queries identically.  In "SQL Performance Tuning" by Peter Gulutzan and Trudy Pelzer, they tested multiple brands of RDBMS and found no performance difference.
I prefer to keep join conditions separate from query restriction conditions.
If you're using OUTER JOIN sometimes it's necessary to put conditions in the join clause.

A: I prefer the JOIN to join full tables/Views and then use the WHERE To introduce the predicate of the resulting set.
It feels syntactically cleaner.

A: I typically see performance increases when filtering on the join.  Especially if you can join on indexed columns for both tables.  You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.

A: Agree with 2nd most vote answer that it will make big difference when using LEFT JOIN or RIGHT JOIN. Actually, the two statements below are equivalent. So you can see that AND clause is doing a filter before JOIN while the WHERE clause is doing a filter after JOIN.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'

SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN (SELECT * FROM dbo.Orders WHERE OrderDate >'20090515') AS ORD
ON CUS.CustomerID = ORD.CustomerID

A: The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.
I recommend you write the queries in the most readable way possible.
Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.
For example, instead of:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1

Write:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

A: For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).
However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'

SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'

The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.
The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)
The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null

A: WHERE will filter after the JOIN has occurred.
Filter on the JOIN to prevent rows from being added during the JOIN process.

A: Joins are quicker in my opinion when you have a larger table. It really isn't that much of a difference though especially if you are dealing with a rather smaller table. When I first learned about joins, i was told that conditions in joins are just like where clause conditions and that i could use them interchangeably if the where clause was specific about which table to do the condition on.

A: It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters.

A: Putting the condition in the join seems "semantically wrong" to me, as that's not what JOINs are "for". But that's very qualitative.
Additional problem: if you decide to switch from an inner join to, say, a right join, having the condition be inside the JOIN could lead to unexpected results.


Q: how resource integrity is maintained using Semaphores I am new to computer science and it may sound stupid to some of you. Although i have searched for related question, but this scenario stuck in my mind.
I understand that Mutexes provide lock facility for a section or resource. Consider the example of a buffer(an array of size 10 say) where a thread puts some value in it. We lock the mutex before using it releases after. This whole process is done by same thread.
Now if i have to do this same process with semaphores. I can limit the number of threads that can enter the critical section in this case. But how can the integrity of the buffer is maintained.
(read and write operations handled by different threads on buffer)

A: The usual solution with semaphores is to allow multiple simultaneous readers or one writer. See the Wikipedia article Readers-writers problem for examples.

A: Semaphores are an higher abstraction. Semaphores controls the ability to create processes and make sure the instance created is distinct in which case it is kicked out. In a nutshell.


Q: Spring AsyncTaskExecutor Returns Futures That Don't Throw Exceptions If I submit a Callable task to Spring's ThreadPoolTaskScheduler (the default implementation of AsyncTaskExecutor), I receive a Future representing the result of the computation. I know that my callable will throw an exception, but when I call Future#get, the method returns null instead of throwing an exception. I have found this to be the case when I invoke AsyncTaskExecutor#submit directly, and when it is used implicitly through Spring's @Async annotation.
In the source for ThreadPoolTaskScheduler, I see there's an ErrorHandler instance variable that seems to control how the futures throw exceptions. I tried wiring in a custom ErrorHandler that would rethrow any exception it received as a RuntimeException, but for some reason that didn't work. When I sent a request to my running application's endpoint, it timed out. My app printed no logs; not even the ones Spring normally prints before the request hits my REST controller. Note that I wired my ErrorHandler directly into the ThreadPoolTaskScheduler bean. I didn't define the ErrorHandler itself as a bean.
public class DataRetriever {
    @Autowired
    private AsyncTaskExecutor taskExecutor;

    public List<Data> getData(String id) throws Exception {
      Future<List<Data>> futureData = getDataEventually(id);
      return futureData.get(); // exception should be thrown here
    }

    private Future<List<Data>> getDataEventually(
        return taskExecutor.submit(() -> throw new RuntimeException());
    }
}


Q: Guarantee the lock is exclusive on the table for read also I am writing a web application and came across the problem to keep a value in column that is identical in two rows only and both goes in single batch of execution. One way I came up with solution to read the MAX value in the column and increment by 1. Thus, I end-up writing the procedure to lock the table so that other user should not get the dirty read of MAX value.
Create table D(Id int , Name varchar(100))

Begin Tran
    DECLARE @i int = (SELECT MAX(ID) FROM D with (tablockx, holdlock))
    Print @i ;

    Insert into D values ((@i + 1), 'ANAS')

    SELECT * FROM D

    --COMMIT
Rollback

This code lock the table until query commits or rollback. I have two question from this 1) Is this code guarantee to have exclusive lock on table? 2) In my quick read tablockx can help perform lock for read also whereas holdlock help to prevent the changes in row I am working in locked session, but is this rightly used because I think holdlock may actually not required

A: Not sure you are asking the right question.  You need the current value not to be changed and no insert. With SERIALIZABLE you may not need (updlock).
I am not positive about this answer.  You should do your own testing.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
Begin Tran
    DECLARE @i int = (SELECT MAX(ID) FROM D with (updlock))
    Print @i ;

    Insert into D values ((@i + 1), 'ANAS')

    SELECT * FROM D

    --COMMIT
Rollback

identity or sequence number are better approaches


Q: Continuous maps vs open maps in topological homeomorphisms My lecturer writes in my topology notes that :
A map $f:(X,\tau)\rightarrow (Y,\tau')$ is a homeomorphism if it is a bijection and both $f,f^{-1}$ are continuous.
However he then goes on to write that :
If $f$ is homeomorphism then $f$ and it's inverse $f^{-1}$ map open sets to  open sets and we call them open maps and that we should note that open maps are not necessarily continuous.
He gives the example :
Let $X=\{a,b\}$, consider $id_x:(X,\text{trivial topology})\rightarrow(X,\text{discrete topology})$
This is a bijection.
It's inverse is continuous
But the map itself is not continuous
$id_x(\{a\})=\{a\}$ is not open in the trivial topology.
I'm having trouble seeing how this is consistent with the definition though, could anyone please help me understand ?

A: Every set is open in discrete topology, so $\{a\}$ is open in $X$ with discrete topology. The inverse image of this set under the identity map is  $\{a\}$ is itself. But the only open sets in trivial topology are the empty set and $X$. Hence (assuming $X$ is not  a singleton)  the inverse image is not open so the identity map is not continuous.
Continuity of the inverse map follows from the fact that every set is open in discrete topology.


Q: Add two factor authentication to my web application I have a java spring web application and currently it has a normal authentication flow. I need to add a two factor authentication implementation to it. For that can we use 3rd party provider like google or any other provider.

A:
I need to add a two factor authentication implementation to [my java spring web application].

Here's a good package that I wrote which implements 2FA/two-factor authentication in Java code.
Copying from the READ_ME, to get this to work you:

*

*Properly seed the random number generator.

*Use generateBase32Secret() to generate a secret key for a user.

*Store the secret key in the database associated with the user account.

*Display the QR image URL returned by qrImageUrl(...) to the user.

*User uses the image to load the secret key into his authenticator application.

Whenever the user logs in:

*

*The user enters the number from the authenticator application into the login form.

*Read the secret associated with the user account from the database.

*The server compares the user input with the output from generateCurrentNumber(...).

*If they are equal then the user is allowed to log in.


Q: Condition is not verifying the validity of the input I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {

    int minPassingAvg;

    public MonitoredStudent(){
        super();
        minPassingAvg = 0;
    }

    public MonitoredStudent(String name, int minPassingAvg) {
        super(name);
        this.minPassingAvg = minPassingAvg;
    }

    public int getMinPassingAvg() {
        return minPassingAvg;
    }

    public void setMinPassingAvg(int minPassingAvg) {
        this.minPassingAvg = minPassingAvg;
    }

    boolean isOffProbation() {
        if(getAverageScore() >= minPassingAvg)
            return true;
        return false;
    }
}

This is the Student super class:
public class Student{

   private String name;

   private double totalScore;

   private int quizCount;

   public Student(){
      name = "";
      totalScore = 0;
      quizCount = 0;
   }

   public Student(String n){
      name = n;
      totalScore = 0;
      quizCount = 0;
   }

   public void setName(String aName){
      name = aName;
   }

   public String getName(){
      return name;
   }

   public void addQuiz(int score){
      if(score >= 0 && score <= 100){
         totalScore = totalScore + score;
         quizCount = quizCount + 1;
      }else{
         System.out.println("Score must be between 0 and 100, inclusive");
      }
   }

   public double getTotalScore(){
      return totalScore;
   }

   public double getAverageScore(){
      return totalScore / quizCount;
   }
}

This is the main method:
import java.util.Scanner;

public class MonitoredStudentTester{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        MonitoredStudent monStu = new MonitoredStudent();
        String repeat = "n";
        int currentScore = 0;
        int minPassAv;

        System.out.println("Enter the student's name:");
        String stuName = scan.next();
        Student sName = new Student(stuName);
        System.out.println("What is the minimum passing average score: ");
        minPassAv = scan.nextInt();

        Student stu = new Student();
        do {
            System.out.println("Enter a quiz score: ");
            currentScore = scan.nextInt();

            stu.addQuiz(currentScore);
            monStu.setMinPassingAvg(currentScore);

            System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
            scan.nextLine();
            repeat = scan.nextLine();

        }while(repeat.equalsIgnoreCase("y"));

        String studName = stu.getName();
        double totalScore = stu.getTotalScore();
        double avgScore = stu.getAverageScore();
        boolean offProb = monStu.isOffProbation();

        System.out.println(studName + "'s Total Score is: " + totalScore);
        System.out.println(studName + "'s Average Score is: " + avgScore);
        System.out.println("Is " + studName + "off academic probation?: " + offProb);

    }
}

A: You main class should be something like this.
public class MonitoredStudentTester {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    MonitoredStudent monStu = new MonitoredStudent();
    String repeat = "n";
    int currentScore = 0;
    int minPassAv;

    System.out.println("Enter the student's name:");
    monStu.setName(scan.next());
    System.out.println("What is the minimum passing average score: ");
    minPassAv = scan.nextInt();

    do {
      System.out.println("Enter a quiz score: ");
      currentScore = scan.nextInt();

      monStu.addQuiz(currentScore);
      monStu.setMinPassingAvg(minPassAv);

      System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
      scan.nextLine();
      repeat = scan.nextLine();

    } while (repeat.equalsIgnoreCase("y"));

    String studName = monStu.getName();
    double totalScore = monStu.getTotalScore();
    double avgScore = monStu.getAverageScore();
    boolean offProb = monStu.isOffProbation();

    System.out.println(studName + "'s Total Score is: " + totalScore);
    System.out.println(studName + "'s Average Score is: " + avgScore);
    System.out.println("Is " + studName + "off academic probation?: " + offProb);
  }
}

When using inheritance you just need to create an object of child class.


Q: How to convert excel rate() formula into step by step formula I want to convert this excel rate() formula =RATE(D5,-D8,D3,,D6)*12 into manual formula for me to get the Effective Rate.

How can I convert this rate() =RATE(D5,-D8,D3,,D6)*12 formula from excel into a step by step formula?
The Effective Rate formula that I found online has not been able to reproduce the same results from the excel file.
You can download the excel file from Google Drive
Appreciate if anyone  can help.

A: There is not a closed-form formula for the effective interest of an amortized loan payment. The RATE formula in Excel uses an iterative approach to "solve" for the rate by guessing and adjusting the rate until the present value of the payments matches the passed-in PV.


Q: Unable to add SSL support for database I am using Spring3, Hibernate4 and postgres9.2.
For enabling the SSL database connection, I followed following steps :

*

*Creating self signed Certificate : refer : http://www.postgresql.org/docs/9.2/static/ssl-tcp.html#SSL-CERTIFICATE-CREATION

*Copied the generated server.crt and server.key into postgres/9.2/data folder.

*URL for hibernate connection : jdbc:postgresql://localhost:5432/DB_NAME?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
After restarting the postgres I run my application and it gives error as :
org.postgresql.util.PSQLException: The server does not support SSL.
    at org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:307)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:105)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
    at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:140)
    at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
    at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
    at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
    at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:23)
    at org.postgresql.Driver.makeConnection(Driver.java:393)
    at org.postgresql.Driver.connect(Driver.java:267)

Even I tried to add this line at the end of pg_hba.conf file but postgres does not get restarted :
hostssl     all     all         127.0.0.1/32        trust

EDIT
It is for other folks who received such error or wants to add database ssl connection :
I added ssl = true and removed comments for ssl related entries from postgresql.conf and it worked. :)

A: The root of your problem appears to be that your server does not support SSL or does not have it enabled. The message:
The server does not support SSL

may only be emitted by org/postgresql/core/v3/ConnectionFactoryImpl.java in enableSSL(...) when the server refuses or doesn't understand SSL requests.
Sure enough, in your update you say that you had the SSL-related options in postgresql.conf commented out. Them being commented out is the same as them being not there at all to the server; it will ignore them. This will cause the server to say it doesn't support SSL and refuse SSL connections because it doesn't know what server certificate to send. PgJDBC will report the error above when this happens.
When you un-commented the SSL options in postgresql.conf and re-started the server it started working.
You were probably confused by the fact that:
&ssl
&ssl=true
&ssl=false

all do the same thing: they enable SSL. Yes, that's kind of crazy. It's like that for historical reasons that we're stuck with, but it's clearly documented in the JDBC driver parameter reference:

ssl
Connect using SSL. The driver must have been compiled with SSL
  support. This property does not need a value associated with it. The
  mere presence of it specifies a SSL connection. However, for
  compatibility with future versions, the value "true" is preferred. For
  more information see Chapter 4, Using SSL.

As you can see, you should still write ssl=true since this may change in future.
Reading the server configuration and client configuration sections of the manual will help you with setting up the certificates and installing the certificate in your local certificate list so you don't have to disable certificate trust checking.
For anyone else with this problem: There will be more details in your PostgreSQL error logs, but my guess is your PostgreSQL config isn't right or you're using a hand-compiled PostgreSQL and you didn't compile it with SSL support.

A: If you are using a self-signed certificate you need to add it to your trusted key store of your Java installation on the client side.
You find the detailed instructions to achieve this here: telling java to accept self-signed ssl certificate

A: In your connection string, try
?sslmode=require

instead of
?ssl=true

A: Use param sslmode=disable. Work for me. Postgresql 9.5 with jdbc driver SlickPostgresDriver.


Q: Google Analytics not showing any data After building a basic ionic 3 app with two pages (quotes-list and quotes-detail) where clicking a name on the former you edit a text on the latter, run the app on a real device and go through GA, trying to get some statistics about the two tracked pages, but all I can see is nothing. Anyone could help me, please? I'm not able to get data, neither past nor real time. I'd appreciate it so much...
app.module.ts

import { GoogleAnalytics } from '@ionic-native/google-analytics';

  providers: [
    GoogleAnalytics,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})

app.component.ts

import { GoogleAnalytics } from '@ionic-native/google-analytics';

export class MyApp {
  rootPage:any = QuotesListPage;

  constructor(platform: Platform, googleanalytics: GoogleAnalytics) {
    platform.ready().then(() => {
      googleanalytics.debugMode();
      googleanalytics.startTrackerWithId("UA-XXXXXXXXX-1");
      googleanalytics.enableUncaughtExceptionReporting(true).then((_success) => {
        console.log("Successful enabling of uncaught exception reporting "+_success)}).catch((_error) => {
          console.log("error occured "+_error)
      });
    });
  }

}

quotes-list.ts

  import { GoogleAnalytics } from '@ionic-native/google-analytics';

  constructor(platform: Platform, private http:Http, public navCtrl: NavController, public navParams: NavParams, public googleanalytics: GoogleAnalytics) {
    this.isfiltered = false;
    this.http.get('quotes.json')
    .map(res => res.json())
    .subscribe(
      data => {
        this.quotesList = data.quotes;
      },
      err => console.log("error is "+err), // error
      () => console.log('read quotes Complete '+ this.quotesList) // complete
    );
    platform.ready().then(() => {
      googleanalytics.trackView("Quotes List");
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad QuotesListPage');
  }

}

quotes-detail.ts

  import { GoogleAnalytics } from '@ionic-native/google-analytics';

  constructor(public navCtrl: NavController, public navParams: NavParams, public googleanalytics: GoogleAnalytics) {
   this.quoteDetail = navParams.get('quote');
   googleanalytics.trackView("Quotes Detail");
  }

}

A: 2 changes needed in app.components.ts

*

*Ensure googleanalytics.startTrackerWithId("UA-XXXXXXXXX-1"); is always the first line to be executed before any other analytics code.

*Remove googleanalytics.debugMode();


Q: Shopware 6: How to display product name in breadcrumbs We want to add the product name to the breadcrumb list when current page matches a product detail page.
Unfortunately, it doesn't seem like the product is loaded yet when the breadcrumb is rendered. We have tried using dump() to see what variables are available and nothing related to the product.
Where should I look in order to include the product name in our breadcrumbs?

A: Have a look at storefront/base.html.twig. There you will see, that currently the breadcrumb-template gets passed the context and the category. If you want to also use some product-information, you have to overwrite this block like this:
{% block base_breadcrumb %}
    {% sw_include '@Storefront/storefront/layout/breadcrumb.html.twig' with {
      context: context,
      category: page.product.seoCategory,
      product: page.product
    } only %}
{% endblock %}

Then you can use product in the breadcrumb-template.


Q: Playing a MIDI file using SoundFonts and NAudio I am trying to create a simple program that plays some notes using a preset from inside a Soundfont. To do this I am trying to use NAudio. So far I have been able to successfully open a SoundFont, and get the names of all the instruments, presets, etc.:
NAudio.SoundFont.SoundFont sf = new NAudio.SoundFont.SoundFont("SoundFont.sf2");
MessageBox.Show(sf.Presets[0].Name); //Just looking at the first name

Now I want to be able to play sounds using those soundfonts, in the end from midi, but for now, just a note. I have played around with a few things, but not come up with anything so far.

A: NAudio can read information out of SoundFont files, but it does not include a SoundFont engine. For that you would need a good pitch shifting algorithm, some filters, and some voice management, as well as a sequencer if you wanted to play back MIDI files.
The closest I have come to building something like this is a demo I made for my NAudio Pluralsight course, in which I build a simple sampled piano based on some piano note recordings. If you are subscriber, you are free to use it. The technique I use is to load the sample into memory, connect a RawSourceWaveStream to it, convert it into a sample provider, and then pass it through a pitch shifter sample provider, based on the one I ported to C# for this open source project.


Q: Image.createImage problem in J2ME I tried this on J2ME
try {
    Image immutableThumb = Image.createImage( temp, 0, temp.length);
} catch (Exception ex) {
    System.out.println(ex);
}

I hit this error:
java.lang.IllegalArgumentException:
How do I solve this?

A: Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).
http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)
(This URL refuses to become a hyperlink for some reason (?))

A: It's hard to say without more details or more surrounding code, but my initial suspicion is that the file your are trying to load is in a format not supported by the device.

A: Let us have a look at the docs: IllegalArgumentException is thrown

if imageData is incorrectly formatted or otherwise cannot be decoded

So the possible reason can be either unsupported format of the image, or truncated data. Remember, you should pass entire file to that method, including all the headers. If you have doubts about the format, you'd better choose PNG, it must be supported anyway.

A: I just had the same problem with my MIDLET and the problem in my case was the HTTP header that comes along the JPEG image that I read from the socket's InputStream. And I solved it by finding the JPEG SOI marker that is identified by two bytes: FFD8 in my byte array. Then when I find the location of the FFD8 in my byte array, I trim the starting bytes that represent the HTTP header, and then I could call createImage() without any Exception being thrown...
You should check if this is the case with you. Just check is this true (temp[0] == 0xFF && temp[1] == 0xD8) and if it is not, trim the start of temp so you remove HTTP header or some other junk...
P.S.
I presume that you are reading JPEG image, if not, look for the appropriate header in the temp array.
Also if this doesn't help, and you are reading JPEG image make sure that the array starts with FFD8 and ends with FFD9 (which is the EOI marker). And if it doesn't end with the EOI just trim the end like I explained for SOI...
P.P.S
And if you find that the data in temp is valid, then your platform cannot decode the JPEG images or the image in temp is to large for JPEG decoder.


Q: retrieve most recent records I'm having a bit of mysql query brain freeze. I need to retrieve the latest record from a table, grouped by a second column. Something like this:
SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
  ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
GROUP BY cid
ORDER BY activity_date DESC

...except that I need the most recent record (using activity_date) within the group by (the order by is performed after the group). I tried using HAVING activity_date = max(activity_date) but that doesn't work.

A: I think you can do it like this:
SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
  ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
    and ca.id = (SELECT id from activity a
            join activity_target t on a.id = t.activity_id
        WHERE t.contact_id = cat.contact_id
        ORDER BY activity_date DESC LIMIT 1)
ORDER BY activity_date DESC

I can't say for sure without looking at your schema, and I'm guessing a bit with the differences between MySQL and Microsoft SQL Server.

A: SELECT ca.id, ca.activity_date, cat.contact_id AS cid
FROM activity ca
  JOIN activity_target cat
    ON ca.id = cat.activity_id
  JOIN
      ( SELECT t.contact_id
             , MAX(a.activity_date) AS activity_date
        FROM activity a
          JOIN activity_target t
            ON a.id = t.activity_id
        WHERE a.activity_type_id = 44
        GROUP BY t.contact_id
      ) AS grp
    ON  grp.contact_id = cat.contact_id
    AND grp.activity_date = ca.activity_date
WHERE ca.activity_type_id = 44
ORDER BY ca.activity_date DESC


Q: Try to export form result into single field I'm trying to fill one hidden field with the results obtained from an HTML form. I have seen someone who suggests using Javascript and jQuery. I've tried to write some scripts using that language. This is the HTML form hosted in Formtools platform (www.formtools.org):
I tried many times and I'm going crazy, cause everything I've tried didn't work. Could someone help me?
Thanks

<$(document).ready(function() {

  $("#formdatimarketing.php").continue(function() {
    var tipologia_auto = $("tipologia_auto[]").val();
    var alimentazione = $("alimentazione[]").val();
    var km_annui = $("km_annui").val();
    var mod_acq = $("mod_acq").val();
    var budget = $("budget_spesa").val();
    var rata = $("rata_mensile").val();
    var abitudini_acq = $("abitudini_acq").val();
    var componenti_famiglia = $("n_comp_famiglia").val();
    var hobby = $("hobby[]").val();
    var professione = $("professione").val();
    var asscociazione_categoria = $("ass_cat").val();
    var privacy = $("privacy_mkt_all").val;
    var giorno_pref_ricontatto = $("giorno_ricontatto[]").val();
    var orario_ricontatto = $("orario_ricontatto[]").val();
    var mkt = "";
    mkt = tipologia_auto + "," + alimentazione + "," + km_annui + "," + mod_acq + "," + budget + "," + rata + "," + abitudini_acq + "," + componenti_famiglia + "," + hobby + "," + professione + "," + asscociazione_categoria + "," + privacy + "," + giorno_pref_ricontatto + "," + orario_ricontatto;
    output = mkt;

    alert(output);
  });
});

<form action="formdatimarketing.php" method="post" enctype="multipart/form-data" id="ts_form_element_id" name="edit_submission_form">
  <input type="hidden" id="form_tools_published_form_id" value="12">

Dati Marketing

          Segmento auto richiesto
          *

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_1" value="tipologia_auto_1">
            Citycar

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_2" value="tipologia_auto_2">
            Berlina

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_3" value="tipologia_auto_3">
            Monovolume

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_4" value="tipologia_auto_4">
            Veicolo commerciale

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_5" value="tipologia_auto_5">
            Suv

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_6" value="tipologia_auto_6">
            Cabrio

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_7" value="tipologia_auto_7">
            Coupe

            <input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_8" value="tipologia_auto_9">
            Station Wagon

          Alimentazione
          *

            <input type="checkbox" name="alimentazione[]" id="alimentazione_1" value="alimentazione_1">
            Benzina

            <input type="checkbox" name="alimentazione[]" id="alimentazione_2" value="alimentazione_2">
            Diesel

            <input type="checkbox" name="alimentazione[]" id="alimentazione_3" value="alimentazione_3">
            Metano

            <input type="checkbox" name="alimentazione[]" id="alimentazione_4" value="alimentazione_4">
            GPL

            <input type="checkbox" name="alimentazione[]" id="alimentazione_5" value="alimentazione_5">
            Ibrido

            <input type="checkbox" name="alimentazione[]" id="alimentazione_6" value="alimentazione_6">
            Elettrico

          Km annui percorsi
          *

            <input type="radio" name="km_annui" id="km_annui_1" value="km_annui_1">
            0-10.000 km
            <input type="radio" name="km_annui" id="km_annui_2" value="km_annui_2">
            10.000 - 25.000 km
            <input type="radio" name="km_annui" id="km_annui_3" value="km_annui_4">
            Più di 25.000 km

          Modalità di acquisto
          *

            <input type="radio" name="mod_acq" id="mod_acq_1" value="mod_acq_1">
            Contanti
            <input type="radio" name="mod_acq" id="mod_acq_2" value="mod_acq_2">
            Finanziamento - Leasing
            <input type="radio" name="mod_acq" id="mod_acq_3" value="mod_acq_4">
            Noleggio

          Budget di spesa
          *

 <input type="radio" name="budget_spesa" id="budget_spesa_1" value="budget_spesa_1">
                Budget: 0 - 5.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_2" value="budget_spesa_2">
                Budget: 5.000 - 12.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_3" value="budget_spesa_3">
                Budget: 12.000 - 18.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_4" value="budget_spesa_4">
                Budget: 18.000 - 24.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_5" value="budget_spesa_5">
                Budget: 24.000 - 32.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_6" value="budget_spesa_6">
                Budget: 32.000 - 40.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_7" value="budget_spesa_7">
                Budget: 40.000 - 50.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_8" value="budget_spesa_8">
                Budget: 50.000 - 60.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_9" value="budget_spesa_9">
                Budget: 60.000 - 70.000 €

 <input type="radio" name="budget_spesa" id="budget_spesa_10" value="budget_spesa_10">
                Budget: 70.000 € o più

          Rata mensile
          *

 <input type="radio" name="rata_mensile" id="rata_mensile_1" value="rata_mensile_1">
                Rata = 150-200

 <input type="radio" name="rata_mensile" id="rata_mensile_2" value="rata_mensile_2">
                Rata = 200-300

 <input type="radio" name="rata_mensile" id="rata_mensile_3" value="rata_mensile_3">
                Rata = 300-400

 <input type="radio" name="rata_mensile" id="rata_mensile_4" value="rata_mensile_4">
                Rata = 400-500

 <input type="radio" name="rata_mensile" id="rata_mensile_5" value="rata_mensile_5">
                Rata = 500-750

 <input type="radio" name="rata_mensile" id="rata_mensile_6" value="rata_mensile_6">
                Rata = 750 o piu

          Abitudini di acquisto
          *

            <input type="radio" name="abitudini_acq" id="abitudini_acq_1" value="abitudini_acq_1">
            Primo acquisto

            <input type="radio" name="abitudini_acq" id="abitudini_acq_2" value="abitudini_acq_2">
            1 - 3 anni

            <input type="radio" name="abitudini_acq" id="abitudini_acq_3" value="abitudini_acq_3">
            3 - 6 anni

            <input type="radio" name="abitudini_acq" id="abitudini_acq_4" value="abitudini_acq_4">
            6 - 10 anni

            <input type="radio" name="abitudini_acq" id="abitudini_acq_5" value="abitudini_acq_5">
            più di 10 anni

          Numero di componenti del nucleo familiare

            <input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_1" value="n_comp_famiglia_1">
            Single

            <input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_2" value="n_comp_famiglia_2">
            Senza figli

            <input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_3" value="n_comp_famiglia_3">
            1 figlio

            <input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_4" value="n_comp_famiglia_4">
            2 o più figli

          Hobby

 <input type="checkbox" name="hobby[]" id="hobby_1" value="hobby_1">
                Golf

 <input type="checkbox" name="hobby[]" id="hobby_2" value="hobby_2">
                Vela

 <input type="checkbox" name="hobby[]" id="hobby_3" value="hobby_3">
                Tennis

 <input type="checkbox" name="hobby[]" id="hobby_4" value="hobby_4">
                Cucina

 <input type="checkbox" name="hobby[]" id="hobby_5" value="hobby_5">
                Cinema

 <input type="checkbox" name="hobby[]" id="hobby_6" value="hobby_6">
                Musica

 <input type="checkbox" name="hobby[]" id="hobby_7" value="hobby_7">
                Fitness

 <input type="checkbox" name="hobby[]" id="hobby_8" value="hobby_8">
                Basket

 <input type="checkbox" name="hobby[]" id="hobby_9" value="hobby_9">
                Calcio

 <input type="checkbox" name="hobby[]" id="hobby_10" value="hobby_10">
                Motori

 <input type="checkbox" name="hobby[]" id="hobby_11" value="hobby_11">
                Sci

 <input type="checkbox" name="hobby[]" id="hobby_12" value="hobby_12">
                Concerti

 <input type="checkbox" name="hobby[]" id="hobby_13" value="hobby_13">
                Motociclismo

 <input type="checkbox" name="hobby[]" id="hobby_14" value="hobby_14">
                Automobilismo

 <input type="checkbox" name="hobby[]" id="hobby_15" value="hobby_15">
                Test drive in pista

 <input type="checkbox" name="hobby[]" id="hobby_16" value="hobby_16">
                Teatro

 <input type="checkbox" name="hobby[]" id="hobby_17" value="hobby_17">
                Fotografia

 <input type="checkbox" name="hobby[]" id="hobby_18" value="hobby_18">
                Arte

 <input type="checkbox" name="hobby[]" id="hobby_19" value="hobby_19">
                Viaggi

          Professione

            <select name="professione">
              <option value="professione_1">Impiegato</option>
              <option value="professione_2">Libero professionista</option>
              <option value="professione_3">Agente di commercio</option>
              <option value="professione_4">Imprenditore</option>
              <option value="professione_5">Medico</option>
            </select>

          Iscritto ad associazioni di categoria

            <input type="radio" name="ass_cat" id="ass_cat_1" value="ass_cat_3">
            Confindustria

            <input type="radio" name="ass_cat" id="ass_cat_2" value="ass_cat_4">
            Confartigianato

            <input type="radio" name="ass_cat" id="ass_cat_3" value="ass_cat_5">
            Confagricoltura

            <input type="radio" name="ass_cat" id="ass_cat_4" value="ass_cat_6">
            Confcommercio

            <input type="radio" name="ass_cat" id="ass_cat_5" value="ass_cat_7">
            Forze dell'ordine

            <input type="radio" name="ass_cat" id="ass_cat_6" value="ass_cat_8">
            Ordine dei Dottori Commercialisti

            <input type="radio" name="ass_cat" id="ass_cat_7" value="ass_cat_9">
            Ordine degli avvocati

            <input type="radio" name="ass_cat" id="ass_cat_8" value="ass_cat_2">
            Ordine dei medici

            <input type="radio" name="ass_cat" id="ass_cat_9" value="ass_cat_10">
            Altri ordini professionali

            <input type="radio" name="ass_cat" id="ass_cat_10" value="ass_cat_1">
            Associazioni di volontariato varie

          Privacy marketing

            <input type="radio" name="privacy_mkt_all" id="privacy_mkt_all_1" value="privacy_mkt_all_1">
            Si
            <input type="radio" name="privacy_mkt_all" id="privacy_mkt_all_2" value="privacy_mkt_all_2">
            No

          Giorno preferito per il ricontatto

            <input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_1" value="giorno_ricontatto_1">
            Lunedì

            <input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_2" value="giorno_ricontatto_2">
            Martedì

            <input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_3" value="giorno_ricontatto_3">
            Mercoledì

            <input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_4" value="giorno_ricontatto_4">
            Giovedì

            <input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_5" value="giorno_ricontatto_5">
            Venerdì

          Orario preferito per il ricontatto

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_1" value="orario_ricontatto_1">
                09:00 - 10:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_2" value="orario_ricontatto_2">
                10:00 - 11:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_3" value="orario_ricontatto_3">
                11:00 - 12:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_4" value="orario_ricontatto_4">
                12:00 - 13:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_5" value="orario_ricontatto_5">
                13:00 - 14:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_6" value="orario_ricontatto_6">
                14:00 - 15:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_7" value="orario_ricontatto_7">
                15:00 - 16:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_8" value="orario_ricontatto_8">
                16:00 - 17:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_9" value="orario_ricontatto_9">
                17:00 - 18:00

 <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_10" value="orario_ricontatto_10">
                18:00 - 19:00

    <input type="submit" name="form_tools_continue" value="Continue">

</form>

A: use the id not the name of the input fields
e.g. var tipologia_auto = $("#tipologia_auto_1").val();

A: Ok, thank you! I need also to store these concatenated values into one field that will be saved into the MySql Database.


Q: How to run 'git diff --check' on certain file types only I have been unable to figure out how to run 'git diff --check' on only Python files in my commit. I have a commit with 3 files in it:
$ git show --name-only
...
tools/gitHooks/preReceive.py
tools/gitHooks/unittests/testPreReceive.py
Makefile

The last 2 files have trailing whitespace in them.
$ git diff --check HEAD~1 HEAD
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()
Makefile:41: new blank line at EOF.

I would like to restrict the whitespace check to only Python files. Doing this gives me the correct files:
$ git diff --name-only HEAD~1 HEAD | grep ".py"
tools/gitHooks/preReceive.py
tools/gitHooks/unittests/testPreReceive.py

But when I pipe the filenames to 'git diff --check' (with or without xargs) I get the wrong output.
$ git diff --name-only HEAD~1 HEAD | grep ".py" | xargs git diff --check HEAD~1 HEAD --
$
$ git diff --name-only HEAD~1 HEAD | grep ".py" | git diff --check HEAD~1 HEAD --
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()
Makefile:41: new blank line at EOF.

I also tried this as well as a few variations on it with no luck:
$ git diff --check HEAD~1 HEAD -- "*.py"
$

Can anyone help? I feel like I'm close to the answer.

A: From the original poster:
Turns out I was using the wrong grep.
$ git diff --name-only HEAD~1 HEAD | grep \.py$ | \
$ xargs git diff --check HEAD~1 HEAD --
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()