text:
Q: compile error when using parenthesis in visual studio but pass in g++/clang++ I am developing cross-platform project, and I found something strange.
in visual studio, the following code will fail. But g++/clang++ in Linux environment can compile without error. In addition, I search for keyword on VS, but found nothing. Anyone the reason?
int main(){
  ({;});
  return 0;
}

error C2059: syntax error: '{'
error C2143: syntax error: missing ';' before '{'
error C2059: syntax error: ')'

Visual Studio version I have : Microsoft Visual Studio Professional 2019, Version 16.5.1

A: In visual studio, it is interpreted as vc++. In c++, ; marks end of statement. So your code
({;}); is exactly taken by compiler as 1  ({;  and 2 }); as a statement  which is synaxtically not correct. Check syntax of wrting code in c++. I dont know about g++/clang. Sorry there.

A: Compiling with clang++ using the -pedantic -Werror flags we see
dummy.cc:2:4: error: use of GNU statement expression extension [-Werror,-Wgnu-statement-expression]
  ({;});
   ^
1 error generated.

The MSVC compiler (cl, typically used by Visual Studio) does not support many non-standard extensions specific to GCC, including its statement expressions.
In this case, the block {;} is treated as a (useless) statement expression:
{
  /* nothing */
  ;
  /* nothing */
}

The outermost parentheses ((...)) are there to ensure the parser treats the block as an expression, rather than a more typical empty code block.


text:
Q: How To get skewness for every row on dataframe in R i try to get skewness for every row datafarme with
library(moments)
install.packages("FactoMineR")
data <-read.csv("data.csv",header=TRUE,sep=";",dec="."=)

My dataframe:
df <- structure(list(Marque = c("x1", "x2", "x3", "x4", "x5", "x6",
"x7", "x8", "x9"), V1 = c("2", "3", "1,5", "1,2", "1,9", "3,5",
"3,3", "4", "3,6"), V2 = c("2,4", "4", "3,4", "3,6", "1,6", "4,8",
"4,1", "3,5", "4,5"), V3 = c("1,7", "4,4", "3,8", "3,9", "3,4",
"4,5", "3,9", "4,3", "2,1"), V4 = c("2,3", "4,9", "4,7", "4,3",
"4", "4,6", "4,9", "2", "3,6"), V5 = c("3,3", "3,9", "2,3", "1,3",
"1,2", "3,9", "3,6", "3,3", "4")), class = "data.frame", row.names = c(NA,
-9L))

A: You may apply e1071::skewness over MARGIN=1 i.e. rows.
apply(df[-1], MARGIN=1, e1071::skewness)
# [1]  0.53353911 -0.25708728 -0.09059249 -0.23259728  0.26626966 -0.34683620
# [7]  0.44701696 -0.56946469 -0.61043085

If you really have commas as decimal separators, clean beforehand:
df[2:6] <- lapply(df[2:6], \(x) as.numeric(gsub(',', '.', x)))

df <- structure(list(Marque = c("x1", "x2", "x3", "x4", "x5", "x6",
"x7", "x8", "x9"), V1 = c(2, 3, 1.5, 1.2, 1.9, 3.5, 3.3, 4, 3.6
), V2 = c(2.4, 4, 3.4, 3.6, 1.6, 4.8, 4.1, 3.5, 4.5), V3 = c(1.7,
4.4, 3.8, 3.9, 3.4, 4.5, 3.9, 4.3, 2.1), V4 = c(2.3, 4.9, 4.7,
4.3, 4, 4.6, 4.9, 2, 3.6), V5 = c(3.3, 3.9, 2.3, 1.3, 1.2, 3.9,
3.6, 3.3, 4)), row.names = c(NA, -9L), class = "data.frame")

A: First change , to ..
Then convert to numeric.
Then use skewness function from moments package with c_across
to apply it to each row use rowwise() before:
library(dplyr)
library(moments)

df %>%
  mutate(across(-1, ~str_replace(., ',', '.'))) %>%
  type.convert(as.is = TRUE) %>%
  rowwise() %>%
  mutate(Skew = skewness(c_across(V1:V5)))

  Marque    V1    V2    V3    V4    V5   Skew
  <chr>  <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
1 x1       2     2.4   1.7   2.3   3.3  0.746
2 x2       3     4     4.4   4.9   3.9 -0.359
3 x3       1.5   3.4   3.8   4.7   2.3 -0.127
4 x4       1.2   3.6   3.9   4.3   1.3 -0.325
5 x5       1.9   1.6   3.4   4     1.2  0.372
6 x6       3.5   4.8   4.5   4.6   3.9 -0.485
7 x7       3.3   4.1   3.9   4.9   3.6  0.625
8 x8       4     3.5   4.3   2     3.3 -0.796
9 x9       3.6   4.5   2.1   3.6   4   -0.853

