text:
Q: What is the right interpretation of the axiom of extensionality A set $a$ can be called extensional if it has the following propery:
$$\forall b\left[\forall x\left[x\in b\iff x\in a\right]\Rightarrow a=b\right]$$
Based on this the axiom of extensionality can be formulated as: $$\forall a\left[a\text{ is extensional}\right]$$

How exactly should  this axiom be interpreted?

I see two options:
1) The statement that every set is extensional.
2) The statement that  sets that are not extensional are to be neglected.
The first looks like a statement of a dictator. The second
more like an admittance that there is more, but that we agree to keep that out of sight. If statement 2) could be practicized
then I would choose for it, but I have my doubts about that, which is the reason
for asking this.
addendum
Inspired by comments and answers (thank you very much!) I have decided
to share something about my motivation and also my doubts about option
2).
A set $a$ is regular if it has the following property: $$\forall b\left[a\in b\Rightarrow\exists c\in b\; c\cap b=\emptyset\right]$$ Based on that the axiom of regularity can be formulated as: $$\forall b\left[b\text{ is regular}\right]$$
This axiom can be accepted in the awareness that you just restrict
your scope and focus on studying the regular ones. You could say that
option 2) 'works' here. If $\mathbf{V}$ denotes the class of all
extensional sets then there is a subclass $\mathbf{G}$ of regular
extensionals. Option 1) applied on regulars says: $\mathbf{V}=\mathbf{G}$
while option 2) says: focus on $\mathbf{G}$. Here I prefer the second
option. This is facilitated by the fact that the elements
of regular sets are regular, which means that by focusing on regulars
their elements do not get out of sight. It should be remarked here that you need the
axioms PAIR and SUM to prove this. This facilitation lacks (or seems to lack; uptil now I was looking for it in vain) when
it comes to extensionals, which was the reason for my doubt concerning
the second option applied on extensionals.

A: 1) is correct. There are things which are not extensional, but in a theory which accepts the axiom of extensionality, those things are not called "sets".
This is not "a statement of a dictator", whatever you mean by that, this is how language works: every term in every language has a definition, which describes what the term means and what it does not mean. In the same way that an elephant is not an insect, something which is not extensional is not a set.

A: You should interpret it the first way. Axioms of formal systems are to be satisfied without explanation. A model which instantiates a formal system must satisfy the axioms of the formal system.
Thus any model of ZF does not have a set that is not extensional, they are not merely 'not considered'. I mean that they cannot be neglected because non-extensional sets do not exist in a model of ZF.

A: To add to the other answers:
(1) does say that every set the quantifier ranges over is extensional, full stop. There's no room in any model of extensionality for non-extensional objects. But at the same time there are other theories of which ZF is a subtheory, or in which ZF is interpretable, including some with very different properties (some strong extensions of NFU, Esser's positive set theory).
The question, and it's a philosophical one, is whether to think of some of these other theories as actually axiomatizing a theory of sets. NFU+Choice doesn't satisfy extensionality, but it's usually interpreted as a theory of sets and other stuff; the things that are sets in the theory are characterised precisely by extensionality. As extensionality is a strong part of many people's intuitions about sets, you would have to make a case for deviation from it.

A: I think that can be useful to start from the debate about extensionality in modern mathematics and logic, that dates back to Cantor and Frege and their researches about classes and extensions.
We can start with the (very simplified) picture of a concept or "universal", we can symbolize it as $\phi(x)$,   and its extension, defined as the set of objects such that $\phi$ holds of them, we symbolize it as $\{ x : \phi(x) \}$.
Following the discovery of paradoxes of Cantor's set theory (with the Comprehension axiom : for every "condition" $\phi(x)$,  there exists the corresponding extension $\{ x : \phi(x) \}$) and of Frege's logic (with Basic Law V), several attempts was explored to solve them.
One of the most relevant attempt was due to Russell, in his Principles and then in the Principia.
The basic idea was to avoid the "language of classes (or set)" and adopt instead the language of "propositional functions"; think of them as "attributes", and assume for simplicity that they correspond to open formula (i.e. to $\phi(x)$).
According to Russell, propositional functions are primitive, and classes or sets are reduced to suitable "abbreviations" .
The following comment by the logician and philosopher Quine (Whitehead and the Rise of Modern Logic, 1941, reprinted in Selected Logic Papers, new edition 1995, page 22) is a good clarification of the issue :

To have reduced classes to attributes is of little philosophical consequence, for attributes are no less universal, abstract, intangible, than classes themselves.
[…] classes are identified when they coincide in point of members, whereas it may be held that attributes sometimes differ though they are attributes of just the same things. It is precisely this difference, in fact, and nothing more that Russell's contextual definition of classes accommodates; his is a technical construction enabling us to speak ostensibly of identical classes by way of shorthand for discourse about coincident but perhaps non-identical attributes.
Such definition rests the clearer on the obscurer, and the more economical on the less. Classes are more economical than attributes because they are scarcer: they coalesce when their members are the same. [emphasis added] Classes are clearer then attributes because they have a relatively definite principle of individuation: they differ from one another just in case their members differ, whereas attributes (if they diverge from classes at all) differ from one another also under additional circumstances whose nature is left, in Principia, quite unspecified. […]
In any case there are no specific attributes that can be proved in Principia to be true of just the same things and yet to differ from one another.

Due also to the immediate success of Zermelo's axiomatic set theory as a mathematical theory, compared to the solution developed into the Principia (the ramified theory of types), the "more clear and economical" conception of set as "extensional"  has become, since the beginning of last century, the "mainstream view" about classes or set.
In conclusion, referring to Malice Vidrine's answer, I think that is perfectly possible to think of "abandoning" our "intuitions about sets": from one side, we have a lot of interesting results based on extensional set theory; form the other side, we need support for "a case for deviation from it".

