text:
Q: ngClass funcion + expresion Angular2+ estoy intentado combinar en un ngClass una expresion + una función sin embargo la expresión no se esta evaluando y no se ejecuta la clase, actualmente lo tengo así, es solo un ejemplo:
<div [ngClass]="[cargar(), {'hola':true}]"></div>

cargar() {
    return 'hola2';
  }

por lo que solo me esta aplicando la clase que trae cargar(), y hola no se esta aplicando aun sabiendo que la evaluo como verdad
aqui el ejemplo
https://stackblitz.com/edit/angular-t35zo1

A: Por lo que veo en la documentación oficial de angular, en el atributo ngClass, solo se pueden colocar expresiones. puedes colocar string, arreglos u objetos. por tanto una función no es bien recibida.
No veo que permita combinar ambas maneras como lo haces, he intentado ejecutarlo y no lo permite, debes realizarlo de una u otra forma.
te dejo el link de la documentación oficial de angular https://angular.io/api/common/NgClass
Si lo que deseas es que se aplique una clase u otra según te parezca, una de las formas podría ser de la siguiente manera:
Tengo en mi css el las siguientes clases:
export class AttrNgClass implements OnInit {

  public changeBackground: boolean;

  constructor() { }

  public ngOnInit(): void {
    this.changeBackground = false;
   }

  public backGround(): void {
    this.changeBackground = !this.changeBackground;
  }

  backGround2() {
    return 'bg-dark-gray';
  }
}

.text-blue {
    color: blue;
}

.bg-aqua {
    background-color: aqua !important;
}

.bg-dark-gray {
    background-color: darkgray;
}

<div (click)="backGround()"
    [ngClass]="{'text-blue': true, 'bg-aqua': !changeBackground, 'bg-dark-gray': changeBackground}">
    Prueba de cambio de color
</div>

<div [ngClass]="[backGround2()]">
    otra prueba
</div>


text:
Q: Can't access 2nd Form from TabPanel - ExtJs I create a window and then add a tabpanel. Within that tab panel I added form,grid,grid,grid and form.
When I try to get the 2nd form always it gives me the first one.
What would be the problem?
I'm very very new to ExtJs and this is the way I did it.
win = desktop.createWindow({
items : {
     xtype : 'tabpanel',
     ....
     items : [
           {
           xtype : 'form',
           id:'form1',
           ....
           },
           Grid1,
           Grid2,
           Grid3,
           {
            xtype : 'form',
            id:'form2',
            .....
           }
      ]
   }
});

var form_a = Ext.getCmp('form1').getForm(); //returns form1
var form_b = Ext.getCmp('form2').getForm(); //returns form1

.....
win.show();

This works well without 'form2' and it shows the 'form2' tab, but I cant access it.
Is there a problem or do I violate some extJs rules?
Thank You!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute multiple sqoop commands from a file I have multiple sqoop commands, and I want to execute them sequentially. How can I do this.
Currently, --options-file allows us to execute one command at a time.

A: Use shell script. Write commands one by one and execute the script.It will definitely work.
    #!/bin/bash

echo "*************SQOOP IMPORT JOB UTILITY*******************"

# First Sqoop command
echo
sqoop import --connect jdbc:db2://localhost:<PORT_NUMBER>/<DB> --table TABLE_NAME_1  --username user -password pass -m 1 2> log1.txt

# Second Sqoop command
echo
sqoop import --connect jdbc:db2://localhost:<PORT_NUMBER>/<DB> --table TABLE_NAME_2  --username user -password pass -m 1 2> log2.txt

echo "Check log file for sqoop jobs status"

Run shell script
./myscript.sh

A: I am not sure if that is possible only with Sqoop but for my case i have used Oozie to execute multiple Sqoop commands.


text:
Q: How to use the result of guardian-ffmpeg-Android? I am trying to build ffmpeg on Android. There are many tutorials. Some are very old.
So I want to try one that can use newer version of ffmpeg and Android NDK.
After long time searching, I find one, guardianproject / android-ffmpeg
The project was updated several months ago.
NDK r8 is used. ffmpeg is put from online, so a latest version.
After I follow all the instruction, I am confused which result I should use, and how to use it.
The README mentions testing, like:
# embedding metadata into a matroska video /data/local/ffmpeg -y -i test.mp4 \
    -attach attach.txt -metadata:s:2 mimetype=text/plain \
    -acodec copy -vcodec copy testattach.mkv

First, I fail to find the path: /data/local
Second, this is a command. How will I use it in Android?
Totall confused.
Any light?

A: I presume that you have successfully built the ffmpeg executable and understand the difference between static and shared libs in the build. If not you should read up on that before trying to exec it on the CLI in android.
I think that the author uses ffmpeg on the cli using either system.exec or processbuilder techniques to run and executable located on the phone in ./data/local/$yourSubDir....
see here for discussion on ffmpeg on cli in android and note that alot of people prefer to use the full JNI route employing java interfaces to wrap calls to ffmpeg.main(). IMO the JNI route is more robust for apps you intend to distribute. But it works on the cli.
the tests that confused you are just expressions for using ffmpeg that would need to be called in android using the approach you prefer ( system.exec or processbuilder ). You can get familiar with the cli testing by simply running ffmpeg in windows/ linux in your dev environment. Get a shell there and play with samples mentioned in the ffmpeg faqs.
you can look at the halfninja project on git for more examples on JNI approach.


text:
Q: python: recurcive list processing changes original list What I'm trying to do is recursively process a list. I'm new to python so when all the code was written and sent to be executed I faced a strange problem: the list returns changed after calling the recursive function. To test this I wrote that:
def recur(n):
    n.append(len(n))
    print '>',n
    if n[-1]<5: recur(n)
    print '<',n

And called the function:
recur([])

Here was the result:
> [0]
> [0, 1]
> [0, 1, 2]
> [0, 1, 2, 3]
> [0, 1, 2, 3, 4]
> [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]

What I expected to see was
> [0]
> [0, 1]
> [0, 1, 2]
> [0, 1, 2, 3]
> [0, 1, 2, 3, 4]
> [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4]
< [0, 1, 2, 3]
< [0, 1, 2]
< [0, 1]
< [0]

, as it is for simple integer variables:
def recur(n):
    n=n+1
    print '>',n
    if n<5: recur(n)
    print '<',n

recur(0)
> 1
> 2
> 3
> 4
> 5
< 5
< 4
< 3
< 2
< 1

How can I fix the situation and what have I understood wrong?

A: All the recursive invocations of your function operate on the same list. You need to make a copy:
def recur(n):
    n.append(len(n))
    print '>',n
    if n[-1]<5: recur(n[:])  # <<<< Note the [:]
    print '<',n

There are some good explanations in the answers to How do I pass a variable by reference?

A: As the other answers indicated, you are mutating the list in place. You could make copies of the list and/or use an immutable data structure, like a tuple:
def recur(n=()):
    if len(n) > 4:
         return n
    return recur(n + (len(n),))


text:
Q: Issue with .toISOString() function Consider the following code HTML + JavaScript:
<!DOCTYPE html>

Click the button to display a date after changing the hours, minutes, and seconds.

<button onclick="myFunction()">Try it</button>

Output:
Thu Apr 18 2013 00:00:00 GMT+0530 (India Standard Time)
ISO Date 2013-04-17T18:30:00.000Z

Could anyone help on understanding this difference in Date & Time

A: 2013-18-04 00:00:00 GMT+0530
2013-17-04 18:30:00 GMT+0000

These are the two timestamps. The first one has a time zone, the second one is GMT (no time zone adjustment). If you take the second timestamp and add 05:30:00 to 18:30:00 you get midnight of the following day. That matches the first timestamp.

A: var d = new Date();
d.setHours(-12, d.getTimezoneOffset(), 0, 0); //removing the timezone offset and 12 hours
console.log(d.toISOString()); //2013-04-17T00:00:00.000Z

I don't know, why would you need a ISO date a day earlier, but in case it is a typo:
var d = new Date();
d.setHours(0, -d.getTimezoneOffset(), 0, 0); //removing the timezone offset.
console.log(d.toISOString()); //2013-04-18T00:00:00.000Z

A: Also you can remove timezone like this:
let birthday = new Date(this.profile.birthday + ' UTC').toISOString();


text:
Q: Creating a symmetric matrix in R I have a matrix in R that is supposed to be symmetric, however, due to machine precision the matrix is never symmetric (the values differ by around 10^-16).  Since I know the matrix is symmetric I have been doing this so far to get around the problem:
s.diag = diag(s)
s[lower.tri(s,diag=T)] = 0
s = s + t(s) + diag(s.diag,S)

Is there a better one line command for this?

A:  s<-matrix(1:25,5)
 pmean <- function(x,y) (x+y)/2
 s[] <- pmean(s, matrix(s, nrow(s), byrow=TRUE))
 s
#-------
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    4    7   10   13
[2,]    4    7   10   13   16
[3,]    7   10   13   16   19
[4,]   10   13   16   19   22
[5,]   13   16   19   22   25

A: s<-matrix(1:25,5)
s[lower.tri(s)] = t(s)[lower.tri(s)]

A: I was curious to compare all the methods, so ran a quick microbenchmark. Clearly, the simplest 0.5 * (S + t(S)) is the fastest.
The specific function Matrix::forceSymmetric() is sometimes slightly faster, but it returns an object of a different class (dsyMatrix instead of matrix), and converting back to matrix takes a lot of time (although one might argue that it is a good idea to keep the output as dsyMatrix for further gains in computation).
S <-matrix(1:50^2,50)
pick_lower <- function(M) M[lower.tri(M)] = t(M)[lower.tri(M)]

microbenchmark::microbenchmark(micEcon=miscTools::symMatrix(S[upper.tri(S, TRUE)], nrow=nrow(S), byrow=TRUE),
                               Matri_raw =Matrix::forceSymmetric(S),
                               Matri_conv =as.matrix(Matrix::forceSymmetric(S)),
                               pick_lower = pick_lower(S),
                               base =0.5 * (S + t(S)),
                               times=100)