A: thanks a lot for your help
I did it differently, and it works
vect1= c(1:5)
for(x in vect1)
{
  print(x)
  skew_test = skewness(data[,x])
  print(skew_test)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate distance with Azure Maps API I need to calculate distance  between a set of origins and destinations like Bing Map Distance Matrix API, but in my case with Azure Map API. It's possible?

A: You'll have to manually pair each origin with each destination. You can use Azure Maps routing API to get the distance between an origin and a destination.

A: The Azure Maps platforms has a distance matrix service called Route Matrix: https://learn.microsoft.com/en-us/rest/api/maps/route/postroutematrixpreview


text:
Q: How to run Angular with https when by default it runs with http? By default if we run Angular applications they run with  http (e.g. on http://localhost:4200).
How to convert it from http to use https?

A: Simple fix is instead of running:
ng s -o

Run it with an extra attribute:
ng s -o ---ssl true

It will run on https://localhost:4200. But, if you have a .crt and a .key file, then add that attribute also.
You will see a browser which will start with https, although it will say "not secure" as a warning.

This is sufficient if you just wanna run on https and you don't care about the "not secure" message. If you do care, proceed with further instructions.
ng s -o ---ssl true --ssl-key <path to key file>  --ssl-cert <path to crt file>

or give relative path to .key and .crt file.
If you don't want to provide these attributes each time, or running for example a full NGINX server for angular, then add these attributes in angular.json or angular-cli.json depending upon angular version:
"serve":
 {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options":
      {
        "browserTarget": "ideationapp:build",
        "ssl": true,
        "sslKey": "ssl/server.key",
        "sslCert": "ssl/server.crt",
      }
}

sslkey and sslcert are not required if you don't have .key and .crt file.
Here, I assumed to have both files in a ssl dir where src. Now, runningonly ng s -o is sufficient to use the certificate via the angular.json file.

How to create temporary fix for localhost for only your machine or only for one users.
Requirements:

*

*Git bash (Download fom here)

Now go to Git bash and type this command one at a time
git clone https://github.com/RubenVermeulen/generate-trusted-ssl-certificate.git(cloned to local computer)
cd generate-trusted-ssl-certificate(Going to application path)
bash generate.sh(starting shell script wher we called openssl)

The cloned application use openssl(software library for applications that secure communications over computer networks against eavesdropping or need to identify the party at the other end) to generate .crt and .key file
It will create server.key and server.crt file.
Now click on server.crt
For OS X

*

*Double click on the certificate (server.crt)

*Select your desired keychain (login should suffice)

*Add the certificate

*Open Keychain Access if it isn't already open

*Select the keychain you chose earlier

*You should see the certificate localhost

*Double click on the certificate

*Expand Trust

*Select the option Always Trust in When using this certificate

*Close the certificate window

Windows 10

*

*Double click on the certificate (server.crt)

*Click on the button "Install Certificate …"

*Select whether you want to store it on user level or on machine level

*Click "Next"

*Select "Place all certificates in the following store"

*Click "Browse"

*Select "Trusted Root Certification Authorities"

*Click "Ok"

*Click "Next"

*Click "Finish"

*If you get a prompt, click "Yes"

The certificate is now installed.

Now store the certificate in a ssl directory.
Now use the command line to provde ssl key and certificate, or add these files to angular.json (or angular-cli.json, depending on your Angular version).
You will not see any "not secure", and it will show "secure" if you click on lock icon adjacent to address bar.
But, if you will run the application in other's laptop it will show "not secure"
as they have not installed the certificate (trusted).

A: To run angular application on https, do the following steps.
npm install -g angular-http-server
Cd Path to site & in dist folder (ClientApp/dist)
Angular-http-server -o
By default runs at 8080 port and with http
Specify a port using -p  e.g. Angular-http-server -p 44367 -o
To enable https, you have to manually specify the paths to your self-signed certificate using the --key and --cert flags
angular-http-server --https --key c:/localhost.key --cert c:/localhost.crt -p 44367 -o
OR
angular-http-server --https --key "Path where key stores" --cert "Path"
you probably see some error at this point if ssl not installed on local machine.
If OpenSSL is not installed on machine, download from below link
http://slproweb.com/download/Win64OpenSSL-1_1_0L.exe
Command to generate OpenSSL
openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout localhost.key -days 3560 -out localhost.crt -config certificate.cnf
below link is describing how to create a certificate, configuring CLI to use
https and Trusting the certificate on Windows.
https://medium.com/@richardr39/using-angular-cli-to-serve-over-https-locally-70dab07417c8

A: No fancy stuff needed, just add flag --https to your start script and its done.
Eg:
"scripts": {
    "start": "webpack-dev-server --content-base src/ --progress --inline --hot --https"
}


text:
Q: 4 equations with set of numbers I must make 1 addition (x+y=z), 1 subtraction (x-y=z), 1 multiplication (x*y=z), and 1 division (x/y=z) equation with the following numbers. All the numbers must be used to fill x, y, and z of each equation. x, y, and z can consist be 1, 2, or 3-digit numbers.
0-4 available
1-9 available
2-1 available
3-2 available
5-1 available
6-1 avilalble
7-0 available
8-1 available
9-1 available
Thanks!

A: There is no magic here, just guess and try.  I find $11+18=29, 11-6=5, 100*0=0,31/1=31$ as one of what must be many solutions.


text:
Q: Multiplication of lines of irrational length Suppose you are given two lines, each has length of an irrational number. How would one, using a straight-edge and compass, draw a line whose length is the product of the two given irrational numbers?
Edit: Yes, you are also given a unit line. But note that the irrational numbers are not necessarily square roots.

A: Hint: Use similar triangles and the identity $\dfrac{rs}{r} = \dfrac{s}{1}$. You have 3 of the terms and want the 4th.

A: Construct a segment $\overline{ACB}$ such that $AC = r$ and $CB = s$.
Construct a perpendicular through $C$, and mark off a point such that $CD = 1$.
Construct the circle $O$ through $A, B,$ and $D$.
Find the intersection point $E$ of $O$ and $\overline{CD}$.
Then by the power of a point theorem, $CE = rs$.


text:
Q: How do I manipulate algebraic fractions with an addition in the denominator? My lecturer has given me some notes to study and I can't follow one of the steps...
I need to find the inverse laplace transform of $$\frac3{s(0.1s+1)}\;.$$ The notes do the following:
$$L^{-1}\left[\frac3{s(0.1s+1)}\right] = L^{-1}\left[\frac1s-\frac{0.1}{0.1s+1}\right]$$
That's the step I don't follow.
It then goes on to equal $3-3e^{-10t}$. I have an inkling that the $3$ has been missed in the step above and then reapplied to the final answer? But even aside from the missing $3$, I still don't fully understand what he has done.
Any help would be appreciated!

A: You're right about the $3$; the righthand side of the second displayed line should read $$L^{-1}\left[\frac3{s(0.1s+1)}\right] = 3L^{-1}\left[\frac1s-\frac{0.1}{0.1s+1}\right]$$ or $$L^{-1}\left[\frac3{s(0.1s+1)}\right] = L^{-1}\left[\frac3s-\frac{0.3}{0.1s+1}\right]\;.$$
This simply uses the algebraic identity $$\frac1{s(0.1s+1)} = \frac1s-\frac{0.1}{0.1s+1}\;.\tag{1}$$ You can check this by performing the subtraction on the righthand side and verifying that you get the fraction on the lefthand side:
$$\begin{align*}
\frac1s-\frac{0.1}{0.1s+1}&=\frac1s\cdot\frac{0.1s+1}{0.1s+1}-\frac{0.1}{0.1s+1}\cdot\frac{s}s\\
&=\frac{0.1s+1}{s(0.1s+1)}-\frac{0.1s}{s(0.1s+1)}\\
&=\frac{0.1s+1-0.1s}{s(0.1s+1)}\\
&=\frac1{s(0.1s+1)}\;.
\end{align*}$$
The process of starting with the lefthand side of $(1)$ and finding the righthand side known as decomposing the lefthand side into partial fractions. Since you've tagged this (algebra-precalculus), I don't know whether you'll actually be required to perform such decompositions, or merely to be able to verify them. (I'm also a bit surprised to see inverse Laplace transforms in a precalculus setting.)

A: It's called partial fraction decomposition.
$$\rm \frac{1}{(as+b)(cs+d)}=\frac{\square}{as+b}+\frac{\triangle}{cs+d}$$
Setting up constraints on $\rm \square,\triangle$ to make the above true for $\rm s$ arbitrary,
$$\rm (c\square+a\triangle)s+(d\square+b\triangle)=0s+1 \implies\quad \begin{cases} \rm c\square+a\triangle=0 \\ \rm d\square+b\triangle=1\end{cases}$$
which is a linear system with solution
$$\rm \begin{pmatrix}\square \\ \triangle\end{pmatrix}=\begin{pmatrix}c & \rm a \\ \rm d & \rm b\end{pmatrix}^{-1}\begin{pmatrix}0 \\ 1\end{pmatrix}=\frac{1}{ad-bc}\begin{pmatrix}a \\ \rm -c\end{pmatrix}.$$
There is a much simpler case, though:
$$\rm \frac{1}{s(s+h)}=\frac{1}{h}\frac{h}{s(s+h)}=\frac{1}{h}\frac{(s+h)-s}{s(s+h)}=\frac{1}{h}\left(\frac{1}{s}-\frac{1}{s+h}\right).$$
Note that the most general form can be brought into this form:
$$\rm \frac{m}{(as+b)(cs+d)}=\frac{m}{ac(s+b/a)(s+d/c)}=\frac{m}{ac}\frac{1}{r(r+d/c-b/a)},$$
where $\rm r=s+b/a$. Thus we have
$$\rm \frac{3}{s(0.1s+1)}=\frac{30}{s(s+10)}=\frac{30}{10}\left(\frac{1}{s}-\frac{1}{s+10}\right)=\frac{3}{s}-\frac{3}{s+10}.$$
(There is indeed a factor of $3$ missing in the notes, apparently.)


text:
Q: CSS technique for a horizontal line to the left of text with text align centre I'm trying to achieve a solution where a horizontal line appears to the left of the text but the text remains centre aligned. Please see image below.
I've also added my mark-up below. I'm currently using Bootstrap 4.

About

Behind the brand // Meet the team

Our Work

Take a look at our marvelous creations

Services

Learn more about what we can do for you

Contact

Get in touch today. Let's make some magic

A: Use pseudo-elements to do so:
.sidebar-first-item {
  position: relative;
}

.sidebar-first-item:before {
  content: '';
  position: absolute;
  width: 45%;
  height: 5px;
  background-color: red;
  top: 50%;
  left: 0%;
}

CodePen: https://codepen.io/manaskhandelwal1/pen/xxEaQYg

A: First cleanup your html, a
 list may not have children other than
,


text:
Q: python dataframe counter on a column I column x in dataframe has only 0 and 1. I want to create variable y which starts counting zeros and resets when when 1 comes in x. I'm getting an error "The truth value of a Series is ambiguous."
count=1
countList=[0]

for x in df['x']:
if  df['x'] == 0:
    count = count + 1
    df['y']= count
else:
    df['y'] = 1
    count = 1

A: First dont loop in pandas, because slow, if exist some vectorized solution.
I think need count consecutive 0 values:
df = pd.DataFrame({'x':[1,0,0,1,1,0,1,0,0,0,1,1,0,0,0,0,1]})

a = df['x'].eq(0)
b = a.cumsum()
df['y'] = (b-b.mask(a).ffill().fillna(0).astype(int))
print (df)

    x  y
0   1  0
1   0  1
2   0  2
3   1  0
4   1  0
5   0  1
6   1  0
7   0  1
8   0  2
9   0  3
10  1  0
11  1  0
12  0  1
13  0  2
14  0  3
15  0  4
16  1  0

Detail + explanation:
#compare by zero
a = df['x'].eq(0)
#cumulative sum of mask
b = a.cumsum()
#replace Trues to NaNs
c = b.mask(a)
#forward fill NaNs
d = b.mask(a).ffill()
#First NaNs to 0 and cast to integers
e = b.mask(a).ffill().fillna(0).astype(int)
#subtract from cumulative sum Series
y = b - e
df = pd.concat([df['x'], a, b, c, d, e, y], axis=1, keys=('x','a','b','c','d','e', 'y'))
print (df)
    x      a   b     c     d   e  y
0   0   True   1   NaN   NaN   0  1
1   0   True   2   NaN   NaN   0  2
2   0   True   3   NaN   NaN   0  3
3   1  False   3   3.0   3.0   3  0
4   1  False   3   3.0   3.0   3  0
5   0   True   4   NaN   3.0   3  1
6   1  False   4   4.0   4.0   4  0
7   0   True   5   NaN   4.0   4  1
8   0   True   6   NaN   4.0   4  2
9   0   True   7   NaN   4.0   4  3
10  1  False   7   7.0   7.0   7  0
11  1  False   7   7.0   7.0   7  0
12  0   True   8   NaN   7.0   7  1
13  0   True   9   NaN   7.0   7  2
14  0   True  10   NaN   7.0   7  3
15  0   True  11   NaN   7.0   7  4
16  1  False  11  11.0  11.0  11  0


text:
Q: Is every Quantum Computer working with entangled particles? Is every Quantum Computer working with entangled particles?
I ask this question, because entangled particles are not allways local.
I read that a Quantum Gate can be used to concatenate quantum particles.
Logically I follow out of my knowlegde till now (I am no Phisicst), that a Quantum Computer can have more then one gates with entangled particles. Is that OK?

A: Yes.
The alternative would be to have a single monolithic system with a huge number of internal states where you implemented the computation, which is about as bad as it gets in terms of scalability. What we do, instead, is have a number of simpler subsystems (i.e. the qubits) that we put together to do the quantum computation, where the mechanism for 'putting together' is nothing more and nothing less than entanglement.


text:
Q: Can latexdiff be used for mathematics documents? I've been pulling my hair out trying to get latexdiff to work with a mathematics document. It produces output that latex can't compile if one of the files is this:
\documentclass{amsart}
\begin{document}
    \begin{equation} \label{eq:Psi-action}
        2=1+1
    \end{equation}
\end{document}

and the other is this:
\documentclass{amsart}
\begin{document}
    yo
\end{document}

But I think it chokes on other things as well. Am I doing something wrong? Is anyone able to use latexdiff for mathematics documents more than a few lines long? If anyone is able to use it by making some easy changes to their LaTeX code, are there general guidelines about what kind of LaTeX code to avoid?
Update 1: It appears that latexdiff doesn't like things like \big(. You can sort of get around this by changing every \big( to a \left(.
Update 2: Here is another pair of files that breaks it:
\documentclass{amsart}
\begin{document}
    \begin{equation*}
        X_{[1],n}
    \end{equation*}
\end{document}

and
\documentclass{amsart}
\begin{document}
    \begin{equation*}
        [1]X_{n}
    \end{equation*}
\end{document}

I had only a few such examples and was able to get around them by just commenting out the offending code, but it would be nice to know if there are any rules of thumb to avoid having to worry about it in the first place, like Andrew's helpful comment about Perl and line breaks.

A: I can get the example that you gave to compile by moving the \label{eq:Psi-action} on to a line by itself:
\documentclass{amsart}
\begin{document}
    \begin{equation}
     \label{eq:Psi-action}
        2=1+1
    \end{equation}
\end{document}

Without that, what seemed to be happening was that it was recognising the \end{equation} as the end of a mathematics environment that was in one file but not the other, so it marked it up as \end{MATHMODE}.  But for some reason it didn't spot the beginning of that environment so there was no corresponding \begin{MATHMODE}.  Putting the \label on the new line seems to be enough to make it recognise the \begin{equation} once again.
Whilst doing a pretty fair job, latexdiff doesn't interpret TeX documents in the same way that TeX does.  In particular, since latexdiff is a perl program, I imagine it works on a line-by-line basis, so new-lines are more important to latexdiff than to TeX.  So if there are other things that are causing it to complain, try adding more new-lines to separate things so that latexdiff recognises them as separate.
And, of course, if it gets stuck on something else, ask again!


text:
Q: Raw image Editing, Rotating and Saving back as Raw I am working on bayer raw(.raw format) image domain where I need to edit the pixels according to my needs(applying affine matrix) and save them back .raw format.so There are two sub-problems.

*

*I am able to edit pixels but can save them back as .raw
I am using a robust library called rawpy that allows me to read pixel values as numpy array, while I try to save them back I am unable to persist the value

rawImage = rawpy.imread('Filename.raw')   // this gives a rawpy object
rawData = rawImage.raw_image //this gives pixels as numpy array
.
.//some manipulations performed on rawData,  still a numpy array
.
imageio.imsave('newRaw.raw', rawData)

This doesn't work,  throws error unknown file type. Is there a way to save such files in .raw format.
Note: I have tried this as well:-

rawImageManipulated = rawImage
rawImageManipulated.raw_image[:] = rawData[:] //this copies the new
data onto the rawpy object but does not save or persists the values
assigned.

*Rotating a bayer image - I know rawpy does not handle this, nor does any other API or Library acc to my knowledge. The existing image rotation Apis of opencv and pillow alter the sub-pixels while rotating. How do I come to know? After a series of small rotations(say,30 degrees of rotation 12 times) when I get back to a 360 degree of rotation the sub-pixels are not the same when compared using a hex editor.

Are there any solutions to these issues? Am I going in the wrong direction? Could you please guide me on this. I am currently using python i am open to solutions in any language or stack. Thanks

A: As far as I know, no library is able to rotate an image directly in the Bayer pattern format (if that's what you mean), for good reasons. Instead you need to convert to RGB, and back later. (If you try to process the Bayer pattern image as if it was just a grayscale bitmap, the result of rotation will be a disaster.)
Due to numerical issues, accumulating rotations spoils the image and you will never get the original after a full turn. To minimize the loss, perform all rotations from the original, with increasing angles.


text:
Q: My PHP Session logs in the world I've encountered a weird problem with PHP Sessions that I'm not sure how to fix. I know that there's a problem with my code, but Googling the matter and searching for answers her yielded no results...possibly because I have no idea how to make keywords for this!
Basically I'm making a login script to learn PHP better, and so I encountered sessions. I got them working somewhat, but trouble is that when I successfully log in, the session that's created logs the world into my account no matter from where or with what browser is used.
I'm pretty sure I'm missing a step, so if anyone could help me figure that out, that'd be great!
Presently I have this on top of every page dealing with sessions:
session_id("tenaarFeiriSess"); // Define the session name.
@session_start();

error_reporting(E_ALL);

The actual login applies the session like this, where $usr = username:
$_SESSION['loggedin'] = $usr;

What am I missing?

A: The problem is that you give everyone the exact same session with session_id().  PHP automatically sets a session id for everyone so this is really unnecessary.  Once you remove this, it should work.


text:
Q: ANTLR4 throw exception and exit if any error occurs using java I am having custom function written like this.Functionconcat(Functionadd(1,2),1).
Below is the grammer I am using.
Now I have changed the grammer it is working and checking the return type for param if function exists:
grammar FunctionGrammer;

INT
 : [0-9]+
 ;

ID
 : [a-zA-Z_] [a-zA-Z_0-9]*
 ;

expr : add;
string : 'Functionadd(' INT ',' INT ')' ;
add : 'Functionadd(' INT ',' INT ')' ;
concat : 'Functionconcat(' (string|INT )','INT ')';

Below is the test method:
public static void main(String[] args) {
    try {
        CodePointCharStream input = CharStreams.fromString("Functionconcat(Functionadd(m,2),1)");
        FunctionGrammerLexer lexer = new FunctionGrammerLexer(input);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        FunctionGrammerParser parser = new FunctionGrammerParser(tokenStream);
        parser.setErrorHandler(new BailErrorStrategy());
        ParseTree tree = parser.concat();
        FunctionCompilerImpl visitor = new FunctionCompilerImpl();
        visitor.visit(tree);
    } catch (ParseCancellationException e) {
        e.printStackTrace();
    }

    }

It is throwing exception but how can I give meaningful exception like parameter/parameter datatype mismatch exception or function name mismatch exception.
visitor impl:
public class FunctionCompilerImpl extends FunctionGrammerBaseVisitor<String>{

    @Override
    public String visitConcat(FunctionGrammerParser.ConcatContext ctx) {
        super.visitConcat(ctx);
        System.out.println("==================="+ctx);
        return null;
    }

}

But vistor is not printing System.out.println("==================="+ctx);.


text:
Q: Efficient Algorithm for Matrix Version of Waring's Problem Given an $n \times n$ matrix $A$ with entries in a commutative and associative ring with $1$ (say $Z[x_{1},\dots,x_{n^{2}}]$), the following paper guarantees existence of seven $B_{i}$s such that $A = \sum_{i=1}^{7}B_{i}^{k}$  with $k \le n$.
http://www.tandfonline.com/doi/abs/10.1080/03081088708817831
Is there an explicit algorithm to find the seven $B_{i}$ matrices?

A: The result mentioned above is Waring's problem for matrices (respectively for algebraic
number fields). The result is:
Theorem (Katre, Kuhle 1990): Let $R$ be an order in an algebraic number field $K$.
Let $n\ge k \ge 2$. Then every $n\times n$ matrix over $R$ is a sum of $k$-th powers
if and only if it is the sum of seven $k$-th powers if and only if $(k, disc (R)) = 1$.
If this is true, then the question is if the seven matrices can be constructed explicitly.
For the case $k=n=2$ and $R=\mathbb{Z}$ this seems to be the case (article of Newman
 "Sums of squares of matrices"), by constructing certain companion matrices to characteristic polynomials: every integral
$2 \times 2$ matrix is the sum of at most $3$ integral squares. The proof for the general
case however uses an argument of the form "every $n\times n$-matrix is a sum of $k$-th powers
in $M_n(R)$ if every $m\times m$-matrix is a sum of $k$-th powers in $M_m(R)$ for
$n\ge m\ge 1$ and $k\ge 2$", which does not seem to be constructive.


text:
Q: True browser support of get/set/hasAttribute() etc I recently came across a similar problem when researching the readyState property of the document object, where the readystatechange event was supported everywhere but the readyState property itself wasn't supported properly until ~IE9.
What I found out was that document.readyState would actually exist in these earlier browsers, but not be implemented correctly when tested (except for readyState === 'complete'), but this is not in the documentation.
On MDN it shows that Element.getAttribute() is not supported fully until Chrome 29, Firefox 23 and Safari 6, which is significant as previous editions of these browsers have a combined 1.33% market share.
I know for a fact via testing in Browserstack that the .getAttribute method exists in Safari 4, 5.1, and Chrome 10, but it's not currently possible for me to test any earlier than that, and I don't know if these earlier browsers' implementations of getAttribute are buggy in ways that I haven't found out yet. For instance, getAttribute('style') returns an object in IE6.
There is also not a real workaround to these methods that I know of.
In general, I want to know if I can trust a property or method to both exist and to be implemented properly from version 1 of a browser, not version 29, especially where the DOM is concerned. Especially in Safari's case, where you would think based on MDN that version 5.1 supports practically nothing at all.
Here for instance, it says that following properties are essentially supported everywhere, but I need to know if the standard implementations of these methods are also supported without errors. (Which they clearly don't really, since jQuery 1.12 exists, so I'm back to square one).
And QuirksMode's Compat Tables, which CanIUse seems to be based on, seem to have been tested on browser versions later than version 1, which is only partly helpful.
HeLp!


text:
Q: Make TextMate run php from a different binary, not the original php I work with php and postgre, and since the stock php doesn't come with postgre I had to install a different php version.
So I installed php5 from this website: http://php-osx.liip.ch
It's a quick install, just downloaded php5 and its modules and put them in a different directory, now everything works, except the TextMate's "php run".
I couldn't find where TextMate makes the call to the php and I wanna change it, any ideas?
Thanks.

A: Under preferences, go into variables and update (or create) TM_PHP to point to your desired executable. E.g. I have /opt/local/bin/php because I'm using MacPorts.

A: In my case it was /usr/local/php5/bin/php whereas 'php5' is an alias that points to the liip installation dir /usr/local/php5-5.3.29-20141019-211753.
And by the way it solved my textmate line output on syntax checking on osx 10.12. Thanks a lot.


text:
Q: lwjgl And jars, not running i'm a little stuck. I'm doing a little game in java, it's my first time, and i'm using sprites. I finally made it blink jaja, it's not much, but hey! I'm starting. the thing is that i'm using Netbeans 7.3 Ide, and my code runs. There's no problem. The problem comes when i export it as a jar. I export it and i get no error whatsoever, and the jar is created, but, i double click it, and nothing happens. Like, at all. Noting. I run it in Netbeans, and it runs. Any help would be really apretiated. Thanks in advice!

A: I had trouble with this too, at first.
Three things you're going to need to make it work properly:
1) The MANIFEST.MF - This is something that people don't think about much. The below code, make sure it is in the META-INF/MANIFEST.MF inside your .jar
Manifest-Version: 1.0
Class-Path: lib/lwjgl.jar lib/lwjgl_util.jar lib/jinput.jar
Main-Class: <whatever your main method is in>