A: Something nice I learned from Wikipedia is that, even in logical systems that don't have an equality predicate built in, it's possible to express the axiom of extensionality as
$$\forall a,b: (\forall x: x \in a \iff x \in b) \iff (\forall y: a \in y \iff b \in y), \tag1\label{ik-eqn:1}$$
or, in words: "if $a$ and $b$ have all the same members, then they belong in all the same sets."
(In ZF set theory, at least, only the forward implication actually needs to be given as an axiom, since the converse follows from the other axioms.  However, if you don't mind a slight redundancy in your axioms, I prefer to include both implications in the formula to highlight its symmetry.)
The nice thing about the statement $\eqref{ik-eqn:1}$ is that the two sides of it can be seen as two halves of a definition of equality.  That is to say, we may rewrite it as
$$\forall a,b: a \overset R\sim b \iff a \overset L\sim b \tag2\label{ik-eqn:2}$$
where we define the predicates $\overset L\sim$ and $\overset R\sim$ as shorthand for

*

*$a \overset L\sim b \overset{def}\iff (\forall y: a \in y \iff b \in y)$, i.e.
"$a$ and $b$ are substitutable to the left of $\in$," and

*$a \overset R\sim b \overset{def}\iff (\forall x: x \in a \iff x \in b)$, i.e.
"$a$ and $b$ are substitutable to the right of $\in$."
It's easy to see that both of these are equivalence relations, and that any two sets $a$, $b$ that satisfy both $a \overset L\sim b$ and $a \overset R\sim b$ in fact fully satisfy the substitution property of equality with respect to $\in$, and are therefore indistinguishable by any set-theoretic formula (i.e. a formula that can be expressed using only $\in$ and logical symbols).
The full axiom $\eqref{ik-eqn:2}$ then simply asserts that either of these definitions of "half-equality" is, in fact, equivalent to the other (and thus to full equality, in the sense of indistinguishability by set-theoretic formulae): if $a$ and $b$ can be freely interchanged on the right-hand side of $\in$, then they can also be freely interchanged on the left-hand side of it.

So, how does this relate to your original question, then?
In simplest terms, the interpretation of extensionality I've given above falls under your interpretation #1: asserting that $\overset L\sim$ and $\overset R\sim$ are equivalent is essentially the same as asserting that all sets are extensional.
What I find nice about this interpretation, though, is that, by not requiring any fundamental equality predicate, it sidesteps any potential "metaphysical" issues related to it.  We simply have a definition of an equivalence relation $a \sim b \iff a \overset L\sim b \land a \overset R\sim b$, and an axiom further stating that, in fact, $a \overset L\sim b \iff a \overset R\sim b \iff a \sim b$.
It may be useful to contrast this view with user18921's "interpretation #3", which claims that the axiom of extensionality is itself a definition of set equivalence / equality.  In a sense, these views are the same: if we take $\overset R\sim$ as the definition of set equality, and assert that sets equal under this definition are freely substitutable, as in Malice Vidrine's comment, then we obtain an extensional set theory.
On the other hand, what I'm really saying is that there are two natural definitions of set equivalence with respect to $\in$, $\overset L\sim$ and $\overset R\sim$, which together imply indistinguishability using set-theoretical formulae.  Viewed this way, the axiom of extensionality does make a substantive, non-definitional assertion: it asserts that these two relations are, in fact, the same, and thus that any sets equivalent under either of them are in fact indistinguishable.

A: Suppose I want to focus on G.
Among the things that are true about G is

Every set is regular extensional

so, in the course of focusing on G, I will invoke this "dictatorial" fact which is true about the objects I'm studying.


text:
Q: PrintCommandListener is missing I'm trying to upload a file via FTP client using Java, but when trying the:
import org.apache.commons.net.PrintCommandListener;

the PrintCommandListener is show in red.  I verified my library and it does include commons.net.  What should I do?

A: PrintCommandListener is in fact in Apache Commons Net.  For example, if you download the current version, the jar you need to include in your build path is commons-net-3.3.jar.  If this single jar is seen by your compiler, then the class should be recognized.  Make sure there are no other classes called PrintCommandListener (for example custom ones that you might have written) in your build path.
If using an IDE (such as eclipse) make sure the jar is on your build path.  For example, with Eclipse right click project, go to Java Build Path and click Add JARs.  Navigate to the location of your jar file and add it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RegWrite returning ErrorLevel 1 Platform and settings:
AutoHotkey_L Unicode x86 1.1.13.0
RegView=Default
64-bit OS (W7)
32-bit script
Hi Folks,
The following line of code is returning ErrorLevel=1:
RegWrite,REG_DWORD,HKLM,SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System,PromptOnSecureDesktop,0
When I modify the registry manually, it works fine. Btw, the RegWrite fails in the same way with the ANSI x86 binary (I haven't tried the Unicode x64 binary). Anyone know why the RegWrite is failing? Thanks, Joe

A: The manipulation of registry entries usually postulates administrator privileges, which, as of WIN Vista or later must be acquired explicitely, if UAC wasn't turned off.
For AHK, call the following function (source):
RunAsAdmin() {
  Loop, %0%  ; For each parameter:
    {
      param := %A_Index%  ; Fetch the contents of the variable whose name is contained in A_Index.
      params .= A_Space . param
    }
  ShellExecute := A_IsUnicode ? "shell32\ShellExecute":"shell32\ShellExecuteA"

  if not A_IsAdmin
  {
      If A_IsCompiled
         DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_ScriptFullPath, str, params , str, A_WorkingDir, int, 1)
      Else
         DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_AhkPath, str, """" . A_ScriptFullPath . """" . A_Space . params, str, A_WorkingDir, int, 1)
      ExitApp
  }
}


text:
Q: Flag or disagree won't let me disagree
Possible Duplicate:
10k+ users can see flags now, but can't unflag

In the 10k tools, in the flags tab, when it shows a flagged post it has a button like so:

yet, when I press that button, it only brings up a flagging dialog, there is no way I see to disagree.  Please let me disagree.

A: I'm just going to steal Jeff's image from an answer elsewhere. When you click flag or disagree..., you'll get the following dialogue, which the relevant section has been highlighted.

It's already been stated that it's not the most intuitive way to go about it, but it's certainly present.


text:
Q: Is it a good idea to supply jwt token in url? I need to make JSONP REST calls in one of our app. In order to authenticate I got to supply JWT token in url.
I got some idea about its security aspects through this post.
Is it safe to put a jwt into the url as a query parameter of a GET request?
However, I'd like to understand a little more about how could one supply JWT token to JSONP in more secure way.
I may not be able to furnish more details about my app but believe me we haven't to use JSONP for seeving some specific need.
Thanks a lot.

A: If it is part of the query parameter than it goes into the web server log files, also (if not https) the logs of any intervening proxy server. If anyone can access those logs then they can re-use your token. This may not matter if the jwt has a fairly short expiry, but if it has a long expiry time it could be significant.
Also if you put the token in the URL and the URL gets shared with another user then until it expires have your access to that resource. This would particularly matter if the URL with token ever appears in an address bar as someone might just copy/paste it.
JWT is not usually encrypted, just signed. That means anyone can extract the information from the token even if it has expired. So that means if they get hold of old logs they have a record of which user accessed which content, and they may also be able to harvest personal data such as emails.
A better place to pass it would be in an Authorization header. Then it won't be logged. e.g.
Authorization: Bearer <token goes here>


text:
Q: Detect removal of open serial port devices (Qt / Windows) I have a Qt app which communicates with a dongle via serial (it's an FTDI chip). I poll QSerialPortInfo::availablePorts() to detect when ports are added or removed, and then send the dongle a blank line to identify it (my dongle responds to this with its ID, I'm banking on it being harmless to 99% of other devices).
This all works fine, except that if you remove the dongle while the connection is active, it seems like the connection isn't closed and the port is still returned in QSerialPortInfo::availablePorts().
Does anyone know how to detect the serial dongle's removal while I have a connection to it (other than hacks like pinging it).
I've tried listening for all the signals QSerialPort emits (error(), readChannelFinished(), etc.) but none of them are emitted when you pull the dongle out. This is on Windows 7 by the way.

A: I see the same issue with Qt 5.4.1, but only on Windows 7. On Windows 8 the removal of the dongle is detected.
It is actually the problems of the windows 7 itself. If you check with Device Manager you can notice that COM port remains on the list, if it has been open even in the case when dongle is removed.


text:
Q: In Azure SignalR Service, what is a Concurrent Connection? The pricing for Azure SignalR Service is based on Concurrent Connections.
However, I can't find the definition of a Concurrent connection.
I have an ASP.Net Core MVC Web Application.  I understand that the server application connection to the Azure SignalR Service is one connection.  Each client (browser) that connects to my web app is another connection.  But are these considered concurrent connections?  Or just open connections sitting there waiting for a message to be sent?
I'm hoping that the count of concurrent connections is a count of connections that are actively sending a message.  Is that the case?

A: Ok so I figured out that a Concurrent connection is any connection to the SignalR Service!
I ran through the quickstart tutorial here
And then used the Azure Metric as I connected various clients to the chat room, and this is what I found:

After starting the app in debug mode, it seems the server immediately uses 5 connections.  Then, as I open the url in various browser tabs, a new Client connection is established.  As expected, the 16th browser tab does not establish a SignalR connection (Because I am on the Free SignalR Service tier, which has a limit of 20 connections.)


text:
Q: Spring JPA Hibernate Maven - Error : No persistence units parsed from {classpath*:META-INF/persistence.xml} While testing the application created in Getting Started With JPA in Spring 2.0 tutorial I am getting following error. I have created Maven Project in eclipse. Here is the part of the structure of the project
ecotraveler
   src
      main
         java
             com
                enam
         resources
             config
                   applicationContext.xml
   WebContent
       META-INF
           persistance.xml

While running test class I am getting No persistence units parsed from {classpath*:META-INF/persistence.xml}
Can anyone tell what could be the problem? It seems application is unable to find specified path. I double check that WebContet/META-INF is in eclipse build path.

A: You need to put the META-INF directory in you resources directory, not in the WebContent

A: You spelt "persistence.xml" wrong; it has no "a"


text:
Q: Oracle Coherence License Issue Are there any restrictions for using coherence.jar without any license?
coherence.jar is open for downloading without any fee.

A: You can use it for development purposes. Any other purpose means purchasing a license. On the download page is a link to the license agreement that states:

You may not:

*

*use the programs for your own internal data processing or for any
  commercial or production purposes, or
  use the programs for any purpose
  except the development of your
  application;

*use the application you develop with the programs for any internal data
  processing or commercial or production
  purposes without securing an
  appropriate license from us;

*continue to develop your application after you have used it for any
  internal data processing, commercial
  or production purpose without securing
  an appropriate license from us, or an
  Oracle reseller;

*remove or modify any program markings or any notice of our
  proprietary rights;

*make the programs available in any manner to any third party;

*use the programs to provide third party training;

*assign this agreement or give or transfer the programs or an interest
  in them to another individual or
  entity; - cause or permit reverse
  engineering (unless required by law
  for interoperability), disassembly or
  decompilation of the programs;

*disclose results of any program benchmark tests without our prior
  consent.

The first two points are the most relevant.

A: On the Coherence download page it says you need to agree to the Oracle Technology Network (OTN) License Agreement to download the software.
That license contains this text:

We grant you a nonexclusive, nontransferable limited license to use the programs only for the purpose of developing, testing, prototyping and demonstrating your application, and not for any other purpose. If you use the application you develop under this license for any internal data processing or for any commercial or production purposes, or you want to use the programs for any purpose other than as permitted under this agreement, you must obtain a production release version of the program by contacting us or an Oracle reseller to obtain the appropriate license.

So it's a free download only for development purposes.  (Most Oracle Products are available free to developers.)
But if you want to use this code in production or in a product you're selling you will need a license.

A: Have you considered using Infinispan as an open source alternative to Coherence?

A: Don't forget that the version that you download from the public website is usually just the major release.  The minor release, with all the many bug fixes, is only available if you have a support contract.


text:
Q: Get values in another column depending on values in another column pandas I have a Pandas dataFrame with columns A, B, & C. I want to select values in B that sum up to value in column A then select values in column C whose index match the selected values from column B.
A         B                                C
3       [1, 2, 5]                [107385, 128281, 133015]
4       [9, 2,5,2]               [108664, 110515, 113556, 54545]
2       [1.0, 2, 4, 8, 4]        [134798, 133499, 125396, 114298, 133915]

Say for the last row, i will just pick 2 from column B coz it exactly equal to 2 in Column A, and then i will select 133499 in column C and return that number only from C.
Output
      **D**
[107385, 128281]
[ 110515,  54545]
[ 133499]

Can someone help me here? Thanks in advance


text:
Q: How to add a comparator to querydsl Predicate? I have the following webservice the automatically translates get parameter queries to database selects:
public interface PersonRepo extends
        JpaRepository<Person, Long>,
        QuerydslPredicateExecutor<Person> {

}

@GetMapping
public ResponseEntity getFiltered(
    @QuerydslPredicate(root = Person.class) Predicate predicate, Pageable pageable) {
       return ResponseEntity.ok(personRepo.findAll(predicate, pageable)));
    )
}

The following queries could eg be executed:
GET /people?name=John&age=18
GET /people?name=John&age=18&page=1&sort=name,desc

Problem: I want to apply comparator queries as follows:
GET /people?name=John&age>18
GET /people?name=John&age>18&age<30
GET /people?name=John&age<30

Question: how could I achieve this? At least the later queries don't work.

A: I found a solution by defining a placeholder for the field, and using a QuerydslBinderCustomizer:
public interface PersonRepo extends
        JpaRepository<Person, Long>,
        QuerydslPredicateExecutor<Person>,
        QuerydslBinderCustomizer<Person> {
    default void customize(final QuerydslBindings bindings, final QPerson person) {
        bindings.bind(cache.ageMin).first((path, value) -> person.age.goe(value));
        bindings.bind(cache.ageMax).first((path, value) -> person.age.loe(value));
    }
}

Of course the age fields then have to exist as transient fields, so that querydsl knows them:
@Entity
class Person {
    @Transient
    @QueryType(PropertyType.NUMERIC)
    public int ageMin;

    @Transient
    @QueryType(PropertyType.NUMERIC)
    private int ageMax;
}

A: You could use a single binding and use expressions from Query DSL value operators.
public interface PersonRepo extends
    JpaRepository<Person, Long>,
    QuerydslPredicateExecutor<Person>,
    QuerydslBinderCustomizer<Person> {
    default void customize(final QuerydslBindings bindings, final QPerson person) {
        bindings.bind(cache.age).all((path, values) -> ExpressionProviderFactory.getPredicate(path, values));
    }
}


text:
Q: How to map /sys/bus/usb/devices to /dev/video*? I am using a library (librealsense) that only outputs the bus and port number as such (9.1). It uses libusb internally. The issue is from this identifier in libusb I want to know what physical device it belongs to in /dev/video0. For instance, 9.1 -> /dev/video0 and 7.2 -> /dev/video2 when two cameras are plugged in in ports 9.1 and 7.2.
Is this possible? How do I acquire what devices paths belong to a bus and port? Any partial answer would be helpful.

A: Answering so I can close this question full credit to @ridgy and @dirkt for their help. With the command:
udevadm info -n video0 -q path

Or similarly with ls -l /sys/class/video4linux/, a path of the form /devices/pci0000:00/0000:00:10.0/usb7/7-2/7-2:1.0/video4linux/video0 can be found. That in combination with the listing of the video devices using either ls /dev/video* or v4l2-ctl --list-devices allows a map between the usb port and video device to be created.

A: you can also use below command to get more information

udevadm info -a -p $(udevadm info -q path -n /dev/video0)
udevadm info -a -p $(udevadm info -q path -n /dev/video1)


text:
Q: Gnuplot insert points in a parallel plot I need create a parallel plot with lines and points using gnuplot.
Unfortunately either using
set style line 1 lc rgb 'blue' lt 1 lw 2 pt 7 ps 0.75 pi 5