#> Unit: microseconds
#>        expr    min      lq       mean   median       uq        max neval cld
#>     micEcon 62.133 74.7515  136.49538 104.2430 115.6950   3581.001   100   a
#>   Matri_raw 14.766 17.9130   24.15157  24.5060  26.6050     63.939   100   a
#>  Matri_conv 46.767 59.8165 5621.96140  66.3785  73.5380 555393.346   100   a
#>  pick_lower 27.907 30.7930  235.65058  48.9760  53.0425  12484.779   100   a
#>        base 10.771 12.4535   16.97627  17.1190  18.3175     47.623   100   a

Created on 2021-02-08 by the reprex package (v1.0.0)

A: You can force the matrix to be symmetric using forceSymmetric function in Matrix package  in R:
library(Matrix)
x<-Matrix(rnorm(9), 3)
> x
3 x 3 Matrix of class "dgeMatrix"
           [,1]       [,2]       [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,]  0.7076883 -1.0411563  0.4324291
[3,] -0.4108909 -0.3292247 -0.3076071

A <- forceSymmetric(x)
> A
3 x 3 Matrix of class "dsyMatrix"
           [,1]       [,2]       [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,] -0.4460452 -1.0411563  0.4324291
[3,] -0.2828216  0.4324291 -0.3076071

A: Is the workaround really necessary if the values only differ by that much?
Someone pointed out that my previous answer was wrong. I like some of the other ones better, but since I can't delete this one (accepted by a user who left), here's yet another solution using the micEcon package:
symMatrix(s[upper.tri(s, TRUE)], nrow=nrow(s), byrow=TRUE)

A: as.dist() will overwrite the upper triangle of a matrix with the lower one and replace the diagonal with zeros. This method only works on numeric matrices.
mat <- matrix(1:25, 5)

unname(`diag<-`(as.matrix(as.dist(mat)), diag(mat)))

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    2    7    8    9   10
# [3,]    3    8   13   14   15
# [4,]    4    9   14   19   20
# [5,]    5   10   15   20   25

A: Inspired by user3318600
    s<-matrix(1:25,5)
    s[lower.tri(s)]<-s[upper.tri(s)]


text:
Q: How can I test if an IC output is buffered? I have some CD4069UBE and some CD4069BE. From what I understood, the UBE ones should be unbuffered and the BE ones buffered.
But I don't find any datasheet that shows some buffered 4069, so I'd like to test my BE ones to know if they are buffered or not.
How can I test if the outputs are buffered or not?

A: Testing them is simple and there are many ways, although it requires some equipment.
If you feed in a triangle waveform and connect it to oscilloscope X axis and monitor the output on scope Y axis, the output will look like a round S shaped curve for an unbuffered inverter.
A buffered inverter has 3 inverters in a row, so it will have quite sharp transition at some threshold voltage.
An unbuffered inverter can thus be used as a linear amplifier, just like a cheap op-amp in inverting configuration. Just bias the inverter by connecting a resistor in the order of 1Mohm between output and input. The input should stay biased around half supply. By feeding in AC coupled waveform through a resistance it should work as a linear amplifier. If the output has sharp square wave transitions instead of linear output, it's likely a buffered inverter.

A: Texas Instruments lists a number of different properties for buffered vs unbuffered:

From TI's Application Report: Understanding Buffered and Unbuffered CD4xxxB Series Device Characteristics, p11.
So you could measure the propagation delay on the oscilloscope and it should tell you if your parts are buffered or not.
For what it's worth, I couldn't find the -BE part at all; I did find the 4049 buffered part, sadly with different pinout.

A: There's a bit of historical background needed here. There is no double-buffered version extant in the basic CD4000 family.  If you want 6 buffered inverters, you gotta use two quad inverting output gates.
In most applications, you actually want single-buffered inverters, since they are not meant as high-output buffers, only as fast and sweet logic functions to drive one or two inputs at most. They perform ideally when used that way. To drive anything more, use inverting output gates (4001, 4011, etc.), or complementary buffers (4041), or gated buffers (4503), or quad latches (4076), etc.
As for checking if any are buffered: feed a square wave with about 500ns rise/fall times to CD4011 and CD4069U. Look at the slew rates on the outputs. CD4011 has more gain and will slew faster.

A: There are no buffered 4069 parts. Those with a "B" suffix are not buffered, they are just parts with an older part number. So 4069UB and 4069B are the same chip (this latter being older).
I suspect all your 4069B chips have date codes that go back to the '80s, when the CMOS 4000 series was standardized by JEDEC.
I tracked this problem to the origin of the 4000 series. Follow me on this voyage into the history of ICs.
The 4000 series was invented by RCA and commercialized in 1968.
The older technical reference I could find is a 1975 RCA databook. At page 334 (336 of the PDF - from now on I'll just refer to the original page numbers of scanned documents) you can clearly see that the CD4069B is unbuffered, since it consists of a single CMOS inverter structure (PMOS-NMOS pair).
The "B" suffix didn't mean "buffered" at the time, but it designated a different supply voltage range. That databook explains that at page 21. Excerpt:

Operating Supply-Voltage Range
COS/MOS integrated circuits are specified in one of two
supply-voltage ranges: "A"-series devices operate from 3 to 15
volts, and "B"-series devices from 3 to 18 volts.
[...]
Recommended supply-voltage ranges which
realistically assess these conditions are 4 to 12 volts for
"A"-series devices, and 4 to 15 volts for "B"-series devices.

Why the "B" suffix was later thought to mean "buffered" and where does the "UB" suffix come from?
I couldn't find the exact origin, by my hypothesis is that Texas Instruments, when introducing their line of compatible CMOS devices added the buffering. This can be inferred from this 1975 TI CMOS Databook.
At page 18 they again state that the "B" suffix denotes an extended supply voltage range. Moreover, from what they say there, they give the impression that "A" series devices are plug-in replacements for RCA parts, whereas "B" suffixed devices are improved parts to be used for new designs.
At page 19 they describe the peculiarities of the "B" series. Excerpt (emphasis mine):

BUFFERED CIRCUITS
Most 4XXXXB digital circuits will have double- or triple-buffered output stages to attain:

*

*Uniform dynamic performance

*Improved capacitance drive

*Uniform input characteristics

*Lower input capacitance

*Uniform output characteristics

*Lower over-all system CV 2 f power

*Improved noise immunity

So the buffering seems to be part of the improvements on the RCA chips, but it is not necessarily implemented in each device. In fact the TF4069B and TP4069B chips are described at page 55 as interchangeable with RCA CD4069B and the schematic for the inverters shows no buffer.
These improvements seem to have been standardized by JEDEC, as can be inferred by this 1983 RCA CMOS Databook.
At page 48 there is a section titled:

HIGH-VOLTAGE B-SERIES CMOS INTEGRATED CIRCUITS

which mentions (3rd column, last bullet):

JEDEC Tentative Standard No. 13B, "Standard Specifications for Description of 'B' Series CMOS Devices.

On the following page you can find two subsections:

Buffered CMOS devices are types in which the output "on" impedance is independent of any and all valid input logic conditions, both preceding and present.
All such CMOS product are designated by the suffix "B" following the basic type number.

Unbuffered CMOS devices are types that meet all B-series specifications except that the logical outputs are not buffered and the noise-immunity voltages, VIL and VIH, are specified as 20 and 80 percent, respectively, of VDD for operation from 5 or 10 volts, and 17 and 83 per cent,respectively, of VDD for operation from 15 volts. All such CMOS product are designated by the suffix "UB".

and further below, 2nd column (emphasis mine):

All B-series CMOS devices can directly replace their A-series counterparts in most applications. The UB types are high-voltage versions of corresponding A-series (unbuffered) types.

finally, at page 52:

7. Buffered and unbuffered gates
The new industry standard establishes a suffix "UB" for CMOS products that meet all B-series specifications except that the logical outputs of the devices are not buffered and the VIL and VIH specifications are relaxed.
The suffix "B" defines only buffered-output devices in which the output "on" impedance is independent of any and all valid input logic conditions, both preceding and present.

Which confirms my suspects about the origin of the confusion.

A: Look at the CD4069UB datasheet
Page 1 says that this part is for use in cases where "buffers are not required.  The consensus seems to be that the UB parts are not buffered.

Also, if you look at page 9 of the datasheet, they give you a schematic diagram of the inverter design.  It is a simple two transistor CMOS inverter.

On the other hand, you might want to ask yourself why it matters if its buffered or not.
The datasheet parameters for both parts are pretty similar.
Typical propagation delay is 30ns for both parts at VCC=10V.
The output sink/source current is 2.6mA typical for both parts.
If they both parts can switch at the same speed, and drive the same loading, whether they are buffered or not may make little difference.


text:
Q: How to sort an ArrayList which contain more than 1000 different Strings on the basis of similairy to another given String I have an ArrayList which contains some 1000 strings. I want to sort this list on the basis of similarity to given String from outside. The Strings which are very close to the String will come in the top.
For eg. I have a String like "Beauty and The Beast".
My Arraylist contains String like:
RedWall
Beauty and the Beast 3
BlueWall
BeautyQueen I
Beast of Rome  II
Beauty and the Beast 1
Beast with The Beauty
BlueWall 2
BeautyQueen II
Beast of Rome  I
Beauty and the Beast 2
...
So After sorting this arraylist, it should be something like..
Beauty and the Beast 1
Beauty and the Beast 2
Beauty and the Beast 3
Beast with The Beauty
BeautyQueen I
BeautyQueen II
Beast of Rome I
Beast of Rome II
BlueWall
BlueWall 2
RedWall
Some thing like this.. I dont know how the order is going to be after Beauty and the Beast 3..
But it should pick the String which have exactly same String to be in the beginning.
I am looking for some algorithm which can actually help me in implementing this task in Java.
I have also heard about using Levenstein Distance, but I have no idea on how this can be used for my task.
Any pointers will be a lot of help.

A: Sort according to the levenstein distance http://en.wikipedia.org/wiki/Levenshtein_distance.  With this distance you can define how close strings are to each other. Implement this in a comparator.
Here is a implementation: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
Take the code from sanbhat and replace his score function with the levenstein distance from the wikipedia I posted.
The idea is, that you compare each string with your base string and check, if the distances are smaller or greater. A visuell example: Imagine a 2d plane with a point called x. Now you have a list of points and want to sort them according to their distance to x. What you do is, you compare two points a and b from the list by calculating the distance from a and b to x. If a has the smaller distance to x then a must be smaller then b.
Hth

A: I have created a custom comparator as per your need and here's the code

*

*s is the search string, all the matching/closely matching string to the s should appear first

*I have created a Set<String> matches to store all the tokens(words) of the search string

*I have created a comparator c which has a method getScore(String), which basically gives a score as per number of matches found in the given string of the list against the search string

*If the getScore method returns 0 for both the strings of list OR if both the strings have same number of matches, I am sorting them in their natural ordering.

*else I am promoting the string which has highest match by returning -ve
List<String> l = new ArrayList<String>();
l.add("RedWall");
l.add("Beauty and the Beast 3");
l.add("BlueWall");
l.add("BeautyQueen I");
l.add("Beast of Rome II");
l.add("Beauty and the Beast 1");
l.add("Beast with The Beauty");
l.add("BlueWall 2");
l.add("BeautyQueen II");
l.add("Beast of Rome I");
l.add("Beauty and the Beast 2");

String s = "Beauty and the Beast"; //search string
final Set<String> matches = new HashSet<String>();
for(String tokens : s.split("\\s")) {
    matches.add(tokens.toLowerCase()); //convert the search string into tokens
}

Comparator<String> c = new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        int scoreDiff = getScore(o1) - getScore(o2);
        if((getScore(o1) == 0 && getScore(o2) == 0) || scoreDiff == 0) {
            return o1.compareTo(o2);
        }
        return - (getScore(o1) - getScore(o2));
    }

    private int getScore(String s) {
        int score = 0;
        for(String match : matches) {
            if(s.toLowerCase().contains(match)) {
                score++;
            }
        }
        return score;
    }
};
Collections.sort(l, c);
for(String ss : l) {
    System.out.println(ss);
}