2) Alongside your jar, in whatever folder it is in, make a folder called 'lib'. Inside it, put all of the lwjgl jars that you are using. If you are using anything more than lwjgl.jar, lwjgl_util.jar, and jinput.jar, add it to the Class-Path variable in your MENIFEST.MF. Also, inside the lib folder, make a folder called 'natives' and take all of the native LWJGL files and put them inside that folder. That will be important for Step 3.
3) Add the following line of code early in your main method
System.setProperty("org.lwjgl.librarypath", new File("lib/natives").getAbsolutePath());

This is a "secret switch" used to enable the native files. It's smart, and only uses the natives for the operating system that the code is being run on, so don't worry about having all of the native files in the same directory.
And there you go. Export your Jar again with all of these things and you should be able to just simply double-click on it and make it launch!


text:
Q: cygwin1.dll missing when compiling c++ with g++ I'm using cygwin and when I'm compiling hello world with gcc somehow the compiler doesn't understand about using std namespaces (some of them are missing), but when I compile with g++ yes they work. But when I click on the helloworld.exe it says that cygwin1.dll is missing.
Is there anything can I do?

A: "gcc" is the C compiler - and namespaces are not a part of the C language. "g++" is the C++ compiler, so it will understand namespaces.
Try the no-cygwin option when compiling to produce executables that depend on the mingw runtime instead of the cygwin runtime (which, AFAIR, introduces licencing issues).

A: cygwin1.dll errors could indicate a registry problem, a virus or malware.
Don't download cygwin1.dll. It can be an inappropriate version, or just unsafe.
Try to reinstall cygwin (or try mingw32).