or by setting pt ps and pi in plot command
Gnuplot do not insert any point.
I need to insert points to distinguish two line with the same color.
They have to be the same color since they are of the same "family". Therefore, I can not simply change the colors :(
How can I do that?
Thanks

A: It is unfortunately true that Gnuplot does not support this feature "out of the box", nevertheless should you need this just for some quick one-time production plot then there is a slightly dirty way how to do this. To be more specific, one can get the current source code of Gnuplot, in a more or less satisfactory way introduce this feature and generate the desired figure with the modified version of Gnuplot.
To illustrate the idea, let's assume that we want to parallel-plot following data file data.dat consisting of merely three "sets":
1 2 3
2 1 1
3 3 3

Inspired by the default Gnuplot demo parallel.dem, one would probably try to achieve this with a script test.gpl like this:
set title "Parallel Axis Plot" font ",15"

set terminal pdf
set output 'test.pdf'

set border 0
unset key
set xrange [] noextend
unset ytics

# use x-axis tic positions to label the axes
set xtics 1 format "axis %g" scale 0,0

# turn on axis tics for the parallel axes
set for [i=1:3] paxis i tics

plot 'data.dat' using 1:2:3 with parallel

However, this produces plot which will probably resemble:

Here, all lines are of the same type and color which is rather confusing. As a small upgrade, let's modify our input data file as follows:
1 2 3 5
2 1 1 6
3 3 3 7

and use slightly different plotting command
plot 'data.dat' using 1:2:3:4 with parallel lc var

This yields

The resulting figure looks a bit better but let's say that we do insist on having a plot with points. Simply adding something like pt 1 does not work. Moreover, it produces a warning message: "test.gpl", line 17: warning: No pointtype specifier allowed, here suggesting that parallel style does not like any point specification at all.
Dirty fix
To partially improve upon this, let's proceed as follows:
cd ${HOME}

#prepare a sand box directory
mkdir gpl
cd gpl

#download the latest version
wget -O gnuplot_latest.tgz http://sourceforge.net/projects/gnuplot/files/latest/download?source=files
tar -xzvf gnuplot_latest.tgz

cd gnuplot-5.0.0
./configure --prefix=${HOME}/gpl/local
make && make install

Here, we are assuming that our system already has all the necessary prerequisites for a successful build. For example on Ubuntu, this minimal-case scenario should probably require just the development packages of libpango and libreadline.
Now, we need to play a little bit with some of the source files stored in ${HOME}/gpl/gnuplot-5.0.0/src. Namely, we have to

*

*convince Gnuplot that the plotting style parallel likes points. For this it is sufficient to modify line 114 in gp_types.h and replace
PARALLELPLOT = 32*PLOT_STYLE_BITS + PLOT_STYLE_HAS_LINE

with
PARALLELPLOT = 32*PLOT_STYLE_BITS + PLOT_STYLE_HAS_LINE + PLOT_STYLE_HAS_POINT

*introduce the ability to plot points within the parallel style. To this end, one has to locate the function plot_parallel in file graphics.c. By default it looks like this:
static void
plot_parallel(struct curve_points *plot)
{
    int i, j;
    int x0, y0, x1, y1;

    for (i = 0; i < plot->p_count; i++) {

    /* rgb variable  -  color read from data column */
    check_for_variable_color(plot, &plot->varcolor[i]);

    x0 = map_x(1.0);
    y0 = AXIS_MAP(PARALLEL_AXES+0, plot->z_n[0][i]);
    for (j = 1; j < plot->n_par_axes; j++) {
        x1 = map_x((double)(j+1));
        y1 = AXIS_MAP(PARALLEL_AXES+j, plot->z_n[j][i]);
        draw_clip_line(x0, y0, x1, y1);
        x0 = x1;
        y0 = y1;
    }

    }
}

Let's pimp it up a little bit:
static void
plot_parallel(struct curve_points *plot)
{
    int i, j;
    int x0, y0, x1, y1;

    int point_type;
    struct termentry *t = term;

    for (i = 0; i < plot->p_count; i++) {

    /* rgb variable  -  color read from data column */
    check_for_variable_color(plot, &plot->varcolor[i]);
    point_type = plot->varcolor?((int)plot->varcolor[i]-1):plot->lp_properties.p_type;

    x0 = map_x(1.0);
    y0 = AXIS_MAP(PARALLEL_AXES+0, plot->z_n[0][i]);

   (*t->pointsize)(plot->lp_properties.p_size);
   (*t->point)(x0, y0, point_type);

    for (j = 1; j < plot->n_par_axes; j++) {
        x1 = map_x((double)(j+1));
        y1 = AXIS_MAP(PARALLEL_AXES+j, plot->z_n[j][i]);
        draw_clip_line(x0, y0, x1, y1);
        (*t->point)(x1, y1, point_type);
        x0 = x1;
        y0 = y1;
    }

    }
}

*and that's it! Now compile Gnuplot again with make && make install (invoked from directory ${HOME}/gpl/gnuplot-5.0.0). The output generated with ${HOME}/gpl/local/bin/gnuplot ${HOME}/gpl/test.gpl (using plotting command plot 'data.dat' using 1:2:3:4 with parallel lc var ps 1.5) should resemble this:

Explanation

*

*modification in gp_types.h ensured that the point size specification ps 3 used in the final plot is not ignored (and is accessible in the plot_parallel function)

*in the plot_parallel function, we need to introduce a pointer to the global terminal variable, i.e., struct termentry *t = term;. This is then used later for the actual plotting of points.

*in the for loop which iterates over individual lines in the input data file, we determine the corresponding point type with
`point_type = plot->varcolor?((int)plot->varcolor[i]-1):plot->lp_properties.p_type;`

This ensures that if we don't use lc var then the point type is determined by pt (or default). If lc var is active, the point type is taken from the corresponding data column in the input data file.

*call (*t->pointsize)(plot->lp_properties.p_size); sets the desired point size specified with ps (or default).

*finally, calls of the type (*t->point)(x0, y0, point_type); augment individual line segments with the points.


text:
Q: Git clone repository in a specific folder but keep default folder name So I'm using the git clone command but when I try to clone the repository into a specific folder it doesn't create a folder like it does normally.
For example when I use it like this
git clone https://github.com/username/repositoryName.git

it creates a folder named repositoryName and stores the repository in there. When I'm using it like this
git clone https://github.com/username/repositoryName.git myFolderName

it doesn't create that default folder it would create. It just saves it in myFolderName. The thing is that I want it stored in that default folder but I want that default folder in myFolderName. I can't use mv command because I don't know the defaults folder name and I clone a lot of repositories at the same time. Any ideas?
Thanks in advance.

A: You should be able to do it with,
git clone https://github.com/username/repositoryName.git myFolderName/repositoryName

PS:
This is how you could  split the repository name from the URL
basename -s .git $(echo "https://github.com/username/repositoryName.git")

A: Assuming that myFolderName already exists the simplest solution is this:
git -C myFolderName clone https://github.com/username/repositoryName.git

A: What about something like this:
## Your links in an array
declare -a arr=("https://github.com/username/repositoryName" "https://github.com/username/repositoryName2")

## Folder to store each of these git repos
folder=myFolderName

## Go through each link in array
for i in "${arr[@]}"
do
    ## Use basename to extract folder name from link
    git clone $i $folder/$(basename $i)
done

Which will produce your following git repositories:
myFolderName/repositoryName
myFolderName/repositoryName2

Note: You don't need to add .git at the end of each HTTPS link for git clone.
If you need to include .git for some reason, you can strip it with:
git clone $i $folder/$(basename ${i%.*})


text:
Q: Cannot override mutable property 'collectionView' of type 'UICollectionView?' with covariant type 'GeminiCollectionView?' I have had a custom collection view and everything worked fine. I wanted to include 'Gemini' to make beautiful animations when sliding my cells horizontally. I believe that the problem is not Gemini, I think the same would have happen with changing VC class to any other one, but I dont know how to solve this because I never faced with this before, is there a shortcut from this?

I have installed and imported the pod into code.

I had a UICollectionViewController but to work with gemini I needed to connect my collectionView from Storyboard to ViewController. Before that, I have put a class in Storyboard for my CollectionView to be GeminiCollectionView like in the image below:

After that, I changed a class for my CollectionView in ViewController, too, like in the image below and got those three errors:

In the later code, it doesnt show any errors:
viewDidLoad
collectionView.gemini
            .rollRotationAnimation()
            .degree(45)
            .rollEffect(.rollUp)

cellForItemAt
self.collectionView.animateCell(cell)

scrollViewDidScroll
self.collectionView.animateVisibleCells()

willDisplay cell
if let cell = cell as? RatingCell {
//RatingCell inhertis the GeminiCell class
            self.collectionView.animateCell(cell)
        }

So, all the code is fine except the declaration as I mentioned at the beginning and here:
@IBOutlet var collectionView: GeminiCollectionView!

Waiting for random guys to unvote this :P

A: Solved
@IBOutlet var collectionView: GeminiCollectionView!

That line was a problem. Seems like you mustn't default Swift's name to override mutable property, which is collectionView for Collection Views and tableView for Table Views.

I changed that line to
@IBOutlet var collView: GeminiCollectionView!

...and the errors disappeared.


text:
Q: How do i fix 'Loss is nan, stopping training'? I've been trying to run an specific proyect (https://github.com/nicolaihaeni/MinneApple) where i have to run a training model for fruit counting/detection with image recognition.
I tried running the code given for it many times but i still get the following error after running python train_rcnn.py --data_path data --model frcnn --epochs 50 --output-dir data/train/train_results:
Start training
Epoch: [0]  [ 0/20]  eta: 0:04:09  lr: 0.001072  loss: 3.8136 (3.8136)  loss_classifier: 0.9121 (0.9121)  loss_box_reg: 0.6673 (0.6673)  loss_objectness: 2.0488 (2.0488)  loss_rpn_box_reg: 0.1854 (0.1854)  time: 12.4626  data: 4.8800  max mem: 3233
Loss is nan, stopping training
{'loss_classifier': tensor(nan, device='cuda:0', grad_fn=<NllLossBackward0>), 'loss_box_reg': tensor(nan, device='cuda:0', grad_fn=<DivBackward0>), 'loss_objectness': tensor(nan, device='cuda:0', grad_fn=<BinaryCrossEntropyWithLogitsBackward0>), 'loss_rpn_box_reg': tensor(nan, device='cuda:0', grad_fn=<DivBackward0>)}

An exception has occurred, use %tb to see the full traceback.

The images and masks database can be found here (if someone wants to reproduce this): https://conservancy.umn.edu/handle/11299/206575
I'll keep digging while I wait for answers, thank you in advance.
P.D.: The full traceback:
---------------------------------------------------------------------------

SystemExit                                Traceback (most recent call last)

<ipython-input-11-d923a94e9af1> in <module>
      4 start_time = time.time()
      5 for epoch in range(epochs):
----> 6     train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq)
      7     lr_scheduler.step()
      8

/content/drive/MyDrive/universidad/t3/MinneApple/utility/engine.py in train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq)
     41             print("Loss is {}, stopping training".format(loss_value))
     42             print(loss_dict_reduced)