and here's the output
Beauty and the Beast 1
Beauty and the Beast 2
Beauty and the Beast 3
Beast with The Beauty
Beast of Rome I
Beast of Rome II
BeautyQueen I
BeautyQueen II
BlueWall
BlueWall 2
RedWall


text:
Q: paasing from variable to java script and pass this javascript variable to jsp tag i want to pass the javascript variable to jsp tag. i dont know how to pass this value.
And also i am looking for how to pass form hidden variable to the same web page in jsp. there is any method to collect form hidden variable in javascript and pass it to the jsp tag on the same wep page

A: You can't.
JSP executes on the server. A document is sent to the client. JavaScript executes on the client (by which time it is too late to get new data into the JSP for this document).
To get data from the client back to the server you need to issue a new HTTP request:

*

*Follow a link

*Set location

*Submit a form

*Use XMLHttpRequest

*Visit a URI in an iframe


text:
Q: Setting cookies with javascript in Chrome iOS I need to set cookies in Javascript, before the browser will begin to fetch images.

<script type="text/javascript">
    document.cookie='hidpi=1; path=/';
</script>

<img src="happyNY.png" alt=""/>

It works fine in all desktop browsers and in iOS Safari. They are fetching the images with HTTP cookie header had been set.
GET /happyNY.png HTTP/1.1
Host: localhost
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
…
Accept-Encoding: gzip, deflate, sdch
Cookie: hidpi=1

The problem is, that iOS Chrome ignores cookies, while requesting the images.
GET /happyNY.png HTTP/1.1
Host: localhost
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
…
Accept-Encoding: gzip, deflate, sdch

If you click F5, then iOS Chrome will request image with HTTP cookie header correctly set.

A: The only solution I found, was to reload the page for Chrome iOS browser:

<script type="text/javascript">
  if (navigator.userAgent.indexOf('CriOS')>=0 && document.cookie.indexOf('hidpi')<0)
  {
    document.cookie='hidpi=1; path=/';
    window.location.reload();
  }

  document.cookie='hidpi=1; path=/';
</script>


text:
Q: In CartoDB, can columns (e.g. ARPU2011) have descriptions (e.g. Average Revenue Per User 2011) I have an in-house database with spatial data (Postgres + PostGIS) for which I'm generating an extract (GeoJSON/KML etc) in order to load it into CartoDB.
My column names are technical (e.g. ARPU2011, or even less clear, and I need this to remain that way) but I also have column descriptions available (e.g. "Average Revenue Per User 2011").
Using which export format and what type of formatting can I then later find both the technical name and the description usable for filtering in CartoDB?

A: After a bit of searching in multiple places, I believe it is not yet possible. See GitHub issue - Suggestion: Allow adding a description for column information


text:
Q: Doctrine em fetch associate data in Codeigniter I'm working on codeigniter doctrine orm , setup everything but don't know how to fetch data!
having two tables 'user' and 'firm' , wanted to load user with their firms.
Tried this way also ,
$records = $em->getRepository("Entities\YourTargetEntity")->findAll();

But its not working ,
My controller function is,
public function index()
{
    $em = $this->doctrine->em->user;
    $records = $em->getRepository("Entities\user")->findAll();
    echo '<pre>';
    print_r($records);die;
    $this->load->view('welcome_message');
}

Note:I've added firm_id to user table as foreign key. So what i need is 'How to fetch mapped data in doctrine (CI)?'.

A: I believe that the code is as follows:
$userRepository = $this->doctrine->em->getRepository('Entities\user');
$records = $userRepository->findAll();

The findAll() method is available in Doctrine\ORM\EntityRepository class:
http://www.doctrine-project.org/api/orm/2.4/source-class-Doctrine.ORM.EntityRepository.html#158-166


text:
Q: Testing rejected promise in Mocha/Chai I have a class that rejects a promise:
Sync.prototype.doCall = function(verb, method, data) {
  var self = this;

  self.client = P.promisifyAll(new Client());

  var res = this.queue.then(function() {
    return self.client.callAsync(verb, method, data)
      .then(function(res) {
        return;
      })
      .catch(function(err) {
        // This is what gets called in my test
        return P.reject('Boo');
      });
  });

  this.queue = res.delay(this.options.throttle * 1000);
  return res;
};

Sync.prototype.sendNote = function(data) {
  var self = this;
  return self.doCall('POST', '/Invoice', {
    Invoice: data
  }).then(function(res) {
    return data;
  });
};

In my test:
return expect(s.sendNote(data)).to.eventually.be.rejectedWith('Boo');

However while the test passes it throws the error to the console.
Unhandled rejection Error: Boo
   ...
With non promise errors I have used bind to test to prevent the error from being thrown until Chai could wrap and test:
return expect(s.sendNote.bind(s, data)).to.eventually.be.rejectedWith('Boo');

However this does not work with this and returns:
TypeError: [Function] is not a thenable.
What is the correct way to test for this?

A: You're getting the error because sendNote is being rejected and you're not catching it.
Try:
var callPromise = self.doCall('POST', '/Invoice', {
  Invoice: data
}).then(function(res) {
  return data;
});

callPromise.catch(function(reason) {
  console.info('sendNote failed with reason:', reason);
});

return callPromise;

Looks like you'll also have to move your existing catch one block out:
var res = this.queue.then(function() {
  return self.client.callAsync(verb, method, data)
    .then(function(res) {
      return;
    });
  }).catch(function(err) {
    // This is what gets called in my test
    return P.reject('Boo');
  });

A: (Disclaimer: This is a good question even for people that do not use Bluebird.  I've posted a similar answer here; this answer will work for people that aren't using Bluebird.)
with chai-as-promised
Here's how you can use chai-as-promised to test both resolve and reject cases for a Promise:
var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);

...

it('resolves as promised', function() {
    return expect(Promise.resolve('woof')).to.eventually.equal('woof');
});

it('rejects as promised', function() {
    return expect(Promise.reject('caw')).to.be.rejectedWith('caw');
});

without chai-as-promised
You can accomplish the same without chai-as-promised like this:
it('resolves as promised', function() {
  return Promise.resolve("woof")
    .then(function(m) { expect(m).to.equal('woof'); })
    .catch(function(e) { throw e })  // use error thrown by test suite
           ;
});

it('rejects as promised', function() {
    return Promise.reject("caw")
        .then(function(m) { throw new Error('was not supposed to succeed'); })
        .catch(function(m) { expect(m).to.equal('caw'); })
            ;
});

A: I personally use that idiom:
it('rejects as promised', function() {
    return Promise.reject("caw")
        .then(
          (m) => { assert.fail('was not supposed to succeed'); }
          (m) => { /* some extra tests here */ }
        );
});

This is one of the rare cases then(onFulfilled, onRejected) (2 arguments) is legitimate to use.
If you chain .then(reject).catch(onRejected) as suggested in other answers, you end up entering in the catch handler every time since it will catch as well the rejection produced in the preceding then handler--which could cause evergreen tests if you're not careful enough to check that eventuality.

A: generic helper function:
import { assert } from 'chai'

const assertThrowsAsync = async(fn, expectedMessage) => {
    try {
        await fn()
    } catch (err) {
        if (expectedMessage) {
            assert.include(err.message, expectedMessage, `Function failed as expected, but could not find message snippet '${expectedMessage}'`)
        }
        return
    }
    assert.fail('function did not throw as expected')
}