text:
Q: Cannot attach a file as database in child solution of partitioned solutions I recently started working on partitioned solutions using MVC 4 I set up my solution using Structuring Solutions and Projects and Adding an existing Visual Studio solution to another solution. My System is all set up, can build and i have enable migrations on both solutions. Each solution has 4 projects (Domain, Data, UnitTests and WebUI), the child solution has references from master solution. the data layer contains all the repositories and DbContext classes. And each solution has its own connection string, hence i intend to have separate databases for each of the solutions added to the system.
I was trying to update my databases in the Package Manager Console using Update Database -Verbose This worked for the master solution but has not worked with the child solution. Migration files are in the Data layer.
Note: I run Update-Database -Verbose
Using StartUp project Master.WebUI and
Using NuGet project Master.Data (Master Solution)
Using StartUp project Child.WebUI and
Using NuGet project Child.Data (Child Solution)
What should i do to make this work?

A: At first I could't solve this, so what i did was recreate the Child solution and make the first Updat-Database before adding it to Master Solution.
Now, i think it was just a matter of checking to make sure that the Database does not exist anywhere else. So deleting your database from App_Data, Server Explorer, SQL Server Object Explorer would work in an case when an .mdf file cannot be attached as a database


text:
Q: How Can I calculate a math equation from a text box that formulates like an excel box with an equal sign I have a php site that has text boxes in a form. I want to be able to type in the text box "=4*6" or "=5/12*30" with out the quotes and have it calculate the formula in the box. I know how to call a onchange on the text box to a javascirpt function but I am unsure how to have it read the formula. I have googled math for javascript and php and i have not found anything other than predetermined numbers and equation symbols. Any Help Appreciated.
Thank You

A: I started to work on this idea:
http://jsbin.com/sebeke/1/edit
I was borrowing the seconds part of the idea from this answer: split a mathematical expression on operators in Javascript
I think once you had an array of the numbers and operators, like in the examples, you might be able to build an order of operations (Remeber please excuse my dear aunt sally..) type of switch case function, that would recursively loop through the array, looking first for the action to preform, and then perform the actions on the surrounding numbers to your array.
sudo code would be:
if (arrayValues[i]) == '*'{
 arrayValues[i-1] * arrayValues[i+1];
 arraryvalues[i-1] = results;
 //then pop off the next two items in the array.
//Then go back through the array
}

This was my first idea regarding this.

A: For simple calculations you can do it realy easy with AngularJS using $eval().
In your input field add ng-model="formula" and then display the result with {{$eval(formula.substring(1))}}.
Here is an example code:
Type formula:
<input type="text" ng-model="formula" placeholder="=1+1">

result: {{$eval(formula.substring(1))}}

You can check it in action here : enter link description here

If you want to use plain JavaScript you ca do it by using eval().
If the value of your input is in variable formula starting with = sign, the result can be obtained by eval(formula.substring(1)), but note that the standard eval() is less secure than angular's $eval().


text:
Q: MAX() as a filtering clause for a LEFT JOIN, Are there any alternatives? It seems to me that there is another option for this query, but I cannot pinpoint exactly what is that option:
@Query("" +
        "SELECT " +
        "... not really important... " +
        "FROM (" +
        "SELECT ect.* " +
        "FROM element_constant_table ect " +
        "WHERE book_parent_id = :bookId AND availability = 1" +
        ") ect1 " +
        "LEFT JOIN " +
        "element_version_table evt " +
        "ON (" +
            "SELECT evt.element_parent_id " +
            "WHERE " +
            "evt.time = (" +
                "SELECT MAX(evt2.time) " +
                "FROM element_version_table evt2 " +
                "WHERE evt2.element_parent_id = evt.element_parent_id" +
            ") " +
        ") = ect1.element_id" +
        "")
public abstract LiveData<List<Element>> getLatestElementsAt(int bookId);

For readability:
        SELECT
        ... not really important...
        FROM (
        SELECT ect.*
        FROM element_constant_table ect
        WHERE book_parent_id = :bookId AND availability = 1
        ) ect1
        LEFT JOIN
        element_version_table evt
        ON (
            SELECT evt.element_parent_id
            WHERE
            evt.time = (
                SELECT MAX(evt2.time)
                FROM element_version_table evt2
                WHERE evt2.element_parent_id = evt.element_parent_id
            )
        ) = ect1.element_id

The MAX() function is forcing a new instantiation of the whole element_version_table for each row found on element_constant_table.
I was aware that something like this may happen so I always try to filter the table before it reaches the LEFT JOIN, in this case with the clause "WHERE book_parent_id = :bookId AND availability = 1"
There is no way to filter the LEFT TABLE and make it coincide with its corresponding key on the RIGHT TABLE before the ON clause, and so the WHERE needs to be placed there.
The problem is that if instead of using the MAX(), I use a simple ORDER BY evt.time DESC LIMIT 1 inside the ON clause the compiler tells me that there is no evt.time field (I assume that it does not exist YET).
So my conclusions to this are:
a) An ORDER BY requires for the table to be instantiated to its full length (It does not happens during the process of row location).
b) The ON clause happens BEFORE the LEFT TABLE reaches instantiation (what I assume is) to it's full length.
Are my conclusions about the order of clause execution correct?
How much of a burden may this query be on an extensive Database? and
What would a better option be?

A: Please use below sql query to retrieve live data of book in your code:
     SELECT
    ... not really important...
    FROM element_constant_table ect
    LEFT JOIN
    (SELECT evt.*, ROW_NUMBER() OVER (PARTITION BY evt.element_parent_id ORDER BY evt.time DESC) as seqnum
    from element_version_table evt) evt_final on ect.element_id = evt_final.element_parent_id and evt_final.seqnum=1
    where ect.book_parent_id = :bookId AND ect.availability = 1

I am finding here latest book record from "element_version_table" if exists.

A: SQLite window function ROW_NUMBER() can be a solution to your problem.
https://www.sqlitetutorial.net/sqlite-window-functions/sqlite-row_number/
You didn't provide full details of your tables. But, depending on size of your element_version table and query performance, you can try:
SELECT
    ... not really important...  FROM
    (SELECT ect.*
    FROM element_constant_table ect
    WHERE book_parent_id=:bookId AND availability=1
    ) ect1

    LEFT JOIN

    (SELECT t.*
     FROM
        (SELECT
            evt.*,
            ROW_NUMBER() OVER (PARTITION BY element_parent_id ORDER BY evt.time DESC) rn
         FROM element_version_table evt) t
     WHERE t.rn = 1
    ) evt1

    ON ect1.element_id = evt1.element_parent_id

or
SELECT t.*
FROM
    (SELECT
        ... not really important...,
        ROW_NUMBER() OVER (PARTITION BY ect1.element_id, evt1.element_parent_id ORDER BY evt1.time DESC) rn

    FROM
        (SELECT ect.*
        FROM element_constant_table ect
        WHERE book_parent_id=:bookId AND availability=1
        ) ect1

        LEFT JOIN element_version_table evt1
        ON ect1.element_id = evt1.element_parent_id
    ) t
WHERE t.rn = 1

A: This solution would be for SQLite versions < 3.25.0
Thanks to user @armamut That gave the original idea and this other question from 7 years ago MySQL order by before group by.
@Query("" +
        "SELECT " +
        ... not really important ...
        "FROM (" +
            "SELECT ect.* " +
            "FROM element_constant_table ect " +
            "WHERE book_parent_id = :bookId AND availability = 1" +
        ") ect1 " +
        "LEFT JOIN " +
        "(" +
            "SELECT " +
                "evt.*," +
                "MAX(evt.time) " +
            "FROM element_version_table evt " +
            "GROUP BY evt.element_parent_id" +
        ") evt1 " +
        "ON evt1.element_parent_id = ect1.element_id" +
        "")
public abstract LiveData<List<Element>> getLatestElementsAt(int bookId);

For readability:
        SELECT
        ... not really important ...
        FROM (
            SELECT ect.*
            FROM element_constant_table ect
            WHERE book_parent_id = :bookId AND availability = 1
        ) ect1
        LEFT JOIN
        (
            SELECT
                evt.*,
                MAX(evt.time)
            FROM element_version_table evt
            GROUP BY evt.element_parent_id
        ) evt1
        ON evt1.element_parent_id = ect1.element_id


text:
Q: GtkTreeView alternate row color I can't set the alternate row color of a TreeView, I don't know why doesn't works.
This the code
MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "user";
    const char* passwd = "passwd";
    const char* database = "dbname";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);

    /*Glib::RefPtr<Gtk::StyleContext> context = m_TreeView1->get_style_context();
context->add_class("treeview");
*/

    Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;

    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

    }

    m_TreeView1->append_column("InqID", m_Columns.m_col_inqid);
    m_TreeView1->append_column("Cognome e nome", m_Columns.m_col_cognomenome);
    //m_TreeView1->get_column(1)->set_expand(true);
    m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

    mysql_free_result(res);
    mysql_close(connection);

}

And this the css, that is correctly loaded. I set the style class of the TreeView (treeview) in glade file.
.treeview row:nth-child(even)
{
    background-color: #ff0000;
}
.treeview row:nth-child(odd)
{
    background-color: #000000;
}

What's wrong? I tried too to set the style class by code (commented rows) but does't change.
Thanks in advance for an help!
update
I put my updated code, what's I'm wrong?
Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    textRenderer->property_editable() = false;
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_col_inqid);
    m_TreeView1->append_column(*col);
while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);

        row[m_Columns.m_col_inqid] = Gdk::Color("#CCCCCC");

    }

thanks in advance!

A: If you want to set the background color of a row you can use
cell-background-gdk
You can read more about it here

A: Somebody else had already the same problem:
Probably you could do your a function where you grab each cell of a row and use
the already mentioned function or do it on cell creation as here:
Row Background Color GtkTreeView Widget
Watch out, he just used the wrong function for the color:

Thanks @ivo s, I was using the wrong property, I needed
  "cell-background-gdk" and not "background-gdk". Thanks for the help.

Use cell-background-rgba function instead of before mentioned cell-background-gdk cause it is deprecated and will be removed sooner or later.