---> 43             sys.exit(1)
     44
     45         optimizer.zero_grad()

SystemExit: 1


text:
Q: Dispatching further actions when handling actions I have a scenario where I feel like I need to dispatch an action in response to another action, and I don't know the best way to sort it out.
An action is dispatched in response to an HTTP response, something like:
type: 'auth'
data: { username: 'tom' }

Because that response was successful, I want to dispatch an action to send the user to the homepage:
type: 'navigate'
date: { where: 'home' }

This seems like a sensible flow to me: this thing happened, so now I want this thing to happen. Trouble is, the Flux Dispatcher doesn't allow this as we are still in the dispatch cycle. I get why dispatching while dispatching is a bad idea.
Some people have solved this with multiple dispatchers, whilst it seems that the Flux authors are sure that you only need one and that you need to rethink your stores.
I don't see how I could restructure my stores to facilitate this without obfuscating the intent. My UserStore knows about auth actions, and my RouteStore knows about navigate actions. Any suggestions on how the stores could be changed to facilitate this would be appreciated.
I feel like a setImmediate would work, but it seems a bit dirty. I also think a dispatcher that queued actions might help but I can feel in my bones that this could cause nasty problems.
What is the best way out of this?

A: You should look back how you are trying to create this flow.
You say that you need to create an action in response to another action, right?
So, let's name this the "ActionForwarderStore".
We end up with a flow like this:
AuthAction --> Dispatcher --+--> UserStore
                            |
                            +--> ActionForwarderStore --+
                                                        |
           +--------------------------------------------+
           |
           +-> Dispatcher -----> RouteStore

You see that you still have someone that understands that a AuthAction should end up changing a route? This is the ActionForwarderStore. As Flux suggests that every Store listens to every Action, this knowledge of the AuthAction ending up in a route change can go straight into RouteStore. Like this:
AuthAction --> Dispatcher --+--> UserStore
                            |
                            +--> RouteStore

Remember that Flux was "created" in order to avoid the unpredictability of MVC. If you keep all your route changes into RouteStore, you just need to look at this Store code to understand what Actions will cause a route change. If you go in the way of creating an action in response to another action, you will only know that NavigateAction changes routes, and you will need to look at the other Stores to check which ones are triggering this Action in response to others.
This is what Flux names as "unidirectional flow". It's easy to catch problems this way because this is the only flow allowed. If you click a button and it changes the route, you can know for sure that the action that the click dispatched is causing the route change, there are no cascading actions.

A: Usually, the solution to this problem is to to back up and look at the original action, and to waitFor the value that you are trying to send in the second action, if a derived value is required.
So in this case you would respond only to 'auth' in both the UserStore and the RouteStore.


text:
Q: c# How to translate Json data into an objects I'm trying to parse some JSON using the Newtonsoft.Json library. The documentation seems a little sparse and I'm confused as to how to accomplish what I need. Here is the format for the JSON I need to parse through.
const string json = @"{   ""error"" : ""0"",
""result"" :
{
   ""1256"" : {
      ""data"" : ""type any data"",
      ""size"" : ""12345""
   },
   ""1674"" : {
      ""data"" : ""type any data"",
      ""size"" : ""12345""
   },
   // ... max - 50 items
}
}";

I'm trying to convert JSON data a nice object of some kind. Here is my class:
public class ListLink
{
    public String data{ get; set; }
    public String size { get; set; }
}

public class SubResult
{
    public ListLink attributes { get; set; }
}

public class Foo
{
    public Foo() { results = new List<SubResult>(); }
    public String error { get; set; }
    public List<SubResult> results { get; set; }
}
.....
List<Foo> deserializedResponse =
    (List<Foo>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Foo>));

But i always get an error. Any ideas?
EDIT:
I get an Error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[ConsoleApplication1.Foo]' (...)

A: Sample:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public struct Element {
    public string data{ get; set; }
    public int size { get; set; }
}

class Sample {
    static public void Main(){
        const string json =
        @"{ ""error"" : ""0"",
            ""result"" :
            {
               ""1256"" : {
                  ""data"" : ""type any data(1256)"",
                  ""size"" : ""12345""
               },
               ""1674"" : {
                  ""data"" : ""type any data(1674)"",
                  ""size"" : ""45678""
               },
            }
        }";
        dynamic obj =  JsonConvert.DeserializeObject(json);
        int error = obj.error;
        Console.WriteLine("error:{0}", error);
        dynamic result = obj.result;
        Dictionary<string, Element> dic = new Dictionary<string, Element>();
        foreach(dynamic x in result){
            dynamic y = x.Value;
            dic[x.Name] = new Element { data = y.data, size = y.size};
        }
        //check
        Element el = dic["1674"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
        el = dic["1256"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
    }
}

OUTPUT:
error:0
data:type any data(1674), size:45678
data:type any data(1256), size:12345

A: This is a bit ugly, but may suit your needs. It doesn't use a third party solution either. Apologies if it is a bit kludgey!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

const string json = @"{   ""error"" : ""0"",
                            ""result"" :
                            {
                               ""1256"" : {
                                  ""data"" : ""type any data"",
                                  ""size"" : ""123456""
                               },
                               ""1674"" : {
                                  ""data"" : ""type any data"",
                                  ""size"" : ""654321""
                               },
                               ""1845"" : {
                                  ""data"" : ""type any data"",
                                  ""size"" : ""432516""
                               },
                                ""1956"" : {
                                  ""data"" : ""type any data"",
                                  ""size"" : ""666666""
                               }
                            }
                            }";

JavaScriptSerializer j = new JavaScriptSerializer();

var x = (Dictionary<string, object>)j.DeserializeObject(json);

Foo foo = new Foo();

foo.error = x["error"].ToString();

foreach (KeyValuePair<string, object> item in (Dictionary<string, object>)x["result"])
{

    SubResult result = new SubResult();

    ListLink listLink = new ListLink();

    var results = (Dictionary<string, object>)item.Value;

    foreach (KeyValuePair<string, object> sub in results)
    {

        listLink.data = results.First().Value.ToString();
        listLink.size = results.Last().Value.ToString();

    }

    SubResult subResult = new SubResult { attributes = listLink };

    foo.results.Add(subResult);

}


text:
Q: Turkish babel and acronym package issue When using babel-turkish package with package acronym, following error is producing.:

! Missing \endcsname inserted.  \relax l.9
  \AC@undonewlabel{acro:GSM}

The code is below:
\documentclass[12pt]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc} % also latin5
\usepackage[turkish,shorthands=:!]{babel}
\usepackage{mathpazo}
\usepackage{lipsum}
\usepackage[printonlyused,withpage]{acronym}

\begin{document}

\chapter{A}

In the early nineties, \ac{GSM} was deployed in many European countries.
\acf{GSM} offered for the first time international roaming for mobile
subscribers. The \acs{GSM}'s use of \ac{TDMA} as its communication standard was
debated at length. And every now and then there are big discussion whether
\ac{CDMA} should have  been chosen over \ac{TDMA}.

\begin{acronym}[TDMA]
 \acro{CDMA}{Code Division Multiple Access}
 \acro{GSM}{Global System for Mobile communication}
 \acro{NA}[\ensuremath{N_{\mathrm A}}]
 {Number of Avogadro\acroextra{ (see \S\ref{Chem})}}
 \acro{NAD+}[NAD\textsuperscript{+}]{Nicotinamide Adenine Dinucleotide}
 \acro{NUA}{Not Used Acronym}
 \acro{TDMA}{Time Division Multiple Access}
 \acro{UA}{Used Acronym}
 \acro{lox}[\ensuremath{LOX}]{Liquid Oxygen}%
 \acro{lh2}[\ensuremath{LH_2}]{Liquid Hydrogen}%
 \acro{IC}{Integrated Circuit}%
 \acro{BUT}{Block Under Test}%
 \acrodefplural{BUT}{Blocks Under Test}%
 \end{acronym}
\end{document}

When I commented out the line \usepackage[turkish,shorthands=:!]{babel}, everything is OK.
Why are errors caused? Thank you for your valuable time.

A: The acronym package uses a colon in its internal labels and this conficts with the active colon set up by babel-turkish. There's nothing special about the colon, so we can change it into something else, possibly unique. I chose @@@@.
\documentclass[12pt]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc} % also latin5
\usepackage[turkish,shorthands=:!]{babel}
\usepackage{mathpazo}
\usepackage{lipsum}
\usepackage[printonlyused,withpage]{acronym}

\usepackage{xpatch}

\makeatletter
\xpatchcmd{\AC@@acro}{:}{@@@@}{}{}
\xpatchcmd{\AC@@acro}{:}{@@@@}{}{}
\xpatchcmd{\AC@placelabel}{:}{@@@@}{}{}
\makeatother

\begin{document}

\chapter{A}

In the early nineties, \ac{GSM} was deployed in many European countries.
\acf{GSM} offered for the first time international roaming for mobile
subscribers. The \acs{GSM}'s use of \ac{TDMA} as its communication standard was
debated at length. And every now and then there are big discussion whether
\ac{CDMA} should have  been chosen over \ac{TDMA}.

\begin{acronym}[TDMA]
 \acro{CDMA}{Code Division Multiple Access}
 \acro{GSM}{Global System for Mobile communication}
 \acro{NA}[\ensuremath{N_{\mathrm A}}]
 {Number of Avogadro\acroextra{ (see \S\ref{Chem})}}
 \acro{NAD+}[NAD\textsuperscript{+}]{Nicotinamide Adenine Dinucleotide}
 \acro{NUA}{Not Used Acronym}
 \acro{TDMA}{Time Division Multiple Access}
 \acro{UA}{Used Acronym}
 \acro{lox}[\ensuremath{LOX}]{Liquid Oxygen}%
 \acro{lh2}[\ensuremath{LH_2}]{Liquid Hydrogen}%
 \acro{IC}{Integrated Circuit}%
 \acro{BUT}{Block Under Test}%
 \acrodefplural{BUT}{Blocks Under Test}%
 \end{acronym}
\end{document}