calling it like so:
describe('demo', () => {

    it('negative: inacceptable path', async() => {
        await assertThrowsAsync(async() => {
            await someFuntionOfMine({}, ['/really/bad/path'])
        }, 'acceptable path')
    })

    ...


text:
Q: Placement of adverb with gerund-participle that is the object of a preposition I have a rather fussy grammar question, and I'm having a hard time finding out whether there even is a rule that applies here. Even describing the structure correctly is a bit of a challenge.
The sentence in question is this:

Current data collection practices in the country hardly inspire confidence, with personal information regularly being shared among different parties without the knowledge of customers.

This sentence comes from a test of English grammar used in certain countries for English language learners. (For what it's worth, the credited answer, according to the test, is that the sentence contains no error.) I have ended up in a discussion with a grammar teacher over the placement of the word "regularly".
The question is this: is there any standard rule addressing the difference between

...information regularly being shared...

and

...information being regularly shared....

I should clarify exactly what I am asking, and what I am not asking.
My question(s)

*

*Is there any specific rule in a standard English grammar reference (US- and/or UK-based) that addresses this issue? Ideally, a citation to a dusty old grammar reference could be provided. That would somehow be an ideal answer.

*How exactly does one analyze this structure in the first place?

*(Bonus) Is anyone brave enough to diagram this beast? :D

Regarding question 2, I'm seeing a preposition (with), whose object is everything that comes after it. Stripping off all inessential pieces, I get "information being shared" as the bare-bones object of the preposition. What, precisely, is that construction? It must be a gerund phrase, but what is "shared" doing in there, exactly? Is is a participial adjective, completing the linking gerund "being"? Is there something passive about the construction? A lot is going on here!
Anyway...
Not my question(s)

*

*Which version do speakers prefer/which is more natural? I don't mind comments addressing this point, but they will not help with what I'm asking.

*Any philosophical/sociological points about prescriptive vs. descriptive grammar. That's a different conversation, and I know where I stand on those questions. This is just an instance of two people grammar-geeking out because we can.

*How you might rephrase the sentence to avoid this matter. That's neat and all, but again, I'm just trying to find out whether any of the standard prescriptive grammar books address this very particular issue, and if so, what do they say.

A: I shall start with a brief answer to the numbered questions.

*

*As far as I am aware, there is no such fustian rule in a dusty grammar.  But the finer points of the order of adverbs is not an area which i have considered.  I can imagine fine differences.  Of the alternatives given in the question, I marginally prefer the first, with "regularly being shared".  The second, "being regularly shared" might be construed to involve not just that regularly a lot of personal information gets shared, but that lots of personal information gets regularly shared, which is very slightly different.  But I would not go to the stake on this.  I probably would not have noticed, had the question not been raised.  In context, it is abundantly clear what is meant.

*The phrase fragment "...with personal information regularly being shared..." is (I think) an absolute phrase, and "being" (or "being shared") is a participle, qualifying the noun information.  It is not, in my view, a gerund.  I have already explained this in comment and a reply, and shall say more below.

*I cannot comment on the diagramming question.  I was educated in Britain, and this is a phenomenon of US school education, unknown in the UK.  I first encountered it in reading Noam Chomsky's revolutionary book Syntactic Structures, in which he uses the idea of diagramming as a way to present his idea of what he called 'deep structure'.  My understanding of grammar came from the study of Latin and ancient Greek.
There is a term, used in two sources I have found:  that of the absolute phrase.  Examples of this are found, for example, in English Grammar (https://www.englishgrammar.org/absolute-phrase/).  It explains:

When a participle and the noun that comes before it together form an independent phrase, the structure is often called an absolute phrase.

I should say that is a fair description of what I understand by the idea.  It goes on to gives examples like these:

The weather being fine, we went out for a picnic.
  The visitors having left, we went to bed.

It is easy to see that the first of of the two, express a causal relationship between the fact that the wether was fine and the fact that we went out for a walk.  It could have been expressed as:

Because the weather was fine, we went out for a walk.

The second of the two expresses a temporal relationship between the departure of the visitors and our going out for a walk.  We did not go out because they had left.  We just did so afterwards.

When the visitors had left, we went out for a walk.

In both sentences, the opening phrases involve participles, not gerunds.  And there is a perfectly good reason for saying this.  Take these two sentences.

Tired of watching TV, we decided to go out for a walk.

Here, as in the first example, the relationship is obviously causal.  But here it is obvious that "tired" is a participle and that it qualifies the subject of "decided".  It could not possibly be a gerund.
The second sentence can receive the same treatment.

Bidding farewell to our visitors, we went out for a walk.

This has the same temporal relationship, and it is obvious that "bidding" is a participle and qualifies the first person plural pronoun 'we'.  It cannot possibly be a gerund.  So why, in the two sentences in question, should it seem to be a gerund rather than a participle?  Well, in both these sentences, the '-ing' word in question does not qualify any noun or noun phrase in the sentence!  Oh, yes:  and there is this wretched little preposition "with".  With has to modify some noun in the sentence.  But there is none that it can modify... except ** the whole phrase "with personal information being shared...".  And that would make "being shared" a gerund, surely.  A generation ago I should have been able to say that, if so, "personal information being shared" should be "personal information's** being shared.  But the use of the possessive 's with the verbal noun has completed its process of dropping out of use.
The temptation to treat it as a gerund is the greater, because of the difficulty of the grammatically homeless phrase.
But there remains the alternative I mentioned at the outset:  The "Absolute Phrase".  What does this mean and where does it come from?  I have no doubt that it owes its existence to the absolute phrases familiar to the many people who at school studied Latin and the slightly fewer who also studied ancient Greek.  Latin uses participles in exactly this way, and it is called the ablative absolute.  I am as sure as I can be that this accounts for the choice of the term absolute in this context.  In Latin you might get a sentence like this:-

Obsidibus capris, Caesar exercitum in hibernias duxit.
  Literally, "Hostages having been taken, Caesar led his troops into winter quarters."

This construction is used to express a temporal or causal connection.  Ablative is the case used to express agency, cause or origin, and was explained in the grammar books with the words by, with or from.  In ancient Greek, which had no ablative, the corresponding construction employed the genitive, which expressed not only possession, but also agency, origin and cause.
Where does this 'absolute' word come from?  It is and always has been the word used for this particular Latin construction:  the ablative absolute.  Latin was the language of learning and scholarship throughout the middle ages and widely used in the 18th century:  both Newton in England and Leibnitz in Germany wrote their seminal works in Latin.  Even in the 19th century Latin was taught in private schools and grammar schools, and continued to plague such pupils well into the 1950s and early sixties. The following is a good explanation of it.

The ablatives of a participle and a noun (or pronoun) are used to form a substitute for a subordinate clause defining the circumstances or situation in which the action of the main verb occurs. The ablatives are only loosely connected grammatically to the remainder of the sentence, hence its name absolute (absolūtus = free or unconnected). Its connection with the sentence is, essentially, logical:  syntactically, it stands alone.

There are, in fact, familiar phrases that work like this.

Weather permitting, we should make it to top.
  That being said, I don't approve of what you are doing.
  Given the presence of rioters in the street outside, they they decided to stay where they were.
  All things considered, I think we had better leave at once.

But where did the with come from?  My answer is speculative.  The Latin ablative absolute was the bane of many a reluctant victim of the study of Latin.  It was also the bane of teachers of Latin, trying to move their pupils away from the hideous literal translation of "obsidibus captis" as "with hostages having been taken".  Well, out of the possible interpretations of the ablative, 'by' and 'from' seem unpromising, so perhaps 'with' will do.  But since then the usage of 'with' introducing an absolute phrase has become increasingly common.

A: In comment, John Lawler wrote:

There may well be fussy pedantic rules on this in some grammar textbook, but those are for children, like Santa Claus. And they are equally incorrect. Adverbs are notoriously free in their position in English, though there are different affordances for different kinds of adverbs -- "Adverb" is something of a wastebasket category. In this case, whether the adverb is on one side or another of a meaningless auxiliary verb (being) is of no consequence.

And:

A fussy pedant would insist that the closer the adverb is to the word it modifies, the correcter it is. They would also assume that any adverb would modify a particular word, not a phrase or clause, because they learned the beads-on-a-string (or word-follows-word) theory of grammar, and words are all they can see. They might also say something about "regularly shared" being a fixed phrase, which is possible, and if so argues for keeping them together as a predicate phrase. Finally, there might be words about a supposed distinction in the meaning(s) of be; this part can be ignored profitably.


text:
Q: I am getting error in .podspec file -> TestPod.podspec
    - ERROR | spec: The specification defined in `TestPod.podspec` could not be loaded.

[!] Invalid `TestPod.podspec` file: undefined local variable or method `"blabla"' for Pod:Module.

 #  from TestPod.podspec:30
 #  -------------------------------------------
 #
 >    s.author             = { "{blabla}" => "blablabla@gmail.com" }
 #
 #  -------------------------------------------

I am use 'pod spec lint TestPod.podspec --verbose' commnad in terminal.but return above error let me know if you have any chance to solve this.


text:
Q: Event passing to sibling on clicking a view I have a simple LinearLayout(horizontal) with 3 TextViews. The background of these TextViews are set to a drawable that has two states, state_pressed and default. I simply change the background of each TextView to red on state_pressed.
But when i click one TextView, its click listener is invoked but background of all 3 changes to red. This is happening on Android 2.x and working fine on Android 4.0+.
<LinearLayout
        android:id="@+id/back"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/swipe_list_leftoffest"
        android:descendantFocusability="blocksDescendants"
        android:background="@color/list_swipe_back"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:weightSum="3"
        android:tag="back">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="14sp"
                    android:clickable="true"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:id="@+id/amenities_view"
                    android:padding="@dimen/padding_large"
                    android:background="@drawable/swipe_view_background"
                    android:drawablePadding="@dimen/padding_large"
                    android:textColor="@color/white"
                    android:text="@string/amenities_text"
                    android:drawableTop="@drawable/ic_amenities"
                    />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:layout_weight="1"
                android:clickable="true"
                android:gravity="center"
                android:ellipsize="end"
                android:singleLine="true"
                android:id="@+id/cancpolicy_view"
                android:padding="@dimen/padding_large"
                android:background="@drawable/swipe_view_background"
                android:drawablePadding="@dimen/padding_large"
                android:textColor="@color/white"
                android:text="@string/canc_policy_text"
                android:drawableTop="@drawable/ic_cancellation_policy"

                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:layout_weight="1"
                android:gravity="center"
                android:clickable="true"
                android:padding="@dimen/padding_large"
                android:id="@+id/reviews_view"
                android:background="@drawable/swipe_view_background"
                android:drawablePadding="@dimen/padding_large"
                android:textColor="@color/white"
                android:text="@string/reviews_text"
                android:drawableTop="@drawable/ic_reviews"
                />

    </LinearLayout>

Tried putting focusable and focusableInTouchMode false for each of the TextViews, but that didnt help.

A: Do you have 3 separate onClickListeners for the TextViews? If you have only one, this may be the problem and you could solve it by doing something like this in the listener:
public void onClick(View v){
   switch(v.getId()){
      case R.id.amenities_view:
          //Click first
          break;
      case R.id.cancpolicy_view:
          //Click second
          break;
      case R.id.reviews_view:
          //Click third
          break;
   }
}

If you do not create this switch, all the views associated with the listener will react to the click.


text:
Q: Insert query not working in MySQL , PHP Here is my code to insert data in MySQL as Back-end and PHP as front-end
Connection is established properly but insert query is not working neither it is showing any error as per the else conditions at the end after insert query
It is not reaching inside the $_POST['submit'] too.

<title></title>

    <form type="post" name="addimage" enctype="multipart/form-data" >
     Album Name<input type="text" name="albumname">
    <input type="file" name="filesToUpload" id="filesToUpload" multiple=""/>

       Client Name<input type="text" name="clientname">

Location<input type="text" name="location">
        <button type="submit" value="submit" name="submit" id="submit">Submit</button>

</form>

<?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "apostrophe";
 $con=mysqli_connect("localhost","root","","apostrophe");
 mysqli_select_db($con,"apostrophe");
if(isset($_POST['submit']))
{
echo "reached";
$albumname=$_REQUEST['albumname'];
$images=$_REQUEST['filesToUpload'];
$client=$_REQUEST['clientname'];
$loc=$_REQUEST['loc'];
echo "reached submit";
$sql="INSERT INTO album(albumname,images,clientname,location)VALUES('$albumname','$albumname','$client','$loc')";
echo "reached down";
if($con->query($sql)===TRUE)
{
 echo "Success";
}
else
echo "Failed";
}
?>

A: The original code has quite a few errors in ( the form straddles the body, wrong declaration for form method, title outside the head etc ) and there is no attempt at handling the actual uploaded images. Hopefully the following ought to give you a headstart with getting the file handling piece completed - though no doubt I have missed something too '-)
<?php
    $status='';
    /* Might as well test that all necessary fields are included in form submission */
    if( isset( $_POST['submit'], $_POST['albumname'], $_POST['clientname'], $_POST['location'] ) ){

        /* only need to declare the db connection if the variables are set */
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "apostrophe";

        /* create the db conn */
        $con=mysqli_connect("localhost","root","","apostrophe");

        /* at least some basic filtering if you intend to place user submitted content directly in the sql */
        $albumname=strip_tags( filter_input( INPUT_POST,'albumname',FILTER_SANITIZE_STRING ) );
        $client=strip_tags( filter_input( INPUT_POST,'clientname',FILTER_SANITIZE_STRING ) );
        $loc=strip_tags( filter_input( INPUT_POST,'location',FILTER_SANITIZE_STRING ) );

        /* handle file uploads */
        $fieldname='filesToUpload';

        foreach( $_FILES[$fieldname]['name'] as $i => $name ) {
            if( !empty( $_FILES[$fieldname]['tmp_name'][$i] ) ) {

                $filename = $_FILES[$fieldname]['name'][$i];
                $size = $_FILES[$fieldname]['size'][$i];
                $type = $_FILES[$fieldname]['type'][$i];
                $tmpfile  = $_FILES[$fieldname]['tmp_name'][$i];

                /* copy file to final destination - this is not complete!! */
                $bytes=move_uploaded_file( $tmpfile, '/path/to/final/directory/'.$filename );

                /* to debug uncomment below */
                #echo $filename,$tmpfile,$size,$type;
            }
        }

        /* prepare and execute sql */
        $sql="INSERT INTO `album` ( `albumname`, `images`, `clientname`, `location` ) VALUES ( '$albumname', '$albumname', '$client', '$loc' )";

        /* set status variable to be displayed under form */
        $status=( $con->query( $sql )===TRUE ) ?  "Success" : "Failed";

    } else {
        $status='bad foo';
        $status=print_r( $_POST, true );
    }
?>

        <title>File upload and database inserts</title>

        <form method="post" name="addimage" enctype="multipart/form-data" >
            Album Name<input type="text" name="albumname">
            <input type="file" name="filesToUpload[]" id="filesToUpload" multiple=""/>

            Client Name<input type="text" name="clientname">

            Location<input type="text" name="location">
            <button type="submit" value="submit" name="submit" id="submit">Submit</button>
        </form><?php echo $status; ?>

A: Change your line :
<form type="post" name="addimage" enctype="multipart/form-data">
to
<form method="post" name="addimage" enctype="multipart/form-data">


text:
Q: Getting the Table from a Google Spreadsheet We want to gather the info from a google spreadsheet, and are following the code samples given in the Google Apps Platform help.
Using that code, we found the right spreadsheet and the right worksheet (the Debug line confirms it to be the right worksheet - there are only two in the whole account).  However, when it comes to fetching the data from the rows, it comes back blank.  So I tried to discover the number of rows, and the count comes back 0, which explains why there was no text forthcoming.
So what am I missing?
  Debug.WriteLine("Worksheet Name=" + worksheet.Title.Text);
  // Iterate through each row, printing its cell values.
  foreach (ListEntry row in listFeed.Entries){
      Debug.WriteLine("thisrow=" + row.Title.Text);
  }
  Debug.WriteLine("Number of rows=" + listFeed.Entries.Count);

P.S. I've been to this wonderful thread, but it doesn't mention list-based feeds - only cell-based feeds.

A: Ah!  Solved it:
There was a blank row just below the header row.  Apparently, that breaks the dataset, which explains why I was getting no results.

The list feed contains all rows after the first row up to the first
  blank row. The first blank row terminates the data set. If expected
  data isn't appearing in a feed, check the worksheet manually to see
  whether there's an unexpected blank row in the middle of the data. In
  particular, if the second row of the spreadsheet is blank, then the
  list feed will contain no data.


text:
Q: Get all data attributes of an element and their value in jquery I have a element defined as follows:

I have performed a click event on this element as :
$('.js-road-btn').on('click', function () {
    var latS = $(this).attr('data-lat-s');
    var longS = $(this).attr('data-lng-s');
    var latE = $(this).attr('data-lat-e');
    var longE = $(this).attr('data-lng-e');
});

Instead of getting each attribute separately, I want to retrieve all the attributes values as a whole. Then I access the properties separaretly. How can I achieve this in jquery ?

A: You could use the jQuery method .data() like :
$(this).data(); //Will return the set of all the data-* attributes

$('.js-road-btn').on('click', function() {
  var attributes = $(this).data();

  console.log(attributes);

  alert(attributes.lngE);
});

 Click me

A: As the values are all stored in data-* attributes, you can use data() (with no arguments) to retrieve them all in a single object:

$('.js-road-btn').on('click', function() {
  var data = $(this).data();
  console.log(data);
});

  Click me


text:
Q: Applications of the weighted matrix exponential $x^\top e^A x$ (a quadratic function) In this post, the matrix exponential $$e^A = \sum_{k=0}^\infty \frac{1}{k!} A^k$$ of any symmetric matrix $A$ was proven to be positive-definite based on the quadratic function $$x^\top e^A x$$ where $x$ are weights that could sum to 1, I don't know.
In what sort of empirical applications is this weighted matrix exponential, $ x^\top e^A x$,  even used?


text:
Q: PortAudio unreliable: Expression '...' failed I'm currently experimenting with real-time signal processing, so I went and tried out PortAudio (from C).
I have two audio interfaces on my computer, onboard sound (Intel HD Audio) and a USB audio interface. Both generally work fine under ALSA on Linux. I also tried the USB audio interface under JACK on Linux and this also works perfectly.
What I do:
My code just initializes PortAudio, opens and starts a stream (one channel, paInt32 sample format, defaultLowInputLatency / defaultLowOutputLatency, though I tried changing to paFloat32 or defaultHighInputLatency / defaultHighOutputLatency, which didn't improve anything).
On each invocation of the callback, it copies sizeof(int32_t) * frameCount bytes via memcpy from the input to the output buffer, then returns paContinue. It does nothing else in the callback. No memory allocation, no system calls, nothing it could block on. It just outputs what it has read. The code is very simple, still I can't get it running.
Replacing the memcpy with a loop copying frameCount elements of type int32_t over from the input to the output buffer didn't change anything.
What I've tried:
The following scenarios were tried out with PortAudio.

*

*Input and output via USB audio interface, callback mechanism on PortAudio, ALSA backend.

*Input and output via USB audio interface, blocking I/O on PortAudio with 1024 samples buffer size, ALSA backend.

*Input via USB audio interface, output via onboard sound, callback mechanism on PortAudio, ALSA backend.

*Input via USB audio interface, output via onboard sound, blocking I/O on PortAudio with 1024 samples buffer size, ALSA backend.

*Input and output via USB audio interface, callback mechanism on PortAudio, JACK backend.

*Input and output via USB audio interface, blocking I/O on PortAudio with 1024 samples buffer size, JACK backend.

The problems I encountered:
The results were as follows. (Numbers represent the scenarios described above.)

*

*No output from device.

*Output from device unsteady (interrupted). All the time lots of buffer underruns.

*No output from device.

*Output from device unrealiable. Sometimes it works, sometimes it doesn't. (Without changing anything, just running the executable multiple times.) When it works, latency starts off low, but increases over time and gets very noticeable.

*No output from device.

*No output from device.

Between each try, ALSA has been tested if it's still responsive (sometimes it got completely "locked up", so that no application could output sound any longer) and rebooted the system in case ALSA got "locked up", then continued the testing.
More details, that might be useful when tracking the problem down:
In the scenarios where there is no output at all, I get the following error messages when using ALSA as backend.
Expression 'err' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 3350
Expression 'ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 3876
Expression 'PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 4248

I get the following error message when using JACK as backend.
Cannot lock down 42435354 byte memory area (Cannot allocate memory)

In addition, no matter what method I use, I always get these warnings.
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map

When using ALSA, I also get one or two complaints about underruns.
ALSA lib pcm.c:7905:(snd_pcm_recover) underrun occurred

The PortAudio functions that I call (Pa_Initialize, Pa_OpenStream, Pa_StartStream, Pa_StopStream, Pa_CloseStream, Pa_Terminate, in this order), all return paNoError.
The paex_read_write_wire.c (blocking I/O) example that comes with PortAudio can usually access the device, but also experiences lots of underruns (like my test case 2).
In either case, there's nothing interesting showing up in dmesg. (Just checked that, since ALSA has a kernel-level component.)
My question:
Anyone knows what's the problem here and how I could fix it? Or at least, how I could narrow it down a bit more?

A: When you write only a single block of samples, the playback device will run out of samples just when you're about to write the next block.
You should fill up the playback device's buffer with zero samples before you start the read/write loop.

A: I'm unclear on the details, but for me switching from default low input/output latency to default high input/output latency cured this problem, and I can't perceive a change in latency.


text:
Q: F test with a multiplier in null hypothesis I'm having a following question in my entrance exam practices:
A model of beta1 + beta2 * variable2 + beta3 * variable3 + error, based on specific data.
The claim: Beta3 equals 5 times beta2.
The exercise: Perform f-test to test whether the claim is valid at 5% confidence interval.
How should I form the restricted regression? All my materials are describing how to start with hypotheses such as beta2 + beta3 = 1, and so on. How to deal with a multiplier?


text:
Q: Como eu faço para adicionar mais elementos a um array no php Estou criando uma função pra validar dados de formulário, e queria saber como eu adiciono os erros ao array, a cada erro novo ele add no array???
<?php
// Função criada para validar todo tipo de formularios em uma unica função \\

function valida_formularios($nome){

    // Criamos um array de erro
    $erro = array();

    //Verificamos se exite uma variavel nome setada
    if(!isset($nome)){
        // Caso não exite o programa continua normal
    }else{
        if(empty($nome)){
            $erro = 'Variavel nome está fazia';
        }else{

            // Rodamos a validação de nome
            $nome = str_replace(" ","",$nome); // Retira os espaços caso aja

            // Verifica se a números no nome
            if(filter_var($nome, FILTER_SANITIZE_NUMBER_INT) === '' ? false : true){
                $erro = 'É proibido usar numeros no seu nome';
            }

             // Conta o numero de caracteres
            $cont_nome = strlen($nome);

            // Verifica se a variavel tem menos de 3 letras
            if($cont_nome <= 3){
                $erro = 'A variavel deve conter no minimo 3 letras';
            }

            // Verifica se a variavel tem mais que 16 letrar
            if($cont_nome >= 16){
                $erro = 'seu nome não pode ter mais que 16 caracters';
            }

            return $erro;

        }
    }
}

A: Para adicionar itens em um array você deve utilizar a função array_push.
http://php.net/manual/pt_BR/function.array-push.php
Por exemplo:
$erro = [];
array_push($erro, "Erro 1");
array_push($erro, "Erro 2");
print_r($erro);

A: No php é possível adicionar elementos a um array de diversas formas, elas são:
Dado seu array $erro:

*

*Adicionando elemento em uma posição específica do array:
$erro[5] = $elemento;

*Adicionando elemento na última posição do array com função:
array_push($erro, $elemento);

*Adicionando elemento na última posição do array:
$erro[] = $elemento;


text:
Q: Ошибка прогнозирования python Я хочу получить правильный результат прогнозирования. Прогноз основан на 5 инпутах и 5 значениях. По одному значению в каждом. Мне нужно сделать всего один инпут, чтобы в него поместить 5 значений. Я использовал библиотеку select2, но прогноз был неверный. Я думаю, что это из-за этой библиотеки, т.к видимо на выходе функция прогнозирования получила только одно значение, а остальные 4 просто пропустила.Вопрос в том, как сделать так, чтобы был один инпут и все 5 значений в нем считывались?
Код:
app.py:
app = Flask(__name__)

with open('templates/Testing.csv') as f:
        reader = csv.reader(f)
        values = next(reader)
        values = values[:len(values)-1]

@app.route('/', methods=['GET','POST'])
def dropdown():
        return render_template('includes/default.html', values=values)

@app.route('/predict', methods=['GET','POST'])
def predict():
    selected_values = []
    if(request.form['Value1']!="") and (request.form['Value1'] not in selected_values):
        selected_values.append(request.form['Value1'])
    if(request.form['Value2']!="") and (request.form['Value2'] not in selected_values):
        selected_values.append(request.form['Value2'])
    if(request.form['Value3']!="") and (request.form['Value3'] not in selected_values):
        selected_values.append(request.form['Value3'])
    if(request.form['Value4']!="") and (request.form['Value4'] not in selected_values):
        selected_values.append(request.form['Value4'])
    if(request.form['Value5']!="") and (request.form['Value5'] not in selected_values):
        selected_values.append(request.form['Value6'])

    result = prediction.dosomething(selected_values)
    return render_template('predict.html',result=result, values=values)

if __name__ == '__main__':
    app.run(debug=True)

default.html:

  <form name="ValueForm" id="ValForm" method="POST" action=/predict>

      Select your values

      Value 1
      <input type="text" list="values" multiple="multiple" class="form-control" name="Value1">
      <datalist id="val">
          {% for val in values %}
          <option value= "{{val}}">{{val}}</option>
        {% endfor %}
      </datalist>

      Value 2
      <input type="text" list="values" multiple="multiple" class="form-control" name="Value2">
      <datalist id="val">
          {% for val in values %}
          <option value= "{{val}}">{{val}}</option>
        {% endfor %}
      </datalist>

      Value 3
      <input type="text" list="values" multiple="multiple" class="form-control" name="Value3">
      <datalist id="val">
          {% for val in values %}
          <option value= "{{val}}">{{val}}</option>
        {% endfor %}
      </datalist>

      Value 4
      <input type="text" list="values" multiple="multiple" class="form-control" name="Value4">
      <datalist id="val">
          {% for val in values %}
          <option value= "{{val}}">{{val}}</option>
        {% endfor %}
      </datalist>

      Value 5
      <input type="text" list="values" multiple="multiple" class="form-control" name="Value5">
      <datalist id="val">
          {% for val in values %}
          <option value= "{{val}}">{{val}}</option>
        {% endfor %}
      </datalist>

    <button type="submit" class="btn btn-primary" style="padding: 10px;" name=form>Identify</button>
</form>

predict.py:
data = pd.read_csv(os.path.join("templates", "Training.csv"))
df = pd.DataFrame(data)
cols = df.columns
cols = cols[:-1]
x = df[cols]
y = df['prognosis']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)

print ("DecisionTree")
dt = DecisionTreeClassifier()
clf_dt=dt.fit(x_train,y_train)

indices = [i for i in range(137)]
values = df.columns.values[:-1]

dictionary = dict(zip(values,indices))

def dosomething(value):
    user_input_values = value
    user_input_label = [0 for i in range(137)]
    for i in user_input_values:
        idx = dictionary[i]
        user_input_label[idx] = 1

    user_input_label = np.array(user_input_label)
    user_input_label = user_input_label.reshape((-1,1)).transpose()
    return(dt.predict(user_input_label))

identify.html:
{% block body%}

{{ result[0] }}

{% endblock %}

A: исходя из уточняющих вопросов в ЛС:
требуется одна форма в которой можно сделать мультивыбор без ctrl/shift -
test.html:
<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />

            <form action="/home" method="POST" class="form-inline">
                <select id='sel' name='sel' class="selectpicker" multiple data-live-search="true">
                    {% for val in values %}
                    <option value= "{{val}}">{{val}}</option>
                    {% endfor %}
                </select>
                <button type="submit" class="btn btn-primary mb-2">Select</button>
            </form>

всё это передать в python и вызвать dosomething(), которая принимает список, из predict.py -
test.py:
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def login():
    values = [1, 2, 3]
    return render_template('test.html', values=values)

@app.route('/home', methods=['GET', 'POST'])
def home():
    print(request.form.getlist('sel'))
    return 'OK', 200

app.run(host='10.10.10.2', port=5555, debug=True)


text:
Q: Has anybody seen git create a commit that has no date & an all-zero hash? So a fellow team member, using TortoiseGit in Windows, pulled up his log the other day, and at the top was a commit with a hash entirely of zeroes, no user, and no date, but it did have four modified files and a commit message.
It appears to be a commit from some time ago, but other than that we've no idea.
Is there any way to either correct this commit, or to just remove it, so it's not sitting at the top of his log all the time?

A: TortoiseGit shows the state of the current working copy with "commit 0000":

I don't know how to explicitly tell TortoiseGit to save a commit message for the next commit, but when a merge fails this space is pre-populated with the merge message, which could give the impression this already is a commit.
So to answer the actual question "how to correct this", just commit the changes ;-).

A: If the Working Directory is dirty, it's possible that it's just a pseudo-commit to show you what's changed.


text:
Q: Is it possible to find the 3d position of the camera relative to a cube (dimentsions known) based on the edges length? I am trying to find the relative position of the camera to a fixed cube using the length of the visible edges (2 if the cube is exactly in the front and 3 if its at an angle)
Im entirely new to this field and this is a small portion that will help me in course correction of an autonomous vehicle.


text:
Q: How to build custom route by adding taxonomies to URL ? ex: www.demo.com/communities/palo-alto/ I am trying to achieve this in WordPress, but no luck
Here '/communities' is custom Taxonomy of post type 'PAGE', '/Palo-alto' is term from communities taxonomy .

*

*I want user first to click on communities which will show all communities in grid, URL should be www.demo.com/communities/

*then after he can select one community from list, ex he select 'Palo-alto' , then URL should be www.demo.com/community/palo-alto/
BASICALLY here each community has its own home page , linked by communities taxonomy , like 'Palo-alto' has its own home page, 'las-Vegas' has its own, I want to show home page of particular community
problem is that I don't want .php at end of URL just www.demo.com/community/palo-alto/
Extra : after solving this issue I also want to show 'gallery', 'events', 'downloads' for that particular community ex; www.demo.com/community/palo-alto/events , www.demo.com/community/palo-alto/gallery


text:
Q: List of objects dissapears in the method i'm testing with Moq mocking and unittests in ASP.net Ok i'm having trouble to form a good qeustion so please don't flame me on that what i'm trying to do in my code is moqing a list of which i get 1 object in the list. This object is retrieved by a .find method in the moqed database. It however doesn't return values because somehow in the method the data dissappears and my Person object is left with null i'll post some screenshots that will hopefully explain what i'm trying to say together with the testing method i'm using:
the method:
[TestMethod]
        public void TestDetails()
        {
            Person test = new Person();
            test.ID = 1;
            test.City = "Eindhoven Area, Netherlands.";
            test.Name = "Marijn van Donkelaar";
            test.LearntSkillsAndLevelOfSkills = "Java:7, C#:4, SQL:4, PLSQL:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1";
            test.ProfileImage = "/Images/hollemar.jpg";
            test.PhoneNr = "0612345678";
            test.SkillsToLearn = "ASP.net:2, JAVA:2";
            test.Email = "fraylight@gmail.com";
            Person test1 = new Person();
            test1.ID = 2;
            test1.City = "Eindhoven Area, Netherlands.";
            test1.Name = "Jan Pietjes";
            test1.LearntSkillsAndLevelOfSkills = "Java:7, C#:4, SQL:4, PLSQL:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1";
            test1.ProfileImage = "/Images/hollemar.jpg";
            test1.PhoneNr = "0612345678";
            test1.SkillsToLearn = "ASP.net:2, JAVA:2";
            test1.Email = "fraylight@gmail.com";
            Person test2 = new Person();
            test2.ID = 3;
            test2.City = "Eindhoven Area, Netherlands.";
            test2.Name = "Jasmine Test";
            test2.LearntSkillsAndLevelOfSkills = "Java:7, C#:4, SQL:4, PLSQL:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1";
            test2.ProfileImage = "/Images/hollemar.jpg";
            test2.PhoneNr = "0612345678";
            test2.SkillsToLearn = "ASP.net:2, JAVA:2";
            test2.Email = "fraylight@gmail.com";

            var data = new List<Person> { test, test1, test2 }.AsQueryable();

            var mockSet = new Mock<DbSet<Person>>();
            mockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            var mockContext = new Mock<PersonDBContext>();

            mockContext.Setup(m => m.Persons).Returns(mockSet.Object);

            var service = new PersonController(mockContext.Object);

            ActionResult person = service.Details(1);

        }

is there any particular reason for this? because i honestly don't see it. i figured it might be because the moq data only thinks it has to be called once and then dissappears but i have no idea... and i did check the data and saw that the ID that is given (1) is added to 1 of the objects and it's also visible in that passed on list
thanks in advance,
Marijn

A: You're using one IEnumerator in your mocked object. This means that when your code is through enumerating over the items in it, it's at the end of the IEnumerator, and subsequent evaluation of the enumerator will yield 0 results (since it's at the end).
You should be able to fix this just by returning a new IEnumerator every time GetEnumerator is called:
mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator())
    .Returns(() => data.GetEnumerator());

Or, reuse the same enumerator, but reset it each time it's accessed:
var enumerator = data.GetEnumerator();

mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator())
    .Returns(() =>
    {
        enumerator.Reset();
        return enumerator;
    });


text:
Q: Spring Cloud Bus with rabbit - Application Failed to Start I'm triying to create a Config Server that listens to Git event and streams events to client. I followed several examples and also the documentation, but I cant manage to get application to start. I guess I have a problem with spring boot and cloud versions.
It is important to mention im running rabbitmq with docker.
This is my build.gradle
plugins {
    id 'org.springframework.boot' version '2.5.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.pal.pocs.config'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

ext {
    set('springCloudVersion', "2020.0.3")
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.cloud:spring-cloud-config-server'
    implementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

test {
    useJUnitPlatform()
}

And this is the exception Im getting:
***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.stream.binder.rabbit.RabbitMessageChannelBinder.createConsumerEndpoint(RabbitMessageChannelBinder.java:517)

The following method did not exist:

    org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.<init>(Lorg/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer;)V

The method's class, org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter, is available from the following locations:

    jar:file:/C:/Users/lambe/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-amqp/5.5.2/7195ed265b0f6c24e52c3ed84253f7974b2d5014/spring-integration-amqp-5.5.2.jar!/org/springframework/integration/amqp/inbound/AmqpInboundChannelAdapter.class

The class hierarchy was loaded from the following locations:

    org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter: file:/C:/Users/lambe/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-amqp/5.5.2/7195ed265b0f6c24e52c3ed84253f7974b2d5014/spring-integration-amqp-5.5.2.jar
    org.springframework.integration.endpoint.MessageProducerSupport: file:/C:/Users/lambe/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-core/5.5.2/d6822cb2d758d2a5d821879778c31120b4a3c86c/spring-integration-core-5.5.2.jar
    org.springframework.integration.endpoint.AbstractEndpoint: file:/C:/Users/lambe/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-core/5.5.2/d6822cb2d758d2a5d821879778c31120b4a3c86c/spring-integration-core-5.5.2.jar
    org.springframework.integration.context.IntegrationObjectSupport: file:/C:/Users/lambe/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-core/5.5.2/d6822cb2d758d2a5d821879778c31120b4a3c86c/spring-integration-core-5.5.2.jar
2

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter

Does anyone has a clue about where is the missconfiguration?

A: Well, I figured out
I turns out that Spring Cloud 2020.0.3 is supported by Spring Boot 2.4.6
So I downgraded to 2.4.6 and application started!
Hope it is helpfull for someone else


text:
Q: An aggregate may not appear in the set list of an UPDATE statement UPDATE [silverdb01].[dbo].[info]
SET [FM] = SUM(a.[MONDAY] - b.[QUOTA])
FROM  [silverdb01].[dbo].[info] a,  [silverdb01].[dbo].[quota] b
WHERE a.[WORK_TYPE]='IN' AND a.[NAME]='KUTHAY'

When I run this I get the following error:

An aggregate may not appear in the set list of an UPDATE statement.

Any ideas?

A: I am guessing that (as other's have pointed out) you don't really want a cartesian on this update so I have added an "id" to the query so you will have to do some modification but this might get you on the right path
;with temp as (
    select  a.id, SUM(a.pazartesi - b.kota) as newTotal
    from    [asgdb01].[dbo].[info] a join [asgdb01].[dbo].[kota] b
          on a.id = b.id
    where   a.work_type='in' and a.name='alp' )
update  a
set     fm = t.newTotal
from    [asgdb01].[dbo].[info] a join temp t on a.id = t.id


text:
Q: Magento 1.7 + onsite paypal Follwoing are the Paypal methods available in New Magento 1.7
PayPal All-in-One Payment Solutions  Accept and process credit cards and PayPal payments.
Paypal Payments Advanced (Includes Express Checkout)

*

*Basic Settings - PayPal Payments Advanced

*Basic Settings - PayPal Express Checkout

Paypal Payments Pro (Includes Express Checkout)

*

*Basic Settings - PayPal Payments Pro

*Basic Settings - PayPal Express Checkout

Paypal Payments Standard

*

*Basic Settings - PayPal Payments Standard

PayPal Payment Gateways
*Payflow Pro (Includes Express Checkout)*
 - Basic Settings - PayPal Payflow Pro
 - Basic Settings - PayPal Express Checkout
Payflow Link (Includes Express Checkout)

*

*Basic Settings - PayPal Payflow Link

*Basic Settings - PayPal Express Checkout

PayPal Express Checkout
 - Express Checkout
Now my question is which one of the above paypal method is useful , if i need to setup my paypal like , customer can enter the CC details on the Checkout and they will not be redirected to paypal .
Thanks

A: You can use Paypal Payflow Pro or Paypal Payflow Link.
These options will let your customers pay without leaving your website.


text:
Q: Neural Network Backpropagation? Can anyone recommend a website or give me a brief of how backpropagation is implemented in a NN? I understand the basic concept, but I'm unsure of how to go about writing the code.
Many of sources I've found simply show equations without giving any explanation of why they're doing it, and the variable names make it difficult to find out.
Example:
void bpnn_output_error(delta, target, output, nj, err)
double *delta, *target, *output, *err;
int nj;
{
  int j;
  double o, t, errsum;

  errsum = 0.0;
  for (j = 1; j <= nj; j++) {
    o = output[j];
    t = target[j];
    delta[j] = o * (1.0 - o) * (t - o);
    errsum += ABS(delta[j]);
  }
  *err = errsum;

}

In that example, can someone explain the purpose of
delta[j] = o * (1.0 - o) * (t - o);

Thanks.

A: The purpose of

delta[j] = o * (1.0 - o) * (t - o);

is to find the error of an output node in a backpropagation network.
o represents the output of the node, t is the expected value of output for the node.
The term, (o * (1.0 - o), is the derivative of a common transfer function used, the sigmoid function. (Other transfer functions are not uncommon, and would require a rewrite of the code that has the sigmoid first derivative instead. A mismatch between function and derivative would likely mean that training would not converge.) The node has an "activation" value that is fed through a transfer function to obtain the output o, like

o = f(activation)

The main thing is that backpropagation uses gradient descent, and the error gets backward-propagated by application of the Chain Rule. The problem is one of credit assignment, or blame if you will, for the hidden nodes whose output is not directly comparable to the expected value. We start with what is known and comparable, the output nodes. The error is taken to be proportional to the first derivative of the output times the raw error value between the expected output and actual output.
So more symbolically, we'd write that line as

delta[j] = f'(activation_j) * (t_j - o_j)

where f is your transfer function, and f' is the first derivative of it.
Further back in the hidden layers, the error at a node is its estimated contribution to the errors found at the next layer. So the deltas from the succeeding layer are multiplied by the connecting weights, and those products are summed. That sum is multiplied by the first derivative of the activation of the hidden node to get the delta for a hidden node, or

delta[j] = f'(activation_j) * Sum(delta[k] * w_jk)

where j now references a hidden node and k a node in a succeeding layer.

A: (t-o) is the error in the output of the network since t is the target output and o is the actual output. It is being stored in a normalized form in the delta array. The method used to normalize depends on the implementation and the o * ( 1.0 - o ) seems to be doing that (I could be wrong about that assumption).
This normalized error is accumulated for the entire training set to judge when the training is complete: usually when errsum is below some target threshold.

A: Actually, if you know the theory, the programs should be easy to understand. You can read the book and do some simple samples using a pencil to figure out the exact steps of propagation. This is a general principle for implementing numerical programs, you must know the very details in small cases.
If you know Matlab, I'd suggest you to read some Matlab source code (e.g. here), which is easier to understand than C.
For the code in your question, the names are quite self-explanatory, output may be the array of your prediction, target may be the array of training labels, delta is the error between prediction and true values, it also serves as the value to be updated into the weight vector.

A: Essentially, what backprop does is run the network on the training data, observe the output, then adjust the values of the nodes, going from the output nodes back to the input nodes iteratively.


text:
Q: How can I flush my ssh keys on power management activity? Using ssh-agent and private keys per the usual. Everything's working as normal.
My question regards best practices on flushing keys from ssh-add on activity like sleep, suspend, hibernate, etc. I thought about writing a simple wrapper around those commands, but then wondered if are they even called? Or does the kernel initiate this activity directly? Are the PM utilities strictly userland?
I would like this additional layer of security beyond locking my screen, etc. and was wondering if anyone else had solved this elegantly or has best practices to recommend. Thanks.

A: You might be able to have a user daemon listen for the status change over D-Bus. It looks like gnome-power-manager doesn't expose any signals for this, but you might be able to get something from hal or DeviceKit-power/upower.

A: I have a little pm script that run's user-defined scripts for each logged in user on suspend/hibernate, resume/thaw.  I've used this to kill or restart processes that don't behave well over suspend.  User's can create scripts in ~/.user-pm which are run in lexicographic order on suspend and reverse order on resume.  $1 has the pm operation name.
You could simply add a user-script that calls "ssh-add -D" on suspend/hibernate.  (you'll have to look up the SSH_AUTH_SOCK somewhere, but I assume you'd need that for any solution).
Here's the global pm hook:
> cat /etc/pm/sleep.d/10_run_user_parts
#!/bin/sh

USER_PM_DIR=".user-pm"

# foreach logged in user
for user in `users | grep -o "\S*" | sort -u`; do
    user_home=`getent passwd "${user}" | awk -F: '{print $6}'`

    # check user has a valid home-directory
    [ -d $user_home ] || continue

    user_pm_dir="$user_home/$USER_PM_DIR"
    # check for user-pm directory
    [ -d "$user_pm_dir" ] || continue

    # call run-parts as $user
    case "$1" in
        hibernate|suspend)
        su -c "run-parts --arg=\"$1\" \"${user_pm_dir}\"" "${user}"
        ;;
        thaw|resume)
        su -c "run-parts --reverse --arg=\"$1\" \"${user_pm_dir}\"" "${user}"
        ;;
        *) exit $NA ;;
    esac
done

I'm on ubuntu - this should work for debian too - otherwise, YMMV

A: If you add your key using the "-c" option to "ssh-add", it requires that you confirm every use.  This isn't as good as removing the key from your agent on suspend, if you also lock your screen it can have a similar effect, since the key use can't be confirmed until you login.
In the past I accomplished this key removal by running a simple script that woke up every few seconds and looked for the program that locks the screen, and if it was found it would do the "ssh-add -D".  Then once it went away, it would invoke the "ssh-add -c" again to ask me for the password.  I ended up switching to just relying on confirmation and screen locking when I suspend or leave the keyboard.

A: Thanks @Greg for your answer, I took the liberty of expanding on it to make it more "freedesktop" compliant, since pm-utils is a freedesktop.org project.
This script now will work in config.d, power.d, and sleep.d with a copy or a symlink.  It'll then look for scripts to run in ~/.config/pm/ using the same folder names (config.d, power.d, and sleep.d) as /etc/pm.
#!/bin/sh

scriptdir=`cd $(dirname $0) && pwd`
USER_PM_DIR=".config/pm/$(basename $scriptdir)"

# foreach logged in user
for user in `users | grep -o "\S*" | sort -u`; do
    user_home=`getent passwd "${user}" | awk -F: '{print $6}'`

    # check user has a valid home-directory
    [ -d $user_home ] || continue

    user_pm_dir="$user_home/$USER_PM_DIR"
    # check for user-pm directory
    [ -d "$user_pm_dir" ] || continue

    # call run-parts as $user
    case "$1" in
        hibernate|suspend)
        su -c "run-parts --arg=\"$1\" \"${user_pm_dir}\"" "${user}"
        ;;
        thaw|resume)
        su -c "run-parts --reverse --arg=\"$1\" \"${user_pm_dir}\"" "${user}"
        ;;
        *) exit $NA ;;
    esac
done

Then this is my script to remove all keys from the ssh-agent on suspend/hibernate, and re-add a key used for SparkleShare.  Just to be sure, it also checks for other ssh-agents and removes all the keys from them.
#!/bin/sh

case "$1" in
    hibernate|suspend)
        if [ ! -z $SSH_AUTH_SOCK ] && [ -r $SSH_AUTH_SOCK ]; then
            ssh-add -D
        fi

        for SSH_AUTH_SOCK in `find /tmp/ssh-*/agent.* -user $USER`; do
            SSH_AUTH_SOCK=$SSH_AUTH_SOCK /usr/bin/ssh-add -D
        done
        ;;
    thaw|resume)
        if [ ! -z $SSH_AUTH_SOCK ] && [ -r $SSH_AUTH_SOCK ]; then
            /usr/bin/ssh-add -t 0 ~/.config/sparkleshare/2011-03-21_14h15.key
        fi

        for SSH_AUTH_SOCK in `find /tmp/ssh-*/agent.* -user $USER`; do
            SSH_AUTH_SOCK=$SSH_AUTH_SOCK ssh-add -t 0 ~/.config/sparkleshare/2011-03-21_14h15.key
        done

        ;;
esac

A: This is another indirect solution that doesn't involve flushing registered identities/keys from the agent, but would locking the ssh-agent be just as useful (ssh-add -x)? I am unsure how secure this method would be (certainly no where near as secure as removing keys from the agent), however I assume this feature was implemented to offer the kind of added security you are looking for in this situation.


text:
Q: I can't delete marks in IdeaVim, the VIM PyCharm plugin Docs link: http://vimdoc.sourceforge.net/htmldoc/motion.html#:delmarks.
(I usually use offical VIM ressources since I can use pretty much every shortcut with the plugin.)
When I try to type ":delmarks markLetter" and hit enter, I get an Windows error sound that usually hints me that a key that's invalid and the marks aren't deleted.
I also heard that there's a config file for VIM, but i don't know how I can access it with the plugin.
Also, this is my first post lol


text:
Q: Decrypt difference integer values 1 and 2, using AesCrypto What causes the results below to be different?
--------------
IF Value = 1 :
--------------
String key1 = "123456";
String key2 = "654321";
String  x = AesCrypto.encrypt(key1, String.ValueOf(1));
String  y = AesCrypto.decrypt(key2, x);

Result --> y = ���8��VW&�S

--------------
IF Value = 2 :
--------------
String key1 = "123456";
String key2 = "654321";
String  x = AesCrypto.encrypt(key1, String.ValueOf(2));
String  y = AesCrypto.decrypt(key2, x);

Result --> y = null

why not produce a null value 1, is not equal to a value of 2? Although both failed to decrypt.

A: I don't know what library that is but when encrypting with one key, and decrypting with another I would expect undefined results.

A: *

*You must encrypt and decrypt with the same key when using AES encryption.

*The key is to short, AES supports only 128, 192 and 256 bit keys.

*The output of encryption is not a string, it is a series of 8-bit bytes.


text:
Q: I cant access my mysql database Hello im new to php and Mysql im stuck here anyone please help me.
Error message :
Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045): Access denied for user 'suren'@'localhost' (using password: YES) in /home/nanot142/public_html/index.php on line 7
Database connection failed : Access denied for user 'suren'@'localhost' (using password: YES)(Access denied for user 'suren'@'localhost' (using password: YES))

My code
<?php

$dbhost ="localhost";
$dbuser ="suren";
$dbpass ="password";
$dbname ="nano";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if(mysqli_connect_errno()) {
     die( "Database connection failed : " . mysqli_connect_error() . "(" . mysqli_connect_error() . ")" );}

?>

<?php

$query = "SELECT * FROM subjects";
$result = mysqli_query($connection, $query);

?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/layouts/header.php"); ?>

Manage Content

<?php include("includes/layouts/footer.php"); ?>
<?php mysqli_close($connection); ?>

A: Just try this..
$dbhost ="localhost";
$dbuser ="root";  //this is the username using to login localhost/phpmyadmin
$dbpass =""; //this is the password using to login localhost/phpmyadmin..if no                     //password leave it blank as given
$dbname ="test"; // this your database name

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

else{
    echo "success";
}


text:
Q: CLLocationManager not returning location after temporarily disabling in settings I temporarily disabled the location services, and the permissions for my app, so that I could test some code which dealt with the scenario where they're not available. Upon turning them on again, my location now can't be fetched, using this code:
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
CLLocation *currentLocation = locationManager.location;
[locationManager stopUpdatingLocation];

The locationManager.location is equal to nil after running this code.
I'm running this on an iPad running iOS 6.

A: Set the delegate for CLLocationManager
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
Try the delegates of CLLocationManager.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    self.currentLocation = newLocation;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // The location "unknown" error simply means the manager is currently unable to get the location.
    // We can ignore this error for the scenario of getting a single location fix, because we already have a
    // timeout that will stop the location manager to save power.
    if ([error code] != kCLErrorLocationUnknown) {
        [self stopUpdatingLocation:NSLocalizedString(@"Error", @"Error")];
    }
}


text:
Q: How can I call a method if my Ionic 2 range slider changes value I'm working on an Ionic 2 app and playing around with the range, as described here:
https://ionicframework.com/docs/v2/api/components/range/Range/
Call me crazy, but I can't find anywhere on google how the range component can call a method in my .ts class once the value has changed.
Something like a button, which goes like this:
<button ion-button (click)="myMethod($event)">

Of course, I need the value of the slider. In my case I defined it as follows:
  <ion-range min="0" max="10" color="danger">
    <ion-label range-left>0</ion-label>
    <ion-label range-right>10</ion-label>
  </ion-range>

Anyone got an idea?

A: The answer is right in the docs in the section output-events:

ionChange Expression to evaluate when the range value changes.

Use it as follows:
<ion-range min="0" max="10" color="danger" (ionChange)="myMethod($event)">
  <ion-label range-left>0</ion-label>
  <ion-label range-right>10</ion-label>
</ion-range>

A: Try in this way.

public myMethod(newRangeValue){
 console.log("Range :"+newRangeValue);
}
<ion-range min="0" max="10" color="danger" [(ngModel)]="modelRange" (ionChange)="myMethod($event)">
  <ion-label range-left>0</ion-label>
  <ion-label range-right>10</ion-label>
</ion-range>
New value : {{modelRange}}