A: so, now it works...this is the complete code in case of somebody have the same problem.
Thanks a lot for those help me!
the model:
class MainWindow : public Gtk::ApplicationWindow
{
    public:
        MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade);
        virtual ~MainWindow();
        MYSQL* connection;
    protected:
        Glib::RefPtr<Gtk::Builder> refBuilder;

        class ModelColumns : public Gtk::TreeModel::ColumnRecord
        {
            public:

            ModelColumns()
            {
                add(m_col_inqid);
                add(m_col_cognomenome);
                add(m_col_stabile);
                add(m_col_mese);
                add(m_col_anno);
                add(m_col_posteggiopagato);
                add(m_col_affittopagato);
                add(m_col_riscaldamentopagato);
                add(m_col_pagatoil);
                add(m_col_stato);
                add(m_col_osservazioni);
                add(m_col_traslocato);
                add(m_col_diversi);
                add(m_col_affitto);
                add(m_col_posteggio);
                add(m_col_riscaldamento);
                add(m_coloreriga);
            }

            Gtk::TreeModelColumn<int> m_col_inqid;
            Gtk::TreeModelColumn<std::string> m_col_cognomenome;
            Gtk::TreeModelColumn<std::string> m_col_stabile;
            Gtk::TreeModelColumn<int> m_col_mese;
            Gtk::TreeModelColumn<int> m_col_anno;
            Gtk::TreeModelColumn<double> m_col_posteggiopagato;
            Gtk::TreeModelColumn<double> m_col_affittopagato;
            Gtk::TreeModelColumn<double> m_col_riscaldamentopagato;
            Gtk::TreeModelColumn<std::string> m_col_pagatoil;
            Gtk::TreeModelColumn<std::string> m_col_stato;
            Gtk::TreeModelColumn<std::string> m_col_osservazioni;
            Gtk::TreeModelColumn<std::string> m_col_traslocato;
            Gtk::TreeModelColumn<double> m_col_diversi;
            Gtk::TreeModelColumn<double> m_col_affitto;
            Gtk::TreeModelColumn<double> m_col_posteggio;
            Gtk::TreeModelColumn<double> m_col_riscaldamento;
            Gtk::TreeModelColumn<Gdk::RGBA> m_coloreriga;

        };

        ModelColumns m_Columns;
        Gtk::TreeView* m_TreeView1;
        Glib::RefPtr<Gtk::ListStore> m_refTreeModel;

};

the main:
MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    //cssProvider->load_from_data(cssProvider, ".treeview row:nth-child(even){  background-color: #ff0000; } .treeview row:nth-child(odd){ background-color: #000000; }", -1, NULL);
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "root";
    const char* passwd = "";
    const char* database = "";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    //m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::on_button_quit) );

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);
Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;
Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);

    textRenderer = manage(new Gtk::CellRendererText());
    col = manage(new Gtk::TreeViewColumn("Cognome e nome", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);
m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

 int i=0;
    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

        if(i%2 == 0)
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#ff0000");
        else
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#cccccc");
        i++;
    }

    mysql_free_result(res);
    mysql_close(connection);

}


text:
Q: Combination regex letters and digits I'm really stuck on this. How do I do a combination of letters and digits? If it contains digits, that's will be invalid.
I've tried this. This doesn't work...
(^[a-z])+(^[0-9])+

example:
abcd (valid)
abcd123 (invalid)
123abcd (invalid)

A: This will treat a string with digits as invalid:
^\D*$

\D matches everything that isn't a digit.

A: You're explicitly saying "starts with one or more lowercase letters". Why would it work on a string that starts with numbers?
If you want it to work with either, combine using or |:
(^[a-z]|[0-9])+

Example here: http://regex101.com/r/eO7tD6/1
Also, if you're wanting to match the character sequence, you'll want the + inside the parens.


text:
Q: T-sql TRIPLE_DES ENCRYPTION - now I need to decrypt the output text file in c# How do I decrypt triple des encryption the file  in c#. Which namespace?
This is the output file:

FirstCol  secondCol  EncryptSecondCol
1         value      00E35587C2CCEF4683B98686ED0483480100000054ABDFFB520111778B477223D1CD853F3CE33B4DD96C0F96

The sql that I used to create the encrypted file below:

--CREATE MASTER KEY
--ENCRYPTION BY PASSWORD = 'jjvc1234%';
--GO

---- Create a test certificate
--CREATE CERTIFICATE Tasc
--   WITH SUBJECT = 'Tasc Encryption',
--   EXPIRY_DATE = '20301231';
--GO

--CREATE SYMMETRIC KEY TestTableKey
--WITH ALGORITHM = TRIPLE_DES ENCRYPTION
--BY CERTIFICATE Tasc
--GO

Declare @TestTable table(FirstCol varchar(8),secondCol varchar(100),EncryptSecondCol VARBINARY(256))
insert into @TestTable
values('1','value',null);

--select * from @TestTable

OPEN SYMMETRIC KEY TestTableKey DECRYPTION
BY CERTIFICATE Tasc
UPDATE @TestTable
SET EncryptSecondCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),secondCol)

select * from @TestTable

--OPEN SYMMETRIC KEY TestTableKey DECRYPTION
--BY CERTIFICATE Tasc
--SELECT FirstCol,SecondCol,CONVERT(VARCHAR(50),DECRYPTBYKEY(EncryptSecondCol)) AS DecryptSecondCol
--FROM @TestTable

--CLOSE SYMMETRIC KEY TestTableKey -- close them drop

--DROP SYMMETRIC KEY TestTableKey
--GO
--DROP CERTIFICATE Tasc
--GO
--DROP MASTER KEY
--GO

-- BACKUP CERTIFICATE Tasc
--TO FILE = 'c:\Temp\TestCert.cer'

A: C# Provides Triple DES as part of the core cryptography libraries
http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledes.aspx

A: You really don't want to do this - you now have your key in two places, which makes it that much harder to secure. If you give one system permission to encrypt using a symmetric key generally the same system should be doing the decryption.
In any case you can't export symmetric encryption keys from SQL, and as you used a certificate to act as a source for the symmetric key, and didn't provide an IDENTITY_VALUE or KEY_SOURCE when creating the symmetric cert SQL used random values for generating the key, so you can't reproduce it in C# either.


text:
Q: When and why to Lift a Function Consider this code:
def f1(a: Int, b: Int) = a + b

def f2(a: Option[Int], b: Option[Int]): Int = (a, b) match {
  case (Some(x), Some(y)) => x + y
  case _ => throw new IllegalArgumentException
}

println(f1(10, 20))
println(f2(Some(10), Some(20)))

I heard you can "lift" f1 to be like f2. As a beginner I have the following question:
What is lifting and why it used? In terms of implementation, how can I "lift" f1?
Any explanation is greatly appreciated as it is a bit tricky to find why I would "lift" something

A: Why: when you have a function with signature like f1 and want to "call it" on Option[Int]s (or List[Int]s, etc)
How: you could write it directly:
def lift2option[A, B, C](f: (A, B) => C): (Option[A], Option[B]) => Option[C] = ???

I'm leaving it undefined because you should try writing it yourself; your definition of f2 should be a good starting point. Note that I made it return Option[Int] instead of Int. Later I can edit and give the answer if you want.
And then instead of defining f2 as separate function, you do:
val f2 = lift2option(f1 _)
println(f2(Some(10), Some(20)))

Of course, the point is that now for any function with a signature like f1 you can get an f2 equivalent.
It can be further generalized to work not only for Option, but you'll want to look into that later.

A: I just wanted to add that lifting a function can be used as an alternative to mapping over a functor. For example, if you had 2 Option[Int] objects which you wanted to apply f1 to, you could do this:
val sum: Option[Int] = option1.flatMap { x => option2.map{ y => x + y } }

Note that the result is an Option[Int]. As Alexey Romanov said, the return type of f2 should also be an Option. The whole point of Option is to let you do operations on a value without fear of NullPointerExceptions or other errors because the value doesn't exist.
However, this mapping is a bit verbose, and it's annoying having to decide when you need to use flatMap and map. This is where lifting comes in handy.
Let's define f2 a little better to handle Nones:
def f2(a: Option[Int], b: Option[Int]): Option[Int] =
  a match {
    case Some(x) => b match {
      case Some(y) => Some(x + y)
      case None => None
    }
    case None => None
  }

We can also define this in terms of f1 by replacing x + y with f1(x + y)
def f2(a: Option[Int], b: Option[Int]): Option[Int] =
  a match {
    case Some(x) => b match {
      case Some(y) => Some(f1(x, y))
      case None => None
    }
    case None => None
  }

Right now, f2 doesn't need to know anything about how to add numbers, it just uses f1 to add them. We could even make f1 a parameter of f2, in fact.
def f2(f1: (Int, Int) => Int)(a: Option[Int], b: Option[Int]): Option[Int] =
  a match {
    case Some(x) => b match {
      case Some(y) => Some(f1(x, y))
      case None => None
    }
    case None => None
  }

See what happened there? We just used f2 to "lift" f1 from (Int, Int) => Int to (Option[Int], Option[Int]) => Option[Int]. Let's rename it lift2, actually. We could also make it more generic:
def lift2[A, B, C](f1: (A, B) => C)(a: Option[A], b: Option[B]): Option[C] =
  a match {
    case Some(x) => b match {
      case Some(y) => Some(f1(x, y))
      case None => None
    }
    case None => None
  }

lift2 is now a function that takes a function of type (A, B) => C (here, A, B, and C are all Int for f1) and returns another function of type (Option[A], Option[B]) => Option[C]. Now, we don't have to use those awkward nested maps and flatMaps. You can just do this:
val sum: Option[Int] = lift2(f1)(option1, option2)

You can also define lift3, lift4, etc., of course, but it's probably easier to define just a lift1 function and use currying to do the rest.
Of course, you can only lift a function if you know how to take apart and put together the type that you are lifting to. For example, if Some were an object with a private unapply method, and it were impossible to pattern match on it, you wouldn't be able to lift f1. The same would happen if the constructor for Some were private and it were impossible for you to make new Options.
Edit: Here's how you can add multiple Option[Int] objects together with f1 and the lift2 function.
val f2 = lift2(f1)
val optionSum = f2(f2(option1, option2), option3)

Without f2, it'd look something like this
val sum1 = option1 match {
  case Some(x) => option2 match {
    case Some(y) => Some(f1(x, y))
    case None => None
  }
  case None => None
}
val finalSum = sum1 match {
  case Some(x) => option3 match {
    case Some(y) => Some(f1(x, y))
    case None => None
  }
  case None => None
}


text:
Q: Removing pixels below a certain threshold I have a grayscale image with something written in the front and something at the back. I'd like to filter out the back part of the letters and only have the front. It's only grayscale and not RGB, and I'd rather not have to calculate pixels manually.
Is there any library function I can use to do this? I'm new to python and at the moment, using PIL library, so that's my preference. But if there are other libraries, I'm open to that as well.
Here's the image:

A: Are you looking for a function that automatically strips the background for any given image, or just one that can filter out pixels that meet a certain criteria for this particular image?
The eval function applies the same transformation to every pixel in an image.  This works for your image.
with Image.open("jFmbt.jpg") as im:
    im = im.convert("L")
    out_image = Image.eval(im, lambda x: 256 if x > 175 and x < 250  else x)

A: A very commonly used library for that would be OpenCV.
import cv2 as cv

# 0 flag -> read image as greyscale
img = cv.imread("img.jpg", 0)