text:
Q: Adding FormData object as value for an object key to be sent as post request I am working on an app where I need to send an image blob as FormData alongside some other data sent as Json.
For this I'm making an http post request to the api with the following data:
const blob = new Blob(['some-image], {type: 'image/jpeg'});

const formData = new FormData();

formData.append("file", blob);

const data = {
  name: 'John',
  age: '24',
  uploads: formData
};

For http post request I'm using fetch:
async postData() {
    try {
      const res = await fetch(endpoint, {
          method  : 'POST',
          headers : {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data),
        });

      return res.status;
    } catch (error) {
      console.log(error)
    }
}

I'm unable to get the file in the backend which just shows an empty object inside uploads['file']. Why is that? Is it not possible to send formData as json with other data?

A: You could just send the FormData as the body.
const formData = new FormData();

formData.append("file", blob);

const data = {
  name: 'John',
  age: '24'
};

// add all key-value pairs of object to the FormData
for (const [key, val] of Object.entries(data))
    formData.append(key, val);

// ...
fetch(endpoint, {
    method  : 'POST',
    body: formData
});

Then you can access the blob as the "file" request parameter and each of the object properties as request parameters also (e.g. "age").


text:
Q: Displaying custom post types as a gallery This is a bit of a specific question--I have found bits and pieces of information on the net, but nothing that puts the whole picture together for me. Hopefully I can get some help here.
Background: I am a newbie to Wordpress. I'm using it as the CMS for a t-shirt shop I'm working on. My 't-shirts' custom post type is set up, but I want to create a 'T-shirts' page that will display all my available t-shirts in a gallery style.
I really don't want to use an e-commerce plug-in because I want a bit more control over how my 'T-shirts' page looks and functions.
Problem(s):
1. I need a code that will output the grid layout automatically. Each new 't-shirt' post should occupy the top left grid space. With each new 't-shirt' added, the old ones should automatically shift right to the next space.
If it helps, the rest of my site uses a 16 column 960px grid--ideally each grid space will be 220px wide (4 columns).
2. I have set up the featured image in my 't-shirt' posts as a thumbnail preview, so I'd like the gallery to display JUST the featured image with the title beneath.
3. I want the gallery to begin paginating after about 12 posts.
From the little I know about Wordpress, I think I'll need to use some loop functions but I have no clue which ones.
Hopefully someone here can help shed some light on this for me.

A: http://www.rvoodoo.com/who-are-the-voodoo-empire/
Something like that I assume?  That's a CPT displayed as sort of a grid.
Basically, you wrap the loop in a div.  Set the width of that div.  Say your overall width is 900px for your page.  You could set the post width as 250.  so 3 of them will be 750 wide, that gives you 150px of padding to use, etc.  You float the divs left.... then they automatically line up next to each other til they run out of space, then go to the next line.  By default, WP would put the newest one top left, if you floated left.  The older ones keep moving right until they wrap to the next line.
To limit to 12 posts, and paginate afterwards, you just use a query.
http://wordpress.org/search/query_posts
Now I don't know your theme, your css selectors will be different than mine, etc.  I'm just going to post what I use, and you can pick it apart.  The code will be different, but the concept remains the same.
You'll also notice I use enqueue style here.  Since the grid layout is different from my normal posts, I only call the stylesheet for the grid on this page.
the query I use here, I've modified to meet your needs, but the rest of the stuff you'll need to tweak.  Like I display the excerpt here, you don't want that.  And the whole entry-utility section I have will not apply to you.  But, Like I said, I'm throwing this up in hopes it will help you with the concept.
    <?php
wp_enqueue_style(  "member_css", $voodoo_template_dir . '/scheme/member-template.css', false, "1.0", "all" );
get_header();
query_posts( array(
      'post_type' => 've_members',
      'posts_per_page' => 12,
      'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
 ));
?>

<?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

        <div class="memberPost" id="post-<?php the_ID(); ?>">

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?>

                    <a rel="lightbox" href="<?php $image_id = get_post_thumbnail_id();
                    $image_url = wp_get_attachment_image_src($image_id,'large', true);
                    echo $image_url[0];  ?>">
                    <?php the_post_thumbnail('member-thumb', array( 'class' => 'member-thumb aligncenter' ) ); ?>

                    <?php the_excerpt(); ?>

                        <?php get_template_part( 'icons', 'members' ); ?>

                        <?php if(function_exists('sfc_like_button')) : ?>
                        <?php sfc_like_button(array('layout' => 'button_count')); ?>
                        <?php endif; ?>

                        <?php if(function_exists('stc_tweetbutton')) : ?>
                        <?php stc_tweetbutton(); ?>
                        <?php endif; ?>

                    <?php comments_popup_link( __( '[Leave a Message]', 'voodoo_lion' ), __( '[1 Message]', 'voodoo_lion' ), __( '[% Messages]', 'voodoo_lion' ) ); ?>

        <?php endwhile; ?>

<?php endif; ?>

<?php get_footer(); ?>

And here is my stylesheet that I enqueue for just this template
    .memberPost {
    float: left;
    width: 225px;
    margin: 10px;
}
.memberPost .fbConnect {
    width: 80px;
    float: left;
    overflow: hidden;
}
.memberPost .twitConnect {
    margin-right: -20px;
}
.memberPost h2 {
    text-align: center;
    margin-top: 5px;
}
.memberPost .memberThumb {
    height: 100px;
}
.memberPost .entry-content p {
    margin: 5px;
    height: 275px;
    text-align: left;
}
.memberPost .entry-utility {
    margin: 0 5px 10px 5px;
}
.memberPost .socialIcons {
    height: 28px;
    margin-bottom: 2px;
}


text:
Q: how to call a function on button click I want to create two buttons that perform separate functions.

When button_B1 is clicked, Function_B1() runs.
When button_B2 is clicked, Function_B2() runs.
How do I call a function on a button click?

A: When a Win32 button is clicked, it sends a BN_CLICKED notification to its parent window, where the message carries the button's HWND and ID.  In the parent window's wndproc, you can catch the notification and call whatever function you want for whichever button is sending the notification.
case WM_COMMAND:
{
    if ((HIWORD(wParam) == BN_CLICKED) && (lParam != 0))
    {
        switch (LOWORD(wParam))
        {
            case ID_BTN1:
                Function_B1();
                break;

            case ID_BTN2:
                Function_B2();
                break;
        }
    }

    break:
}

Or
case WM_COMMAND:
{
    if ((HIWORD(wParam) == BN_CLICKED) && (lParam != 0))
    {
        HWND hwndBtn = (HWND) lParam;

        if (hwndBtn == hwndBtn1)
            Function_B1();

        else if (hwndBtn == hwndBtn2)
            Function_B2();
    }

    break:
}

A: Thank you, Remy.
I just had a problem with the switch statement:
    case WM_COMMAND:
     {
        switch (wmId)
        {
        case 1:
            Function_B1(hWnd, wParam, lParam);
            break;

        case 2:
            Function_B2(hWnd, wParam, lParam);

            break;

        case 3:
            Function_B3(hWnd, wParam, lParam);
            break;


text:
Q: sftp_read jumps large blocks of bytes when reading from a file I'm trying to download a file over sftp and so far I've connected to a server via ssh session then opened an sftp session using the ssh session and everything seems fine. I have opened a file on the server and I'm using sftp_read() to get block of bytes from the file. My code is:
char buffer[16384] = {};
ssize_t nbytes;
ssize_t ntotal = 0;
for (;;) {
    nbytes = sftp_read(file, buffer, sizeof(buffer));

    if (nbytes == 0) {
        break; // EOF
    }

    localFile << buffer;
    ntotal += nbytes;
    //sftp_seek(file, ntotal);
}

But for some reason, when the blocks are being read, the first 20 bytes are correct but the 21st up till the 16384th byte are wrong. It turns out that after reading 20 bytes, the reader jumps to the 16384th byte of the file and continues reading like nothing happened.
I did some testing and if I changed the buffer to any size whether it was 16384, 21, 22, 50 etc, it still jumped to the 16384th byte after reading 20 bytes correctly.
Is there a reason for this? Is there a better library than libssh and sftp that I can use without errors?

A: I didn't need to use libssh after all. For anybody wanting another way of copying files over sftp, just use:
system("scp -i private_key user@server.com:directory_to_file/file.txt path_to_local_dir/file.txt");


text:
Q: C++, pass by reference variable not being update on the same line on which function is called In my c++ program, I have this function,
char MostFrequentCharacter(ifstream &ifs, int &numOccurances);
and in main(), is this code,
ifstream in("file.htm");
int maxOccurances = 0;
cout <<"Most freq char is "<<MostFrequentCharacter(in, maxOccurances)<<" : "<<maxOccurances;

But this is not working, though I am getting the correct char, the maxOccurance remains zero.
But if I replace the above code in main with this,
ifstream in("file.htm");
int maxOccurances = 0;
char maxFreq = MostFrequentCharacter(in, maxOccurances);
cout <<"Most freq char is "<<maxFreq<<" : "<<maxOccurances;

Then, it is working correctly. My question is why is it not working in first case.

A: In C++,
cout << a << b

By Associativity evaluates to:
(cout << a) << b

but the compiler is free to evaluate them in any order.
i.e, the compiler can evaluate b first, then a, then the first << operation and the the second << operation. This because there is no sequence point associated with <<

For the sake of simplicity let us consider the following code, which is equivalent:
 #include<iostream>
    int main()
    {
       int i = 0;
       std::cout<<i<<i++;
       return 0;
    }

In the above source code:
std::cout<<i<<i++;

evaluates to the function call:
operator<<(operator<<(std::cout,i),i++);

In this function call whether operator<<(std::cout,i) or i++ gets evaluated first is Unspecified. i.e:
operator<<(std::cout,i) maybe evaluated first Or
i++ maybe evaluated first Or
Some Magic Ordering implemented by the compiler
Given the above, that there is no way to define this ordering and hence no explanation is possible either.

Relevant Quote from the C++03 Standard:
Section 1.9

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine.

A: Because in the first case, the value of maxOccurances in the expression is being resolved before the call to MostFrequentCharacter.  It doesn't have to be that way though, it is unspecified behavior.
You may experience different results with different compilers, or compiler options.  If you try that same thing on VC++ for example, I believe you will see different results.

A: You just have to note that where you see << you are actually calling the operator<< method - so the compiler is working out the value of the arguments to pass into that function before your variable is modified.
In other words, what you have is similar to
operator<<(operator<<(cout, f(x)), x);

...and since the evaluation order of function arguments is undefined, it depends on the compiler.

A: Cout works right to left in your compiler so first rightmost is evaluated then left one. :)
So the value of referenced variable isn't changed.


text:
Q: How to write multiple data via looping to excel (Jxl) In my below code, I want to write multiple data to excel but it's writing only the first value and not the remaining.
I am trying to read from webpage and write it to a excel sheet. Below is set of code works fine, but i am not able to figure out how to run this in a loop. As i have to write many value which i am reading from the table
Could anybody sort this out.
String m1 = (driver.findElement(By.xpath(".//*[@id='dhfdshjfdsfdsf']")).getText());
   System.out.println(m1);
    WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
    writableSheet ws = wb.createSheet("customsheet",1);
    {
    Label label = new Label(0,0,m1);
    ws.addCell(label);
    }
    wb.write();
    wb.close();

A: I have edited your code to write for multiple values. Check once with below code.
WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
    writableSheet ws = wb.createSheet("customsheet",1);
    int rowsize = ws.getRows();
    int c=0;

    //if m1 contains 20 values then it upadtes till 20 rows
    for(int i=rowsize; i<rowsize+20; i++) {
        String m1 = (driver.findElement(By.xpath(".//*[@id='dhfdshjfdsfdsf']")).getText());
        System.out.println(m1);
        Label label = new Label(c,i,m1);
        ws.addCell(label);
    }
    wb.write();
    wb.close();


text:
Q: Calculating mean values along masking numpy array I have a 2d NumPy array:
# x, y, z, mask_id
data = np.array([[ 3.28246069,  3.63800144, -1.66515279,  0],
                 [ 3.28246069,  3.63800144, -1.66515279,  0],
                 [ 0.,  0., 0.,  1]])

This is the result what I expect:
# mean value of each mask id
array([[3.28246069,  3.63800144, -1.66515279], [0, 0, 0]])

I want to calculate mean value from same mask id. Is there any fast method?


text:
Q: sending SQL INSERT query as a parameter in POST request in FusionTable API I am accessing the fusiontable API using service account and want to send a POST request to insert values in a fusiontable.
I am getting the following error:
    400 Bad Request
     {
   "error": {
  "errors": [
  {
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
  "code": 400,
 "message": "Parse Error"
 }
 }

This is my code, Please let me know where i am going wrong.
            String PostUrl = "https://www.googleapis.com/fusiontables/v1/tables";
            HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);

            //generate the REST based URL
            GenericUrl url = new GenericUrl(PostUrl.replaceAll(" ", "%20"));
            //make POST request
            String requestBody = "sql=INSERT INTO 1DqxKZUct_VhfG3fZy6Lru1CamniDO8vv5qW6jO8 (Species) VALUES ('Red Shoes')";
            HttpRequest request = requestFactory.buildPostRequest(url, ByteArrayContent.fromString("application/json", requestBody));
            request.getHeaders().setContentType("application/json");
            request.getHeaders().set("sql", "INSERT INTO 1DqxKZUct_VhfG3fZy6Lru1CamniDO8vv5qW6jO8 (Species) VALUES ('Red Shoes')");
            System.out.println("HttpRequest request" + request);
            HttpResponse response = request.execute();
            String content = response.parseAsString();

A: You need to send the request to query end point of the Google API service and not the tables end point.
i.e change the PostUrl value as
        String PostUrl = "https://www.googleapis.com/fusiontables/v1/query";


text:
Q: Multi-level paging tables Referring to the image here:

From http://en.wikipedia.org/wiki/File:X86_Paging_4K.svg
Could somebody please explain something for me? I don't get exactly how this works. As I understand it the page "directory" contains an entity which essentially points to the beginning of the "page table". However, surely all of the entities in the page "directory" would contain the exact same value? Or, does this mean we have 1x page "directory" but N page "tables" (at the same level in the page multi-level hierarchy")?
If there are N page "tables" and one page "directory" I get why the PD would point to one of the N PTs. If there aren't then I am really confused.

A: N page tables.
If you look at the Wikipedia entry for Page Tables, you'll see two diagrams there; one for the two-level page table structure, and one for the three-level page table structure.  The purpose of the three-level page table structure is to implement PAE, which allows memory access beyond 4GB.

A: That diagram should be read as:

*

*The Page Directory (PD) is an array of Page Directory Entries (PDEs), pointed to by Control Register 3 (CR3).

*The leftmost 10 bits of the address are used as an index into the PD.  The PDE at that position points to one of many Page Tables (PTs), specifically the PT that maps pages for the desired address.

*The next 10 bits are used as an index into the PT.  The Page Table Entry (PTE) at that position points to one of many 4KB pages in memory, specifically the page that contains the desired address.

*The rightmost 12 bits are used as a byte-index into the page.

Thus the memory location is at CR3 -> [a & 0xffc00000] -> [a & 0x003ff000] -> [a & 0x00000fff]


text:
Q: Updating the UI thread works incorrectly in android I Want to update UI fields after some calculations. But it Runs wrong.
 SolvePuzzle sp = new SolvePuzzle(table);
 solved_puzzle = sp.Solve();

after calculating Solve() Function, its results that saved in solved_puzzle should be shown on app UI.
to set that values I  use set_values() function:
set_values(solved_puzzle);

on set_values() function I'll set UI Elements:
private void set_values(int[][] solved_puzzle1) {
    final int[][] solved_puzzle = solved_puzzle1;

    System.out.print(solved_puzzle1[0][0]);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            t1.setText(String.valueOf(solved_puzzle[0][0]));
        }
}

now System.out.print(solved_puzzle1[0][0]); outputs for example 1 but t1 value is 0.
Do you know what should I do?


text:
Q: longtable package: Stretch height of last row on page "RTL document" I took a look at this nice answer longtable package: Stretch height of last row on page and I need to apply this answer in my arabic document (right to left document).
The problem that I can not get the same output in RTL context (the table is not stretched)
\documentclass[12pt]{article}
\usepackage[showframe,margin=2cm]{geometry}
\usepackage{longtable}
\usepackage{fontspec}
\usepackage{bidi}
\setmainfont[Script=Arabic]{Amiri}

\makeatletter
\def\zz#1{%
\pdfsavepos\write\@auxout{%
\gdef\expandafter\string\csname zz@#1\endcsname{%
 \string\\[\the\dimexpr\the\pdflastypos sp -80pt\relax]}}%
\expandafter\ifx\csname zz@#1\endcsname\relax
\expandafter\\%
\else
\csname zz@#1\expandafter\endcsname
\fi}
\makeatother

\begin{document}

%\setRTL

\begin{longtable}{|p{5cm}|}
\hline
a  \zz{c} \hline
\end{longtable}

\end{document}

RTL context

LTR context

A: Interesting, seems you need to put \pdfsavepos after the \write not before it (in input file order)
\documentclass[12pt]{article}
\usepackage[showframe,margin=2cm]{geometry}
\usepackage{longtable}
\usepackage{fontspec}
\usepackage{bidi}
\setmainfont[Script=Arabic]{FreeSerif}

\makeatletter
\def\zz#1{%
\write\@auxout{%
\gdef\expandafter\string\csname zz@#1\endcsname{%
 \string\\[\the\dimexpr\the\pdflastypos sp -80pt\relax]}}\pdfsavepos%