# threshold
ret, thresh = cv.threshold(img, 150, 255, cv.THRESH_BINARY)

# result
cv.imwrite("output.jpg", thresh)

The resulting image would be:


text:
Q: How to insert code into a code block? I am trying to insert a piece of code in my question and I am receiving this message:

Please add some context to explain the code sections (or check that you have not incorrectly formatted all of your question as code).

These are the steps I'm taking to copy/paste the code from the IDE in VS2008:

*

*Copy and Paste the code

*Select the code

*Click the {} button

What am I doing wrong?

A: To answer your question, you shouldn't be posting code alone with nothing else.  You need to explain what your question is, identify what is wrong, tell us what you're expecting and what you actually got.  It helps nobody if we don't understand your problem.
To be able to ask on Stack Overflow, just posting your code in the body will not be enough.  You need to include details.  If you somehow get around this, don't consider it ok, it is something that should have been stopped in the first place.  Seeing that you were not able to get your question through, it seems like it's working just fine.


text:
Q: User impersonation with asp.net forms authentication I've written a small ASP.NET 3.5 application to allow users to update selected account attributes on their own.
Everything works fine when I use Basic Authentication, but because the dialog that is presented is less than ideal, I'd like to use forms authentication to give the users more instruction on how to log in.
My problem is that in order for the user to update their account information, I have to have the application impersonate them for the update actions.
I've scoured the internet trying to find a solution to my issue, but nothing fits or works. I have tried setting the web.config:
<identity impersonate="true">

but that doesn't seem to work.
I also have the C# code using the WindowsImpersonationContext class, but still no luck.
protected void titleTextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    string fieldTitle = "job title";
    string fieldName = "title";

    if (userDirectoryEntry == null)
        CaptureUserIdentity();
    try
    {
        WindowsImpersonationContext impersonationContext = userWindowsIdentity.Impersonate();
        if (String.IsNullOrEmpty(tb.Text))
            userDirectoryEntry.Properties[fieldName].Clear();
        else
            userDirectoryEntry.InvokeSet(fieldName, tb.Text);
        userDirectoryEntry.CommitChanges();
        impersonationContext.Undo();
        PostBackMessages.Add(fieldTitle, "");
    }
    catch (Exception E)
    {
        PostBackMessages.Add(fieldTitle, E.Message);
    }
}

I also tried using the LogonUser method to create a user token and backend the authentication that way, and it doesn't work either.
IntPtr token = IntPtr.Zero;
bool result = LogonUser(userName, domainName, passwordTB.Text, LogonSessionType.Network, LogonProvider.Default, out token);

if (result)
{
     WindowsPrincipal wp = new WindowsPrincipal(new WindowsIdentity(token));
     System.Threading.Thread.CurrentPrincipal = wp;
     HttpContext.Current.User = wp;
     if (Request.QueryString["ReturnUrl"] != null)
     {
          FormsAuthentication.RedirectFromLoginPage(usernameTB.Text, false);
     }
     else
     {
          FormsAuthentication.SetAuthCookie(usernameTB.Text, false);
     }
}

I just can't help but think that I'm missing something incredibly simple...

A: Have you enabled Windows Authentication and disabled Anonymous Authentication in IIS?
If impersonation is enabled in an ASP.NET application then:
• If anonymous access is enabled in IIS, the request is made using the IUSR_machinename account.
• If anonymous access is disabled in IIS, the request is made using the account of the authenticated user.


text:
Q: Using pgfkeys as an argument to a macro I would like to use pgfkeys in a macro but find the documentation a bit hard to get started with. The following code should illustrate the problem I am trying to solve:
\documentclass{article}

\usepackage{pgfkeys}

\newcommand{\mymacro}[2][]{
  Before the elements.
  % if the elements key is set and the list is not empty
  % extract the members and list them separated by commas...
  % else print `No elements passed.'
  #2
}

\begin{document}

\mymacro[elements={a, b, c}]{Foo.}

% The above should expand to:
%
% Before the elements. a, b, c. Foo.

\mymacro{Foo.}

% The above should expand to:
%
% Before the elements. No elements passed. Foo.

\end{document}

A: The solution depends on what you want to do with elements but an idea is
\documentclass{article}

\usepackage{pgfkeys}
\def\mymacroempty{}

\pgfkeys{/mymacro/.cd,
elements/.code = \def\myelements{#1}}

\newcommand{\mymacro}[2][]{%
\pgfkeys{/mymacro/.cd,elements={}}
\pgfqkeys{/mymacro}{#1}
\ifx\myelements\mymacroempty
   No elements passed.
\else
\myelements.
\fi
  #2
}

\begin{document}

\mymacro[elements={a, b, c}]{Foo.}

\mymacro{Foo.}

\end{document}

A: Edit: This is a modified answer based on the comments.  I've adopted a bunch of suggestions that Andrew Stacey made.
The PGF key facilities are so varied and powerful that it takes a fair amount of effort to figure out how to use them to do what you want!  Let me present my solution in pieces and then in full.
\newcommand{\mymacro}[2][elements/.initial = {No elements passed.}]{
  Before the elements.
  % if the elements key is set and the list is not empty
  % extract the members and list them separated by commas...
  % else print `No elements passed.'
  {\pgfkeys{/mymacro/.cd, #1, print}}
  #2
}

Here is how you should define \mymacro.  You must call \pgfkeys on your optional argument, in order that the keys you want to use actually be processed.  Note that it's necessary to give your keys a "directory" in the path tree of all PGF keys, and it seems like good form to make your own, which I've called /mymacro (like a UNIX directory).
The way things will work is that elements will process the value it is given and then print will output the result, or the error message if no elements were specified.  I handle this by having the default argument for \mymacro simply set the value of elements directly, without any processing.
I am also careful to put the call to \pgfkeys in a group, since the action of elements doesn't initialize its value and subsequent calls of \mymacro could interfere with each other.
\pgfkeys{/mymacro/.cd,
 print/.code = {\pgfkeysvalueof{/mymacro/elements}},
 elements/.code = {%
  \pgfkeys{/mymacro/.cd,
           list/.list = {#1},
           elements/.add={\{}{\}}
  }%
 },
 list/.code = {\pgfkeys{/mymacro/elements/.append = (#1)}}
}

Now we have to define the action of these keys.  As I see it, your elements key is a storage bin, and whatever is in it will get printed by print.  However, it also processes the value it receives when it is called as elements = {a, b, ...}, using the .code subkey ("handler") I define for it.  This thing calls the list key's .list handler (which requires the pgffor package if you are just loading pgfkeys on its own rather than through tikz), which just loops over whatever comma-separated list it is given, applying list/.code to each item.  As an uncreative example, I have this just put parentheses around the items.  Afterwards, you can also have elements/.code postprocess the result, for example by pre- and app-ending braces.
This trick of having a key act both as storage for a value and code to act on that value is quite useful.  At the very least it allows you to write semantically appealing statements like elements = {a,b,c} without worrying whether that is really an assignment, since it can be both code and a subsequent assignment of the processed result.
It is probably possible to set things up more cleverly so that fewer keys are used, but that would be confusing in this example.  Here is the full LaTeX file:
\documentclass{article}

\usepackage{pgfkeys,pgffor}

\newcommand{\mymacro}[2][elements/.initial = {No elements passed.}]{
  Before the elements.
  % if the elements key is set and the list is not empty
  % extract the members and list them separated by commas...
  % else print `No elements passed.'
  {\pgfkeys{/mymacro/.cd, #1, print}}
  #2
}

\pgfkeys{/mymacro/.cd,
 print/.code = {\pgfkeysvalueof{/mymacro/elements}},
 elements/.code = {%
  \pgfkeys{/mymacro/.cd,
           list/.list = {#1},
           elements/.add={\{}{\}}
  }%
 },
 list/.code = {\pgfkeys{/mymacro/elements/.append = (#1)}}
}

\begin{document}
\mymacro[elements = {a,b,c}]{Foo}

\mymacro{Bar}

\mymacro[elements = {1,2,3}]{Baz}

\mymacro{Quh}
\end{document}


text:
Q: Seeding and pivot tables? I'm trying to popular a pivot table with ids in a seed.
$id = DB::table('products')->insertGetId(array(
        array(
            'title' => 'Product A',
            'published' => 1
        )
    ));

    DB::table('product_user')->insert(array(
        array(
            'product_id' => $id,
            'user_id' => '9999999999'
        )
    ));

Is the above the best way to do it? By getting an id via insertGetId and then putting it in the pivot table Is there a better way?
Also the above way gives an error:
 [ErrorException]
 preg_replace(): Parameter mismatch, pattern is a string while replacement i
 s an array

I suspect $id is an array, how can i get InsertGetId to return an int?

A: Well, you can print_r it and seek for the id attribute, and then call $id->attribute on the second insert.
But...
"Me myself", I like to use Eloquent. The mainly reason is: 'Cause it too god damm FUN. Really, Eloquent it's one of the most beautful things I've ever seen in the programming world. I use to thought that .NET was a master piece of software (I was young and naive, though) but once a came across Laravel/Eloquent, I became so AMAZED!
That being said, in my humble opinion, use Eloquent is the best way of doing it!
I'm assuming that you have a table called products and another called users, and you have a product_user table to make the connection. Using Eloquent, you can simply do this:
$user = User::find($user_id);
$product = Product::find($product_id);

$product->user->attach($user);

...I reacomend this approach for several reasons, but the first one is: is way more readable.
Well, I hope I ain't been too prolixous on my answer, and that it hope you and others.


text:
Q: slide effect with JPanel I tried create simple class which can slide a JPanel like this:
+----------+    +------+---+    +----------+
|          |    |      |   |    |          |
| JPanel1  | => | JPane| JP| => | JPanel2  |
|          |    |      |   |    |          |
+----------+    +------+---+    +----------+
I created javax.swing.Timer and added in class
timer = new Timer(50, this);
timer.start();

static final int frames = 5;
int counter = 0;

actionPerformed(ActionEvent e) {
    if (counter >= frames) {
        timer.stop();
        counter = 0;
    } else {
        counter++;
        jPanel2.setBounds(800 - 800 * counter / frames, 0, 800, 600);
    }
}

This is work, but very slowly. I have only 2-3 fps and don't know how to speed up this method. May you help me?

A: Perhaps change the Timer's interval from 50 to some smaller number.
i.e., from this:
timer = new Timer(50, this);

to this:
timer = new Timer(10, this);

Note: you should avoid use of magic numbers here.
Heck, something like...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class SlideEg extends JPanel {
   private SlideContainer slideContainer = new SlideContainer();

   public SlideEg() {
      setLayout(new BorderLayout());
      add(slideContainer, BorderLayout.CENTER);

      JLabel helloLabel = new JLabel("Hello", SwingConstants.CENTER);
      slideContainer.add(helloLabel);

      Timer myTimer = new Timer(5000, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            JLabel goodbyeLabel = new JLabel("Goodbye", SwingConstants.CENTER);
            goodbyeLabel.setOpaque(true);
            goodbyeLabel.setBackground(Color.pink);
            slideContainer.add(goodbyeLabel);
         }
      });
      myTimer.setRepeats(false);
      myTimer.start();
   }

   private static void createAndShowGui() {
      SlideEg mainPanel = new SlideEg();

      JFrame frame = new JFrame("SlideEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class SlideContainer extends JLayeredPane {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final int SLIDE_DELAY = 20;
   protected static final int DELTA_X = 2;
   Component oldComponent;

   public SlideContainer() {
      setLayout(null);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   public Component add(Component comp) {
      Component[] comps = getComponents();
      if (comps.length > 0) {
         oldComponent = comps[0];
      }
      if (oldComponent == comp) {
         return super.add(comp);
      }
      if (oldComponent != null) {
         putLayer((JComponent) oldComponent, JLayeredPane.DEFAULT_LAYER);
      }
      Component returnResult = super.add(comp);
      putLayer((JComponent) comp, JLayeredPane.DRAG_LAYER);
      comp.setSize(getPreferredSize());
      comp.setVisible(true);
      comp.setLocation(getPreferredSize().width, 0);
      slideFromRight(comp, oldComponent);
      return returnResult;
   }

   private void slideFromRight(final Component comp,
         final Component oldComponent2) {
      new Timer(SLIDE_DELAY, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent aEvt) {
            int x = comp.getX();
            if (x <= 0) {
               comp.setLocation(0, 0);
               putLayer((JComponent) comp, JLayeredPane.DEFAULT_LAYER);
               if (oldComponent2 != null) {
                  remove(oldComponent2);
               }
               ((Timer) aEvt.getSource()).stop();
            } else {
               x -= DELTA_X;
               comp.setLocation(x, 0);
            }
            repaint();
         }
      }).start();
   }
}


text:
Q: Unable to connect Outlook 2007 to Exchange 2007 Internally I am able to connect to Exchange via mobile devices, and OWA, but setting up Outlook clients internally I receive "the action cannot be completed, unable to connect to exchange...."
I've edited the host file for IPv6 loopback issue to no resolve. In a two part question, where do I start to troubleshott his, and do internal clients automatically setup using RCP over HTTP? Or do they setup with FQDN, or the remote DNS HTTPS address?

A: Chances are, your auto-discover settings are off. Outlook clients use auto discover to find the exchange servers and if those names are not on the certificates problems can result. Local clients will be using mapi or, maybe even rpc over http if discovery doesn go well. Exchange does have settings for internal and external autodiscovery urls.

A: Need to add the FQDN of the server to the SSL certificate.


text:
Q: Release of flock in case of errors? Imagine the following Perl code (here in pseudo code):
successfully acquired flock for FILEHANDLER       # line 1
some error or maybe simply a call to exit()       # line 2
close FILEHANDLER (which also releases the lock)  # line 3

In this case I wouldn't release the lock, as the Perl script ends in line 2. In that case, is the lock ever released by the operating system? Does it see "hey, the script that acquired the lock crashed" and release the lock? Does it release the lock immediately? Also, is there one Perl instance running for each script, so that it's clear which script crashed/stopped without releasing the lock?

A:
In that case, is the lock ever released by the operating system?
  Does it see "hey, the script that acquired the lock crashed" and release the lock?
  Does it release the lock immediately?

All of these questions are system dependent.  Perl 5 does not implement a file locking function, it just provides a common interface to flock(2), fcntl(2) locking, or lockf(3) (depending on what is available in the OS).  There may also be a difference between what happens when a program exits, segfaults, or is killed with a sigkill.
A quick test under Linux shows that a lock is removed under normal exit conditions:
$ perl -le 'open my $fh, ">", "f" or die $!; print flock($fh, 6) ? "got lock" : "was already locked", "\n"'
got lock
$ perl -le 'open my $fh, ">", "f" or die $!; print flock($fh, 6) ? "got lock" : "was already locked", "\n"'
got lock

Let's see what happens when we die:
$ perl -le 'open my $fh, ">", "f" or die $!; print flock($fh, 6) ? "got lock" : "was already locked", "\n"; die "died"'
got lock
died at -e line 1.
$ perl -le 'open my $fh, ">", "f" or die $!; print flock($fh, 6) ? "got lock" : "was already locked", "\n"; die "died"'
got lock
died at -e line 1.

To get a segfault, we will need access to C, I am using Inline to get it:
$ cat segfault.pl
#!/usr/bin/perl

use strict;
use warnings;

use Inline "C";

open my $fh, ">", "f" or die $!;

print flock($fh, 6) ? "got lock" : "was already locked", "\n";

crash();

__DATA__
__C__

void crash() {
    int* ptr = NULL;
    *ptr = 5;
}
$ perl segfault.pl
got lock
Segmentation fault
$ perl segfault.pl
got lock
Segmentation fault

And finally, here is what happens when a program is sent SIGKILL:
$ cat fork.pl
#!/usr/bin/perl

use strict;
use warnings;

$SIG{CHLD} = "IGNORE"; #auto-reap children

die "could not fork: $!" unless defined(my $pid = fork);
unless ($pid) {
    #child
    open my $fh, ">", "f" or die $!;
    print flock($fh, 6) ? "got lock" : "was already locked", "\n";
    sleep(100);
    exit;
}

kill 9, $pid;

die "could not fork: $!" unless defined($pid = fork);
unless ($pid) {
    #child
    open my $fh, ">", "f" or die $!;
    print flock($fh, 6) ? "got lock" : "was already locked", "\n";
    exit;
}
$ perl fork.pl
got lock
got lock

From these experiments, we can see that the lock is released in Linux for each of the cases you were concerned with.

Also, is there one perl instance running for each script, so that it's clear which script crashed/stopped without releasing the lock?

Yes, Perl 5 has one perl process per script.  Even if you fork, the child gets its own perl process.  Threading does not provide a separate perl process.
Note: if a parent process gets a lock and does not give it up before locking, then the child will have the same lock even if the parent exits.

A: When the program exits, the OS automatically releases all locks acquired by the program and closes all files opened by the program.


text:
Q: Outlook 365 Web Add-in - Context menu from Mail Item Outlook 365 Web Add-in - Context menu from Mail Item
Is this something that is still supported in the new Web Add-in model? From the documentation it appears that it is NOT Supported. I am looking for someone in a solid position to definitively confirm this so that we can move on to other potential solutions.
Extension Points Reference:
https://learn.microsoft.com/en-us/outlook/add-ins/

A: According to my research, the context menu from Mail Item is not supported in Web Add-in model.
However, You might reference the related post and it can meet your requirement.
Please see Add Outlook Web Addin Function to context menu
Solutions: Outlook Web Add-ins allow customizing the ribbon by adding commands only. Read more about that in the Add-in commands for Outlook article.
Hope it helps you.
Thanks,
Yuki


text:
Q: R Table data with a grouping command This seems like a very simple problem, but I can't seem to sort it out. I have sought help from this forum, with the below topics being close, but don't seem to do exactly what I need. I have count data over several years. I want to obtain frequencies of the count value by year. It seems I need a table function with a grouping option, but I haven't found the proper syntax.
Data:
          count year
    1        15 1957
    2         6 1957
    3        23 1957
    4        23 1957
    5         2 1957
    6        28 1980
    7        15 1980
    8        32 1980
    9        18 1981

thank you in advance!
Counting the number of elements with the values of x in a vector
grouping data splitted by frequencies
Aggregate data in R

A: You're looking for the table function.  Something like:
with(yourdata, table(Year, Count))


text:
Q: Setting up Airport Base Station with Uverse AND Sprint Airave I'm trying to configure my home network so that I can use a drive attached to my airport base station as the Time Machine drive. I think that to do this the Airport needs to control the DHCP and the NAT. I'm not sure I really understand DMZ settings, or if it's possible to push that to a third router...
Current setup includes:
ATT Uverse's 2Wire Modem/Router > Sprint Airave  > Apple Airport Extreme.

Everything I've read about this doesn't seem to use three routers. I can connect to the internet, but not able to use Time Machine with my networked drive.
Is Double NAT error that big a deal?
Any thoughts? Any place to read layman's DMZ info? Anyone using a third router as the main DHCP server? Why does everything come with a router? Is my setup just too complicated?
Pre-AiRave, the Airport Base Station was the only thing connected to the ATT 2Wire, and it worked fine. Unfortunately, I sprint says the Airave must be in front of the router. The main concern is to get Time Machine working. That being said, Finder no longer sees the Airport Base station as a 'server' to connect to and simply access the networked drive. Am I barking up the wrong tree?

Airrave WAN Settings Screenshot
Airrave LAN Settings Screenshot

A: The definitive steps that worked for me. I would like to spell them out as much as possible, since many forum posts will say "Set this to that" but in no way tell you how to get to a setting screen.

*

*Set Airport to use WPA2 security (not WPA/WPA2)

*

*Airport Utility > Airport > Wireless > Wireless Security > WPA2 Personal

*This may not work for everyone, especially if you have older devices

*Set Airport to do DHCP and NAT

*

*Airport Utility > Airport > Network > Router Mode > DHCP and NAT

*Set Airport to reserve an IP for your AiRave/Airvana

*

*Airport Utility > Airport > Network > "+" under "DHCP Reservations"

*Choose a high number

*Setup the Uverse Modem/Router

*

*Turn off the wireless network

*

*Settings > LAN > Wireless > Wireless Interface > Disabled

*Verify your Apple Airport is the only thing using your Uverse Modem's Router

*

*Settings > LAN > Status

*Devices > Clear List

*You want to only see one device.

*Set Airport in the Uverse DMZ

*

*Settings > LAN > IP Address Allocation

*

*Firewall > Disabled

*Address assignment > Public

*WAN IP Mapping > Router WAN IP Address

*Verify this worked

*

*Settings > Firewall > Applications, Pinholes, DMZ

*You should only see your Airport as the  'computer' in step 1.

*Since it is selected, you see the radial button pressed for DMZ

*Set up the Airvana/Airave

*

*Manually set the IP to reserved

*

*Advanced > LAN

*(May not be necessary)

*Set to use it's own MAC address

*

*Settings > Status

Ultimately, I resolved the Airport/Uverse DMZ issue by switching the Airport Extreme from WPA/WPA2 to strictly WPA2. Initially, I didn't have much faith in this approach, but I tried it based on ouquinn's comment. This allowed me to set the Airport in the Uverse DMZ, which I had struggled for hours to do.


text:
Q: Converting an empty string to nil in place? I'm looking for a way to convert an empty string to nil in place using Ruby.  If I end up with a string that is empty spaces I can do
 "    ".strip!

This will give me the empty string "".
What I would like to be able to do is something like this.
"    ".strip!.to_nil!

This will get an in place replacement of the empty string with nil.  to_nil! would change the string to nil directly if it is .empty? otherwise if the string is not empty it would not change.
The key here is that I want it to happen directly rather than through an assignment such as
f = nil if f.strip!.empty?

A: The clean way is using presence.
Let's test it.
'    '.presence
# => nil

''.presence
# => nil

'text'.presence
# => "text"

nil.presence
# => nil

[].presence
# => nil

{}.presence
# => nil

true.presence
# => true

false.presence
# => nil

Please note this method is from Ruby on Rails v4.2.7
https://apidock.com/rails/Object/presence
NOTE: Not work on IRB, work with Ruby on Rails!

A: That isn't possible.
String#squeeze! can work in place because it's possible to modify the original object to store the new value. But the value nil is an object of a different class, so it cannot be represented by an object of class String.

A: I know I am bit late but you can write your own method for the String class, and run code in initializers:
class String
  def to_nil
    present? ? self : nil
  end
end

and then you will get:
'a'.to_nil
=> "a"
''.to_nil
=> nil

Of course you can also strip the string before checking if thats suits for you

A: Regex to the rescue! We can use string[regexp] which returns a new_string if there is a match or nil if the regex doesn't match (see documentation String).
''[/.+/]
# => nil

'text'[/.+/]
# => 'text'

# Caution 1: This doesn't work for strings which are just spaces
'   '[/.+/]
# => '   '

# In these cases you can strip...
'   '.strip[/.+/]
# => nil

# ...or use a more complicated regex:
'   '[/.*\S.*/]
# => nil


text:
Q: how to set ...initialize multiple unit id in mopub ios sdk my code
let config = MPMoPubConfiguration.init(adUnitIdForAppInitialization:"ad_unit_id")
        config.loggingLevel = .none

        MoPub.sharedInstance().initializeSdk(with: config) {
            print("mopub now use!!")
        }

why onle one unitid input?
my app is use both banner and reward..
What should I enter? plz..help

A: If you want to initialise multiple ads units in mopub you can do like this:
    let sdkConfigBanner = MPMoPubConfiguration(adUnitIdForAppInitialization:MOPUB_AD_BANNER)
    sdkConfigBanner.loggingLevel = .info
    MoPub.sharedInstance().initializeSdk(with: sdkConfigBanner, completion: nil)

    let sdkConfigReward = MPMoPubConfiguration(adUnitIdForAppInitialization:MOPUB_AD_REWARD)
    sdkConfigReward.loggingLevel = .info
    MoPub.sharedInstance().initializeSdk(with: sdkConfigReward, completion: nil)

A: As per Mopub guidelines, you only need to initialise one ad unit ID belonging to the app.

Initialize once per app's lifecycle, typically on app launch, using
any valid ad unit ID that belongs to the specific app you're
initializing with MoPub.

You can do this by:
let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "YOUR_AD_UNIT")
sdkConfig.loggingLevel = .none
sdkConfig.allowLegitimateInterest = true

// Mopub Configuration
MoPub.sharedInstance().grantConsent()
MoPub.sharedInstance().allowLegitimateInterest = false
MoPub.sharedInstance().initializeSdk(with: sdkConfig, completion: nil)

Extract from Motics Mopub Blog.


text:
Q: Passing Structures by Reference? [C] I am trying to create a linked list, with two seperate lists in one structure. That is, it holds a 'name' and a 'age' value. Then the program can either output the list sorted by name, or sorted by age. So i need two linked lists, essentially.
However, i need the program to be aware of the root/head of both the name list and the age list.
I'm not sure how to send this to my function.
I will already have the name and the age I want to add to each list, and then somehow I have to send it the head of each list. Because there is two heads i want to return, i cant use the return function. How can I make my main aware of the changes to the head/root lists?
Hopefully the question is clea, and thanks for the answers!

A: You may wrap both heads in a single structure.

A: You can link single list item into two lists and sort them independently:
/* List item is linked into two lists */
struct list
{
    struct list* name_next; /* next in name list */
    struct list* age_next;  /* next in age list */

    char*    name;
    unsigned age;
};

/* Holds both list heads */
struct book
{
    struct list* name_sorted;
    struct list* age_sorted;
};

A: You can simply pass a pointer to the pointer to the two heads as a argument and then change the pointer without any problem.
 void list_add(char *name, int age, list_type *list, list_type **name_head, list_type **age_head)
 {
     /* Add the name and age and calculate the two heads. */
     (*name_head) = calculated_head;
     (*age_head) = calculated_head;
 }

A: *

*You can use pointers as Kingdom of Fish suggested. I just wanted to add that your documentation should indicate that these values are "outputs" even though they are parameters.

*You can use a tuple data-type. Here is a simple one:
typedef struct Tuple{void*a,*b;}*Tuple;
Tuple tuple(void*a,void*b){
  Tuple z=malloc(sizeof(struct Tuple));
  z->a=a,z->b=b;
  return z;
}

Beware though, that tracking dynamically allocating memory can be difficult, and unless you are using a garbage collector, you need to be very careful.

*You can use a less-general data structure. For example, you could thread the indexes through the person-object:
struct Person;typedef struct Person*Person;
struct Person{Person*prev_by_name,*next_by_name,*prev_by_age,*next_by_age; ...};

Adding additional indexes (linked lists) becomes trivial, and if you give it some thought, you can make the preprocessor do most of the work for you.
This method also gives you the ability to ask "who is the next-youngest-person after Dave"
Finally, by threading the indexes in this way, all updates to a person's indexes will be kept together, which will make it easier to avoid synchronization bugs.

*You can use separate functions and simply "remember" to call them both. If this is for homework, and you haven't yet addressed how to return multiple values, then you might want to choose this "solution" simply because it's probably what your teacher is looking for.


text:
Q: Email specific sheet tab I want to e-mail an individual sheet tab as a PDF using script.  This script below will send the entire workbook/sheet as a PDF file (which is a great start, but not ideal).  However, I am only interested in e-mailing the specific sheet tab named "Alpha".
function sendpdf() {
   var originalSpreadsheet = SpreadsheetApp.getActive();
   var message = 'Hello, \n\n' + 'Attached is the priority list for today.';
   var subject = "Priority List for - " + new Date().toString();
   var emailTo = "first@example.com,second@example.com";
   var pdf = DriveApp.getFileById(originalSpreadsheet.getId()).getAs('application/pdf').getBytes();
   var attach = {fileName:'PRIORITY.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
}


text:
Q: External library usage in eclipse I want to use this library in my project:https://github.com/hdodenhof/CircleImageView I am using eclipse.I downloaded jar file and put the libs folder.
My xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="131.50dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@android:color/black" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="75dp"
        android:src="@drawable/profile_viewer" />
<de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/profile_viewer"
    app:border_width="2dp"
    app:border_color="#FF000000"/>
</RelativeLayout>

I am getting  following errors:
Multiple annotations found at this line:
    - error: No resource identifier found for attribute 'border_color' in package
     'com.impact.ribony'
    - error: No resource identifier found for attribute 'border_width' in package
     'com.impact.ribony'

How can I resolve this ?

A: Check your style if you have border_color, or border_width name in your style or dimen xml, then rename them, if it doesn't work then
Add
xmlns:app="http://schemas.android.com/apk/res-auto" to your root layout
It will be good if you use source code not jar of this Lib project


text:
Q: trying to get a specific model out of a collection I"m building a simple backbone.js app, without using a "real database".
My data base is very simple and looks something like that:
[
    { "Name": "Daniel", "Month": "abc", "year": "83" },
    { "Name": "Johan", "Month": "abg", "year": "33" }
]

Iv'e succeeded fetching the data into a collection instance, I did console.log and saw it worked:
this.nameList = new NameList();
this.nameList.fetch();
console.log(this.nameList);

Up here I'm fine, now I tried to use only one of the models in the collection and nothing works. I tried:
console.log(this.nameList.at(1));
console.log(this.nameList.get(id));  //when id is passed as a number.
console.log(this.nameList.getByCid(id))  //when id is passed as a number.

I always get "undefined".

*

*How can I work with a simple database like that?

*Where can I read about this stuff?

As an update, it works for me when working with a collection:
    this.projectList = new ProjectList;
    this.projectList.fetch({
        success: function (data) {
            console.log(data.get(id));
        }
    });

Not working when working with a single model:
    this.project = new Project({id: id});
    this.project.fetch({
        success: function (data) {
            console.log(data);
        }
    });

now I get : GET ......../Client/web/Data/projects/3 404 (Not Found)
Why?

A: You can retrieve the model from the "models" property:
console.log(this.nameList.models[0].name);

A: /Client/web/Data/projects/3 404 (Not Found)

Are you sure you're actually serving something at that RESTian location?
The collection's default behavior for a fetch will be to perform a GET on the collection URL [/Client/web/Data/projects] which you say is serving the correct data.
But when you call fetch() on an individual model it appends that model's id to the collection URL: /Client/web/Data/projects/3 which is returning a 404/Not Found response. If you try that URL manually do you actually get a response?
As for why console.log(this.nameList.get(id)) is returning undefined, it seems nameList didn't get populated correctly. Take a look at the output of console.log(this.nameList.models) - does it actually have the models you were expecting?


text:
Q: Connecting Drupal 7 Ubercart with PayPal This seems like it should be a relatively easy process. There are quite a few links that come up addressing the issue in a Google search and in searches here, but something is missing in actual implementation.
My client has a PayPal account already. I have Ubercart installed with products available. But, when I go to Store -> Payment Methods -> Credit Card Settings, I cannot see any place to enter PayPal API information. What am I missing?
Thanks!

A: After some searching and putting bits and pieces together, I found out that the problem wasn't with Ubercart at all!

*

*I could not get any clear answers for the combination of Drupal 7, Ubercart and PayPal from any website that came up from a search.

*All of the sites listed gave me instructions to do steps with form items that did not exist in the site.

*I figured that there was possibly a PayPal module that I was missing, but I could not find one.

*There is indeed a module, but it turns out that the module is part of the basic Ubercart install.

*I could not enable this module.

*Then I found out that the reason I could not enable it is that cURL was not enabled in the server. So, I enabled it in php.ini.

So, the problem was not with Drupal 7 or with Ubercart or with a module. The problem was a php.ini setting!