\expandafter\ifx\csname zz@#1\endcsname\relax
\expandafter\\%
\else
\csname zz@#1\expandafter\endcsname
\fi}
\makeatother

\begin{document}

\setRTL

\begin{longtable}{|p{5cm}|}
\hline
a  \zz{c} \hline
\end{longtable}

\end{document}


text:
Q: Google Docs Sharing Container Bound Script i have a simple google doc running a basic script enabling a sidebar containing a playable mp3.
My goal is to be able to share this document with any anonymous user
and have them view the document and script the same way i do.
what steps can i take to make this happen? if i cant use a container bound scrip, how do i make a stand alone sidebar script? and if none of those are possible, is there another option for including audio in a document without having to open it in another tab?
i am extremely amateur at scripts, plz forgive me
and thanks for any info you can share!
example: https://i.stack.imgur.com/SJH63.png


text:
Q: python regex: search for variable content inside javascript function I have a javascript string like given below
function() {window.__WML_REDUX_INITIAL_STATE__ = {"uuid":null,"isMobile":false,"isBot":false,"isAdsEnabled":true};}

I have to get contents of __WML_REDUX_INITIAL_STAET__ = whose content is json data so that I could parse the json further.
I'm, using following regex pattern
wml_redux_initial_state = re.findall('__WML_REDUX_INITIAL_STATE__ = (.*?);\s*$', redux, re.M)

But this is not working.

A: I don't know how specific your regex needs to be, but your current one isn't working because of the } after the ;....this works:
re.search(r'__WML_REDUX_INITIAL_STATE__ = (.*?);}\s*$', redux, re.M)


text:
Q: Django 1.2 : Multiple database and Generic Content Types I am working on one project with django 1.2.
I have 2 databases :
- First, for users, user's profile, session ...
- Second is to store data from my specifics models like post of blog, pictures, files ...
I made a router (dbrouter.py) to manage where each models are stored (instead of using 'using' for each queryset). When I sync my project there is no problem.
So, I need content types framework in first and second databases. Now, how do I do to declare contenttypes app on my two databases and how I will be sure that data of contenttypes are synchronized on my two databases ?
The only workaround I found, was :

*

*Declare contenttypes framework two times in settings.py.

*Manage with dbrouter this two contenttypes for each databases

*When I sync project, only table django_content_type from my first database is updated with data.

*Manually I copy data from first database (table django_content_type) to the second.

Finally, can you tell me what are the best practices when you want to manage content types on multiple databases ?

A: I think the "best practice" here would be to not use two different databases in the way you are doing. I can't think of any truly useful reason to separate out users/profiles/sessions from the rest of the data for your application.


text:
Q: Problems with strings and fstream I'm currently working on a project where I need to implement several classes to simulate a cafeteria. Each "student" who is waiting on line to get their food has 5 variables which describe them, that is: name, group, entree type, snack/dessert type, and a number representing the amount of salad they plan on buying in ounces. The idea is that all this information will be read in using fstream from a text file (with the outline following a specific order and repeating for each student). Once each student is read in, I push the student onto a queue to simulate them waiting their turn in line.
My issue is two things, first, when reading in each line using the getline() function, I attempt to store this line in a temporary variable for the purpose of plugging it into the constructor for the student class and then pushing that copy into the queue. This doesn't seem to be allowed because when I try to store the information it says "no operator '=' matches these operands."
The other issue I have is with reading in the ounces of salad value, this is an integer value, I have searched but I haven't found any way to directly read in a numerical value and pass it off to an integer variable. Sorry for the long explanation but I wanted to make sure I was clear, any help is appreciated.
Here is a portion of the code where I attempt to do this:
string temp_name;
string temp_group;
string temp_entree;
string temp_snack;
int temp_salad;

string line2;
queue<student> line;
ifstream myfile ("students.txt");
if(myfile.is_open())
    while(myfile.good())
    {
        temp_name= getline(myfile, line2);
        temp_group= getline(myfile, line2);
        temp_salad= getline(myfile, line2);
        temp_entree= getline(myfile, line2);
        temp_snack= getline(myfile, line2);

student s(temp_name, temp_group, temp_entree, temp_snack, temp_salad);
    //.....
    }

A: getline doesn't return the string, so you shouldn't be trying to assign the return value to a string.
do:
getline(myfile, temp_name);

instead of
temp_name = getline(myfile, line2);

To read the next integer in the file use the stream input operators:
int temp_salad;
myfile >> temp_salad;
if (myfile.fail())
    std::cerr << "we failed to read temp_salad ounces\n";

A: getline() returns istream&, which is just the first argument after having the line extracted from it. It reads the line into the second argument (line2 in your example). So, it should look something like this:
getline(myfile, name);
getline(myfile, group);
// ...

Also, getline reads into strings, so you need to convert that string to an integer before you store it in temp_salad. There are several ways to do this, the easiest of which is
getline(myfile, temp);
salad = atoi(temp.c_str());

Just make sure to #include <cstdlib> in that file.

A: You can use operator>> to read an integer from input and put it into a variable, as in: myfile >> my_int;.
Since you've apparently defined student as a class, I'd overload operator>> for that class to read in all the data for a student:
std::istream &operator>>(std::istream &is, student &s) {
    std::getline(is, s.name);
    std::getline(is, s.group);
    std::getline(is, s.entree);
    std::getline(is, s.snack);
    std::string temp;
    std::getline(is, temp);
    s.salad = lexical_cast<int>(temp);
    return is;
}

Then we can read in student objects using that operator -- either directly in a loop rather like you had above, or rather indirectly, such as via an istream_iterator instantiated over that type, such as:
std::deque<student> line((std::istream_iterator<student>(infile)),
                          std::istream_iterator<student>());

Note that in this case I've used a deque instead of an actual queue -- in C++, queue is defined as an iterator adapter, and is sort of a second-class citizen in general. std::deque is often (including this case) simpler, even if you don't need the double-ended part of its definition.


text:
Q: Condense elements in table with Bootstrap Id like to condense the input and have a nowrap on the table column to condense it more.  I am not sure how to approach this best with Boostrap 4.4.1.

                                <input data-bind="value: row.timeIncrements, " id="TimeIncrements" maxlength="3" name="TimeIncrements" placeholder="60" type="text" value="">

                                    min

                                <button type="button" title="More information" class="btn btn-info" data-bind="help: { url: '/directors/dashboard/help?viewName=~%2FAreas%2FDirectors%2FViews%2FEventGridSchedule%2FTimeIncrementsHelp.cshtml&sportId=1', title: 'Time Increments' }"></button>


text:
Q: How to emulate a Timeout property? I have a call to a remote Datasnap REST method where the server sometimes doesn't respond and I need to detect it and terminate the application instead of leaving it frozen.
I use a DSRestConnection, and a Datasnap REST Client Module where all the remote methods are defined, attached to the DSRestConnection. I can't find a Timeout property on them, AFAIK I can only set Timeouts on the Datasnap Server, but sometimes the client loses connection to the server, so I also need to raise a Timeout on the client.
How can I emulate a Timeout when I don't have one ?. Is there a class to help do that or do I need to code it from the ground up ?. in this case, the way to go is to do the remote call on a secondary threat, so the main thread is still responsive and use something like a Timer to check if the call has succeeded in time ?.
I would appreciate any suggestion. Thank you.

A: The TDSRestConnection should give you access to the underlying TDSHTTP client via its HTTP property. The TDSHTTP client exposes a ConnectTimeout and a ReadTimeout property. Perhaps the latter one is what you are looking for.


text:
Q: Re-use Animations in VisualStates What I want to do (in pseudo);
<!-- As a resource -->
<Storyboard x:Key="RepetitiveAnimation">
   <DoubleAnimation .../>
</Storyboard>

<!-- In the templates -->
<VisualStateManager>
   <VisualState x:Name="blah" Storyboard="{StaticResource RepetitiveAnimation}"/>
</VisualStateManager>

or even like;
<VisualStateManager>
   <VisualState x:Name="blah">
      <BeginStoryboard Storyboard="{StaticResource RepetitiveAnimation}"/>
   </VisualState>
</VisualStateManager>

What doesnt work; See above.
You can do this in WPF, but in SL there's no joy. Is there an equivalent I'm missing?
Cheers!

A: I tried reusing Storyboards in my VisualStates as well, but to no avail.
But there is a thing you can do that may mitigate the problem:
Define your own AttachedProperties (attachable to instances of VisualState) for frequently used Storyboard tasks, for example:

*

*setting Visibility on named Elements

*applying Opacity values to named Elements

*even setting Focus via a Storyboard.

The xaml would look like this:
<VisualStateGroup x:Name="TravelPlanningSteps">
    <VisualState x:Name="DateSelection"
        utils:VisualStateUtils.VisibleElements="DateSelector"
        utils:VisualStateUtils.FocusedElement="DateSelector"/>
    <VisualState x:Name="HotelSelection"
        utils:VisualStateUtils.VisibleElements="HotelSelector, BreakfastSelector"
        utils:VisualStateUtils.FocusedElement="HotelSelector"/>
</VisualStateGroup>

And the code (sorry, it's a bit lengthy):
public static class VisualStateUtils
{
    #region FocusedElement

    public static string GetFocusedElement( VisualState obj )
    {
        return (string) obj.GetValue( FocusedElementProperty );
    }

    public static void SetFocusedElement( VisualState obj, string value )
    {
        obj.SetValue( FocusedElementProperty, value );
    }

    public static readonly DependencyProperty FocusedElementProperty =
        DependencyProperty.RegisterAttached( "FocusedElement", typeof( string ), typeof( VisualStateUtils ), new PropertyMetadata( HandleFocusedElementChanged ) );

    private static void HandleFocusedElementChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        var state = d as VisualState;
        if (state == null) return;

        string elementName = e.NewValue as string;
        if (elementName == null) return;

        var storyBoard = state.Storyboard;
        if (storyBoard == null)
        {
            storyBoard = new Storyboard();
            state.Storyboard = storyBoard;
        }

        ClearAutoDefinedFocusClaim( storyBoard );

        var ani = new ObjectAnimationUsingKeyFrames();
        Storyboard.SetTargetName( ani, elementName );
        Storyboard.SetTargetProperty( ani, new PropertyPath( VisualStateUtils.FocusClaimProperty ) );
        VisualStateUtils.SetIsAutoDefinedFocusClaim( ani, true );
        ani.KeyFrames.Add( new DiscreteObjectKeyFrame { Value = true, KeyTime = KeyTime.FromTimeSpan( TimeSpan.FromMilliseconds( 0 ) ) } );
        storyBoard.Children.Add( ani );
    }

    public static bool GetFocusClaim( Control focusTarget )
    {
        return (bool) focusTarget.GetValue( FocusClaimProperty );
    }

    public static void SetFocusClaim( Control focusTarget, bool value )
    {
        focusTarget.SetValue( FocusClaimProperty, value );
    }

    public static readonly DependencyProperty FocusClaimProperty =
        DependencyProperty.RegisterAttached( "FocusClaim", typeof( bool ), typeof( VisualStateUtils ), new PropertyMetadata( false, HandleFocusClaimChanged ) );

    private static void HandleFocusClaimChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var focusTarget = d as Control;
        if(focusTarget==null) return;

        var shouldReceiveFocusNow = (bool) e.NewValue;

        if (shouldReceiveFocusNow)
        {
            if (!focusTarget.Focus()) CheckFocusability( focusTarget );
        }
    }

    private static void CheckFocusability(Control focusTarget)
    {
        //so the focus() call was not successful, what's the problem? lets see...
        //the control may still be collapsed
        //(and another animation will turn it visible anytime soon, remember: we are part of ongoing VisualState switching)
        if (!focusTarget.IsLoaded())
            focusTarget.Loaded += HandleFocusTargetLoaded;

        //it may be disabled (and another animation will enable it)
        else if (!focusTarget.IsEnabled)
            focusTarget.IsEnabledChanged += HandleFocusTargetEnabled;
    }

    private static void HandleFocusTargetLoaded( object sender, RoutedEventArgs routedEventArgs )
    {
        var focusTarget = (Control) sender;
        focusTarget.Loaded -= HandleFocusTargetLoaded;
        focusTarget.Focus();
    }

    private static void HandleFocusTargetEnabled(object sender, DependencyPropertyChangedEventArgs e)
    {
        var focusTarget = (Control) sender;
        focusTarget.IsEnabledChanged -= HandleFocusTargetEnabled;
        focusTarget.Focus();
    }

    public static bool GetIsAutoDefinedFocusClaim( DependencyObject obj )
    {
        return (bool) obj.GetValue( IsAutoDefinedFocusClaimProperty );
    }

    public static void SetIsAutoDefinedFocusClaim( DependencyObject obj, bool value )
    {
        obj.SetValue( IsAutoDefinedFocusClaimProperty, value );
    }

    public static readonly DependencyProperty IsAutoDefinedFocusClaimProperty =
        DependencyProperty.RegisterAttached( "IsAutoDefinedFocusClaim", typeof( bool ), typeof( VisualStateUtils ), new PropertyMetadata( false ) );

    private static void ClearAutoDefinedFocusClaim( Storyboard storyBoard )
    {
        var toDelete = storyBoard.Children.Where( VisualStateUtils.GetIsAutoDefinedFocusClaim ).ToList();
        toDelete.ForEach( animation => storyBoard.Children.Remove( animation ) );
    }

    #endregion

    #region CollapsedElements

    public static readonly DependencyProperty IsAutoCreatedCollapsedElementProperty =
        DependencyProperty.RegisterAttached( "IsAutoCreatedCollapsedElement", typeof( bool ), typeof( VisualStateUtils ), new PropertyMetadata( default( bool ) ) );

    private static void SetIsAutoCreatedCollapsedElement( DependencyObject element, bool value )
    {
        element.SetValue( IsAutoCreatedCollapsedElementProperty, value );
    }

    private static bool GetIsAutoCreatedCollapsedElement( DependencyObject element )
    {
        return (bool) element.GetValue( IsAutoCreatedCollapsedElementProperty );
    }

    public static readonly DependencyProperty CollapsedElementsProperty =
        DependencyProperty.RegisterAttached( "CollapsedElements", typeof( string ), typeof( VisualStateUtils ), new PropertyMetadata( default( string ), HandleCollapsedElementsChanged ) );

    private static void HandleCollapsedElementsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var state = d as VisualState;
        if (state == null) return;

        string elementNames = e.NewValue as string;
        if (elementNames == null) return;

        CreateAutoDefinedAnimationsForVisibility( Visibility.Collapsed, state, elementNames );
    }

    public static void SetCollapsedElements( VisualState state, string value )
    {
        state.SetValue( CollapsedElementsProperty, value );
    }

    public static string GetCollapsedElements( VisualState state )
    {
        return (string) state.GetValue( CollapsedElementsProperty );
    }

    #endregion

    #region VisibleElements

    public static readonly DependencyProperty VisibleElementsProperty =
        DependencyProperty.RegisterAttached( "VisibleElements", typeof( string ), typeof( VisualStateUtils ), new PropertyMetadata( default( string ), HandleVisibleElementsChanged ) );

    private static void HandleVisibleElementsChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        var state = d as VisualState;
        if (state == null) return;

        string elementNames = e.NewValue as string;
        if (elementNames == null) return;

        CreateAutoDefinedAnimationsForVisibility( Visibility.Visible, state, elementNames );
    }

    public static void SetVisibleElements( VisualState state, string value )
    {
        state.SetValue( VisibleElementsProperty, value );
    }

    public static string GetVisibleElements( VisualState state )
    {
        return (string) state.GetValue( VisibleElementsProperty );
    }

    public static readonly DependencyProperty IsAutoCreatedVisibleElementProperty =
        DependencyProperty.RegisterAttached( "IsAutoCreatedVisibleElement", typeof( bool ), typeof( VisualStateUtils ), new PropertyMetadata( default( bool ) ) );

    private static void SetIsAutoCreatedVisibleElement( DependencyObject element, bool value )
    {
        element.SetValue( IsAutoCreatedVisibleElementProperty, value );
    }

    private static bool GetIsAutoCreatedVisibleElement( DependencyObject element )
    {
        return (bool) element.GetValue( IsAutoCreatedVisibleElementProperty );
    }

    #endregion

    private static void CreateAutoDefinedAnimationsForVisibility( Visibility visibility, VisualState state, string elementNames )
    {
        var storyBoard = state.Storyboard;
        if (storyBoard == null)
        {
            storyBoard = new Storyboard();
            state.Storyboard = storyBoard;
        }

        ClearAutoDefinedElementAnimations( visibility, storyBoard );

        string[] namesOfManipulatedElements = (elementNames ?? string.Empty).Split( ',' );
        namesOfManipulatedElements = namesOfManipulatedElements.Select( name => name.Trim() ).ToArray();
        foreach (var elementName in namesOfManipulatedElements)
        {
            var ani = new ObjectAnimationUsingKeyFrames();
            Storyboard.SetTargetName( ani, elementName );
            Storyboard.SetTargetProperty( ani, new PropertyPath( "Visibility" ) );
            MarkAutoDefinedElementAnimation( visibility, ani );
            ani.KeyFrames.Add( new DiscreteObjectKeyFrame { Value = visibility, KeyTime = KeyTime.FromTimeSpan( TimeSpan.FromMilliseconds( 0 ) ) } );
            storyBoard.Children.Add( ani );
        }
    }

    private static void ClearAutoDefinedElementAnimations( Visibility visibility, Storyboard storyBoard )
    {
        if (visibility == Visibility.Visible)
        {
            var toDelete = storyBoard.Children.Where( VisualStateUtils.GetIsAutoCreatedVisibleElement ).ToList();
            toDelete.ForEach( ani => storyBoard.Children.Remove( ani ) );
        }
        else
        {
            var toDelete = storyBoard.Children.Where( VisualStateUtils.GetIsAutoCreatedCollapsedElement ).ToList();
            toDelete.ForEach( ani => storyBoard.Children.Remove( ani ) );
        }
    }

    private static void MarkAutoDefinedElementAnimation( Visibility visibility, ObjectAnimationUsingKeyFrames animation )
    {
        if (visibility == Visibility.Visible)
            VisualStateUtils.SetIsAutoCreatedVisibleElement( animation, true );
        else
            VisualStateUtils.SetIsAutoCreatedCollapsedElement( animation, true );
    }
}

And not to forget the handy Extension to check whether a control is loaded or not:
public static class ControlExtensions
{
    public static bool IsLoaded(this FrameworkElement element)
    {
        return element.GetVisualChildren().Any();
        //or just check the parent ...not sure what's better
        //return System.Windows.Media.VisualTreeHelper.GetParent(element) != null;
    }
}


text:
Q: Update li attribute based on HTML5 and JS drag and drop I have implemented HTML5 drag and drop functionality alongside JS for my one of projects. The issue that I'm currently facing is the following:
I need to update data-iterator when using drag and drop sorting of my LI elements. In other words, when I want to move Test 3 to the first position, data iterator should change from 3 to 0. I think you get the idea.
HTML

Test

Test 1

Test 2

Test 3

JS
    function sortable(rootEl, onUpdate) {
   var dragEl;

   // Making all siblings movable
   [].slice.call(rootEl.children).forEach(function (itemEl) {
       itemEl.draggable = true;
   });

   // Function responsible for sorting
   function _onDragOver(evt) {
       evt.preventDefault();
       evt.dataTransfer.dropEffect = 'move';

       var target = evt.target;
       if (target && target !== dragEl && target.nodeName == 'LI') {
           // Sorting
           rootEl.insertBefore(dragEl, target.nextSibling || target);
       }
   }

   // End of sorting
   function _onDragEnd(evt){
       evt.preventDefault();

       dragEl.classList.remove('ghost');
       rootEl.removeEventListener('dragover', _onDragOver, false);
       rootEl.removeEventListener('dragend', _onDragEnd, false);

       // Notification about the end of sorting
       onUpdate(dragEl);
   }

   // Sorting starts
   rootEl.addEventListener('dragstart', function (evt){
       dragEl = evt.target; // Remembering an element that will be moved

       // Limiting the movement type
       evt.dataTransfer.effectAllowed = 'move';
       evt.dataTransfer.setData('Text', dragEl.textContent);

       // Subscribing to the events at dnd
       rootEl.addEventListener('dragover', _onDragOver, false);
       rootEl.addEventListener('dragend', _onDragEnd, false);

       setTimeout(function () {
           // If this action is performed without setTimeout, then
           // the moved object will be of this class.
           dragEl.classList.add('ghost');
       }, 0)
   }, false);
}

// Using
sortable(document.getElementById('_slides_slideshow_repeat'), function (item) {
   console.log(item);
});

I'm not sure which JS line code I should modify, so any help would be highly appreciated.

A: You can modify your_onDragEnd function so that it updated the data-iterator attribute after every order change

    // End of sorting
    function _onDragEnd(evt){
        var iterator = 0;
        var items = rootEl.getElementsByTagName('li');

        evt.preventDefault();

        dragEl.classList.remove('ghost');
        rootEl.removeEventListener('dragover', _onDragOver, false);
        rootEl.removeEventListener('dragend', _onDragEnd, false);

        // Notification about the end of sorting

        for (var i = 0; i < items.length; i++) {
            items[i].setAttribute('data-iterator', i)
        }

        onUpdate(dragEl);
    }


text:
Q: Customizing build tool for unsupported languages I'm trying to adopt a new build tool, for a language that isn't supported by any build tool (that I've Googled). I don't really need fancy features from the build tool.
I've tried using Gradle, but couldn't find examples/tutorials on writing plugins to support new languages.
Can any one recommend a build tool, that easily supports adding new languages, and has good documentation or examples of how to do it?


text:
Q: is it ok to use one connectionstring to multiple queries how to optimize this codes, I optimize  my execution error by buying a server ram but I want my codes to be optimize to.... and can I reuse my connection?
i have a public sub sqlconnect() which has the codes for my connection
sqlcon = new sqlconnection(cstring);

can I use sqlconnect to process all the queries below without calling it again? or should I use sqlconnect then just use sqlcon.close()?
you can see below that I use too many sqlconenction...
Public Class Tracking
    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
        Try
            Dim airbill, branchcode, t_sender, receiver, setpackagetype, getpackagetype, setdestination, getdestination, Setbranchid, getbranchid, settrackstats, dateuploaded As String
            sqlconnect()
            sqltable = New DataTable
            sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM AIRBILLS WHERE  AirbillNo='" & txttrackor.Text & "' and TrackingNo = '" & txttrackcode.Text & "'", sqlcon)
            sqladapter.Fill(sqltable)
            settrackstats = sqltable.Rows(0)("TrackingstatusID")
            airbill = sqltable.Rows(0)("AirbillNo")
            branchcode = sqltable.Rows(0)("TrackingNo")
            t_sender = sqltable.Rows(0)("Sender")
            receiver = sqltable.Rows(0)("Addressee")
            setpackagetype = sqltable.Rows(0)("ServiceID")
            Setbranchid = sqltable.Rows(0)("BranchID")
            dateuploaded = sqltable.Rows(0)("DateUploaded")
            Label17.Text = dateuploaded
            'get destination
            If IsDBNull(sqltable.Rows(0)("destinationID")) Then
                getdestination = ""
                Label13.Text = getdestination
            Else
                setdestination = sqltable.Rows(0)("destinationID")
                sqlconnect()
                sqltable = New DataTable
                sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM DESTINATION where ID = '" & setdestination & "'", sqlcon)
                sqladapter.Fill(sqltable)
                getdestination = sqltable.Rows(0)("DestinationName")
                Label13.Text = getdestination
                sqlcon.Close()
            End If
            sqlcon.Close()
            'get trackignstatus
            ListBox1.Items.Clear()

            For Each track As DataRow In sqltable.Rows
                sqltable = New DataTable
                sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM TRACKINGSTATUS WHERE  ID = '" & settrackstats & "'", sqlcon)
                sqladapter.Fill(sqltable)
                ListBox1.Items.Add(sqltable.Rows(0)("TrackingStatus"))
            Next

            'get the service name of the tracking
            sqlconnect()
            sqltable = New DataTable
            sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM SERVICE where ID = '" & setpackagetype & "'", sqlcon)
            sqladapter.Fill(sqltable)
            getpackagetype = sqltable.Rows(0)("ServiceName")
            sqlcon.Close()

            'get the tracking
            'get branch Name
            sqlconnect()
            sqltable = New DataTable
            sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM BRANCHES where ID = '" & Setbranchid & "'", sqlcon)
            sqladapter.Fill(sqltable)
            getbranchid = sqltable.Rows(0)("BranchName")
            Label15.Text = getbranchid & " Branch"
            sqlcon.Close()

            'get tracking status
            sqlconnect()
            sqltable = New DataTable
            sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM TRACKING WHERE  TrackingID='" & txttrackor.Text & "' and TrackingCode = '" & txttrackcode.Text & "'", sqlcon)
            sqladapter.Fill(sqltable)

            For Each tracks As DataRow In sqltable.Rows
                Me.Update()
                settrackstats = tracks.Item("StatusID")
                sqltable = New DataTable
                sqladapter = New SqlClient.SqlDataAdapter("SELECT * FROM TRACKINGSTATUS WHERE  ID = '" & settrackstats & "'", sqlcon)
                sqladapter.Fill(sqltable)
                ListBox1.Items.Add(sqltable.Rows(0)("TrackingStatus"))
            Next

            Label8.Text = airbill
            Label9.Text = branchcode
            Label10.Text = t_sender
            Label11.Text = receiver
            Label12.Text = getpackagetype
        Catch ex As Exception
            MsgBox(ex.Message)
            'MsgBox(ex.Message)
            Label8.Text = ""
            Label9.Text = ""
            Label10.Text = ""
            Label11.Text = ""
            Label12.Text = ""
            Label13.Text = ""
            Label15.Text = ""
            ListBox1.Items.Clear()
        End Try
    End Sub
End Class

A: Connection pool at rescue:
They are no performance issues opening and closing connections dinamically, because a connection pool is handling connection objects. Nice explained on docs:

A connection pool is created for each unique connection string. When a pool is created, multiple connection objects are created and added to the pool so that the minimum pool size requirement is satisfied. Connections are added to the pool as needed, up to the maximum pool size specified (100 is the default). Connections are released back into the pool when they are closed or disposed.

Single connection:
If I have not convinced you and you use a single connection for all operations ( in a kind of singleton class that returns de connection ), may be you should to enable Multiple Active Result Sets (MARS):

Multiple Active Result Sets (MARS) is a feature that allows the execution of multiple batches on a single connection. In previous versions, only one batch could be executed at a time against a single connection. Executing multiple batches with MARS does not imply simultaneous execution of operations.

Set it on as a parameter on string connection.
Notice: may be you should to enable MARS anyway, an example is you launch new queries, over same connection, on every iteration of another query.