text:
Q: Making sense of tensor product of observables I'm trying to understand an argument against naive realism in Richard Healey's book, The Quantum Revolution (The second argument in Appendix B). The book is pitched at philosophers, but discusses some of the math. And I'm very new to the math myself, so it's a bit of a challenge. In any case, here's what's confusing me:
The argument works by assuming that an arbitrary system of three photons is such that each photon has both a definite circular and linear polarization, corresponding to the dynamical variables $\bigcirc_1, \bigcirc_2, \bigcirc_3$ and $\diagup_1,\diagup_2,\diagup_3$ (whose possible values are 1 or -1) and operators $\hat{\bigcirc}_1, \hat{\bigcirc}_2, \hat{\bigcirc}_3$ and $\hat{\diagup}_1,\hat{\diagup}_2,\hat{\diagup}_3$.
The idea behind the proof, I think, is that by determining which collections of operators commute, you determine all the possible joint measurements that could be made on the system, but there's no way to assign definite values to the six dynamical variables that doesn't result in a contradiction with what has (apparently) been found in experiments.
This is what confuses me most: Healey claims that the following set of observables commute:
$$\{\widehat{\diagup\diagup\diagup},\widehat{\bigcirc\bigcirc\diagup},\widehat{\diagup\bigcirc\bigcirc},\widehat{\bigcirc\diagup\bigcirc}\}$$
Where these observables are identical to the tensor product of the smaller observables mentioned above, so that for instance:
$$\widehat{\diagup\diagup\diagup} = \hat{\diagup}_1 \otimes \hat{\diagup}_2 \otimes \hat{\diagup}_3$$
And Healey claims that when such measurements are observed, the product of the measurements is always -1, indicating that an odd number of the observables in the set have value -1.
But if that's so, I have no idea how to make sense of what observables like $\widehat{\diagup\diagup\diagup}$ represent. My original thinking was that the dynamical variable $\diagup\diagup\diagup$ should have as its value the product of the photons' linear polarizations. But then it would be impossible for the product $\diagup\diagup\diagup \times \bigcirc\bigcirc\diagup \times \diagup\bigcirc\bigcirc \times \bigcirc\diagup\bigcirc$ to be -1, since each $\pm1$ circular/linear polarization observable appears in this product twice; the product would have to be 1.
In certain cases, though, I thought I had good reasons for thinking that $\widehat{\diagup\diagup\diagup}$ would have as its value the product of the photons' linear polarization. Suppose the three photons each have definite linear polarization, in which case we would find that the individual photon states are eigenvectors for the $\diagup$ operators. Wouldn't this then imply the following?:
$$\widehat{\diagup\diagup\diagup}|\psi_\text{all}\rangle = (\hat{\diagup}_1 \otimes \hat{\diagup}_2 \otimes \hat{\diagup}_3)(|\psi_1\rangle|\psi_2\rangle|\psi_3\rangle = \lambda_1\lambda_2\lambda_3|\psi_1\rangle|\psi_2\rangle|\psi_3\rangle = \lambda_1\lambda_2\lambda_3|\psi_\text{all}\rangle$$
I tried to think through the case where the photons are in a superposition of opposite linear polarizations, but I'm not sure how the math works in that case. Would that change the above result?

A: I'm answering the specific question posed in the final paragraph of the post. If this doesn't clear up your overall confusion, please feel free to comment or edit your question.
I will denote eigenvectors of $\widehat{\diagup}$ with eigenvalues of $+1$ and $-1$ as $\left|+\right>$ and $\left|-\right>$ respectively. I'll also use the notation $\left|+++\right> = \left|+\right>_1 \otimes \left|+\right>_2 \otimes \left|+\right>_3$, etc.
Consider the superposition state
\begin{align}\left|\psi\right> = \frac{\left|+++\right> + \left|---\right>}{\sqrt{2}}.\end{align}
Applying $\widehat{\diagup\diagup\diagup} = \widehat\diagup_1 \otimes \widehat\diagup_2 \otimes \widehat\diagup_3$ to $\left|\psi\right>$,
\begin{align}
\widehat{\diagup\diagup\diagup} \left|\psi\right> &= \frac{1}{\sqrt{2}}\left[\widehat{\diagup\diagup\diagup}\left|+++\right> +  \widehat{\diagup\diagup\diagup}\left|---\right>\right]\\
&= \frac{1}{\sqrt{2}}\left[(+1)(+1)(+1)\left|+++\right> + (-1)(-1)(-1)\left|---\right>\right]\\
&= \frac{1}{\sqrt{2}}\left[\left|+++\right> - \left|---\right>\right].
\end{align}
Evidently, $\left|\psi\right>$ is not an eigenvector of $\widehat{\diagup\diagup\diagup}$.
Re-reading your question, I think you may have instead intended the following product state:
\begin{align}
\left|\chi\right> &= \left(\frac{\left|+\right>_1 + \left|-\right>_1}{\sqrt{2}}\right)\left(\frac{\left|+\right>_2 + \left|-\right>_2}{\sqrt{2}}\right)\left(\frac{\left|+\right>_3 + \left|-\right>_3}{\sqrt{2}}\right)\\
&=\frac{1}{2^{3/2}}\left[\left|+++\right> + \left|++-\right> + \left|+-+\right> + \left|+--\right>\right.\\ &\left.\hspace{3.5em}+ \left|-++\right> + \left|-+-\right> + \left|--+\right> + \left|---\right>\right],
\end{align}
or something similar.
This yields
\begin{align}
\widehat{\diagup\diagup\diagup} \left|\chi\right> &= \frac{1}{2^{3/2}}\left[\left|+++\right> - \left|++-\right> - \left|+-+\right> + \left|+--\right>\right.\\ &\left.\hspace{3.5em}- \left|-++\right> + \left|-+-\right> + \left|--+\right> - \left|---\right>\right].
\end{align}

A: Indeed, the eigenvalues of a tensor product of operators are just the product of the individual operators' eigenvalues, for the reason that you state.
Do you have Healey's exact quote? I think when he says "the product of the measurements" he means each of the four products of the three single-particle measurements, not the product of the four three-particle joint measurements.


text:
Q: How to resample large dataframe with different functions, using a key? I have a large time-series set of data with over 200 recorded values (columns). Some values need to be averaged and some need to be summed, and I have a list that determines which is which. I need help figuring out how to feed that list into the how= function of resample.
Example data:
"Timestamp","TZ","TAO (degF)","RHO (%)","WS (mph)","WD (deg)","RAIN (mm)","OAP (hPa)","INSOL (W/m2)","HAIL (hits/cm2)"......."
2014/04/01 01:01:01.005,n,45.3,88.2,0,0.6,0.339,1.0108,-0.270342,0,68.147808,40.91662,68.15884,40.672356,66.55452,......
2014/04/01 01:02:01.027,n,45.3,88,0,3.4,0.339,1.0108,-0.124948,0,68.216736,40.929836,68.15884,40.656932,66.560072,.......
2014/04/01 01:03:01.050,n,45.3,88,0,1.7,0.34,1.0108,-0.145394,0,68.156064,40.890184,68.103736,40.68332,66.557296,......

The best I can come up with is concatenating the list into a string to pass into the how=function, but the concatenation of strings makes the function SeriesGroupBy error out.
df = pandas.read_csv(parsedatafile, parse_dates = True, date_parser=lambda x: datetime.datetime.strptime(x, '%Y/%m/%d %H:%M:%S.%f') , index_col=0)

while i < len(recordname):
      if recordhow[i]=="Y":
        #parseavgsum[i]="sum"
        recordhow[i]=str(recordname[i])+str(": sum")
      else:
        recordhow[i]=str(recordname[i])+str(": mean")
        #parseavgsum[i]="mean"
      i+=1

df2=df.resample('60Min', how = recordhow)

A: I would pass how a dictionary:
>>> df
                             WD (deg)  RAIN (mm)
Timestamp
2014-04-01 01:01:01.005000  40.916620  68.158840
2014-04-01 01:02:01.027000  40.929836  68.158840
2014-04-01 01:03:01.050000  40.890184  68.103736

[3 rows x 2 columns]
>>> what_to_do = {"WD (deg)": "mean", "RAIN (mm)": "sum"}
>>> df.resample("60Min", how=what_to_do)
                      RAIN (mm)   WD (deg)
Timestamp
2014-04-01 01:00:00  204.421416  40.912213

[1 rows x 2 columns]

I think using a recordhow list like you're doing is a little dangerous, because it's very easy for columns to get shuffled accidentally in which case your means and sums would be off.  It's much safer to work with column names.  But if you have recordhow, you could do something like:
>>> recordhow = ["N", "Y"]
>>> how_map = {"Y": "sum", "N": "mean"}
>>> what_to_do = dict(zip(df.columns, [how_map[x] for x in recordhow]))
>>> what_to_do
{'RAIN (mm)': 'sum', 'WD (deg)': 'mean'}

but again, I recommend moving away from a bare list that doesn't know what maps to what as quickly as possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Export Azure Cosmos DB table to CSV I need to export the data that I have in Azure CosmosDB table to a CSV file.
I tried to use ADF but I only found configured for SQL and MongoDB and I am using TABLE STORAGE in COSMOSDB options .
Is there an easy or coded way to achieve this?

A: I found a way to export Azure data from CosmosDB table to a CSV file.
From what I found there is no way to export the data directly from the azure web portal but from Azure Storage Explorer It is free and supported by Microsoft. Browse to the appropriate storage account, click on the table storage you want to export and look for the export option in the explorer.
I still have a code tool pending to solve this and make it more automatic

A: I think I can share this answer with you. Because I haven't found any docs to describe a solution to export data from cosmosdb table api.
First, it mentioned a tool which is not free and provides download data as csv file.

And along the idea of writing code to achieve exporting data feature. I think it's also realizable for cosmosdb. You can query all the items you wanted and write them in csv file. Share a high voted answer here and it recommend to use the library CsvHelper, I think it's helpful to use File.WriteAllText(filePath, csv.ToString());

A: I wrote a small library built on the new Azure.Data.Tables SDK to get Azure Storage Explorer compatible CSV exports.With that you can export to CSV file or to Azure BLOB Storage in a few lines of code and use it for example in Azure Storage. Note that it currently loads all data in memory though to create the proper CSV headers.
// Export all rows from the table to a CSV file
using StreamWriter writer = File.CreateText("test.csv");
await _tableClient.ExportCSVAsync(writer);

// Export all rows as CSV to Azure BLob Storage
BlobContainerClient containerClient = new(BlobConnectionString, "testcontainer");
var blobClient = containerClient.GetBlobClient("test.csv");
var stream = await blobClient.OpenWriteAsync(true, new BlobOpenWriteOptions() { HttpHeaders = new BlobHttpHeaders { ContentType = "text/csv" } });
using StreamWriter writer = new(stream);
await _tableClient.ExportCSVAsync(writer);


text:
Q: Boundedness of heat semigroup on $L^1(\Omega)$ On a bounded domain $\Omega \subset \mathbb{R}^n$ with smooth boundary, consider the Laplacian $-\Delta$ with either the Dirichlet or Neumann boundary conditions. More generally, one can also consider a strongly elliptic self-adjoint operator $L$, where $L$ is negative definite. Now consider the heat semigroup $e^{tL}$, which is $L^2$ contractive. I am curious whether $e^{tL}$ is bounded on $L^1(\Omega)$, that is,
could we say something like $$ \Vert e^{tL}f\Vert_{L^1(\Omega)} \leq C\Vert f\Vert_{L^1(\Omega)}, f \in L^1(\Omega) ?$$
If yes, will the constant $C$ be independent of $t$? Most books list these types of results when $p \in (1, \infty)$. I would be really grateful if someone can provide a reference. If results like the above hold only under special conditions on the operator $L$, I would like to know that too. Thanks.


text:
Q: UserControll and calling TextBox events from this UserControll as primary events I have UserControl which has two components
public System.Windows.Forms.ComboBox innerComboBox;
public System.Windows.Forms.TextBox innerTextBox;

and when i am using this UserControl i can not call Validating event like
myName.Validation += new System.ComponentModel.CancelEventHandler(myName_Validating);

becouse not working. I must call it like.
myName.innerTextBox.Validating += new System.ComponentModel.CancelEventHandler(myName_Validating);

can i override my UserControll that all events will be calling from innerTextBox of TextBox ?

A: In your UserControl, try adding it like this:
public new event CancelEventHandler Validating {
  add { innerTextBox.Validating += value; }
  remove { innerTextBox.Validating -= value; }
}

Then your myName.Validating should work like you want.

A: No, but you can "wrap" them in some ways, meaning you will need to expose the events from your top-level user control to which outsiders can subscribe, and then, subscribing to the inner-control even handlers, "inform" your top-level subscribers. For instance...
public class MyControl
{
    public event CancelEventHandler Validating;

    public System.Windows.Forms.TextBox innerTextBox;

    public MyControl()
    {
        //post-instantiation stuff here

        innerTextBox.Validating += myName_Validating;
    }

    void myName_Validating(oject sender, CancelEventArgs e)
    {
        if (Validating != null)
        {
            Validating(sender, e);
        }
    }
}

How exactly you want to wrap them is up to you; if you want your control to have some handling logic prior to publishing and executing the top-level subscriptions (can be handy in threading situations) then this will work, otherwise a more concise and practical approach for your might be what LarsTech suggests.


text:
Q: Punctuation, stopwords and lemmatization with spacy I'm trying to apply punctuation removal, stopwords removal and lemmatization to a list of strings
I tried to use lemma_, is_stop and is_punct
data = ['We will pray and hope for the best',
    'Though it may not make landfall all week if it follows that track',
    'Heavy rains, capable of producing life-threatening flash floods, are possible']

import spacy
from spacy.lang.en.stop_words import STOP_WORDS

nlp = spacy.load("en")

doc = list(nlp.pipe(data))

data_clean = [[w.lemma_ for w in doc if not w.is_stop and not w.is_punct and not w.like_num] for doc in data]

I have the following error:
    AttributeError: 'spacy.tokens.doc.Doc' object has no attribute 'lemma_'
(same problem for is_stop and is_punct)

A: You iterate over the unprocessed list of strings data in the outer-loop, but you need to iterate over doc.
Further, your variables have unfavorable names, the following naming should be less confusing:
docs = list(nlp.pipe(data))
data_clean = [[w.lemma_ for w in doc if (not w.is_stop and not w.is_punct and not w.like_num)] for doc in docs]


text:
Q: How evil would it be to use type punning between trivially copyable structs? I have a library with a Swift interface that hides a C++ layer. In the C++, I have struct A { ...}. I want the Swift to pass around by-value copies of this struct (for various complicated reasons). Swift understands C declarations but not C++, so I'd need to declare some dummy C struct for it with the same size, e.g. struct FakeA { char data[/* size of A */]; }. Then, I could use type punning to go back and forth. Since A is trivially copyable, I would think it's OK. However, at cppreference.com it states, "Unlike in C, however, objects with trivial default constructors cannot be created by simply reinterpreting suitably aligned storage, such as memory allocated with std::malloc: placement-new is required to formally introduce a new object and avoid potential undefined behavior."
How undefined are we talking? Could it realistically cause problems, say, when compiling with Clang for arm64 and x86_64?

A: C++ abstracts the concept of a lifetime, even for pods with no constructors, C++ defines in specific terms when lifetime starts and ends of an object, that's why you can't just reinterpret bytes from a memory even if you know their layout match. It is undefined behavior because that is not start of lifetime of the object.
In practice, this is the kind of of UB that people still use though, because there's no equivalent non UB option.
std::start_lifetime_as<T> and new (p) std::byte[n] (formerly std::bless) would be the perfect remedy for this (http://wg21.link/p0593) but sadly not for now.


text:
Q: node:internal/modules/cjs/loader:1078 throw err; ^ I am having this error in windows 10 with npm  run command
:
node:internal/modules/cjs/loader:1063
 throw err;
^
Error: Cannot find module 'D:\mobile-version portfolio\
at Module._resolveFilename (node:internal/modules/cjs/loader:1060:15)
at node:internal/main/check_syntax:34:20 {
 code: 'MODULE_NOT_FOUND',
   requireStack: []
}

Node.js v19.6.0   someone help me please.
I have uninstalled and installed node.js, but didn't work for me, I also deleted node-modules and installed again but all is not working.
When I try to run any npm command i.e npm run start, npm run build or check linter errors with npx stylelint **/*.{css,scss} it throws the same error.am working with webpack and I need to run the command to update my changes in dist file from src file.
I also need to run and check linter errors and fix in my project. Here is my package.json file:
 "name": "to-do-list",
 "version": "1.0.0",
 "description": "README.md\r One attachment\r • Scanned by Gmail\r ",
 "main": "index.js",
 "private": true,
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "webpack serve --open",
   "build": "webpack --config webpack.config.js"
 },

 "repository": {
   "type": "git",
   "url": "git+https://github.com/Tracy-miranja/TO-DO-LIST.git"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "bugs": {
   "url": "https://github.com/Tracy-miranja/TO-DO-LIST/issues"
 },

 "homepage": "https://github.com/Tracy-miranja/TO-DO-LIST#readme",
 "devDependencies": {
   "@babel/core": "^7.17.8",
   "@babel/preset-env": "^7.16.11",
   "babel-eslint": "^10.1.0",
   "babel-loader": "^8.2.3",
   "css-loader": "^6.7.1",
   "eslint": "^7.32.0",
   "eslint-config-airbnb-base": "^14.2.1",
   "eslint-plugin-import": "^2.27.5",
   "hint": "^2.0.0",
   "html-webpack-plugin": "^5.5.0",
   "sass": "^1.49.9",
   "sass-loader": "^12.6.0",
   "style-loader": "^3.3.1",
   "stylelint": "^13.13.1",
   "stylelint-config-standard": "^21.0.0",
   "stylelint-csstree-validator": "^1.9.0",
   "stylelint-scss": "^3.21.0",
   "webpack": "^5.75.0",
   "webpack-bundle-analyzer": "^4.5.0",
   "webpack-cli": "^4.9.2",
   "webpack-dev-server": "^4.11.1"
 },

 "dependencies": {
   "lodash": "^4.17.21"
 }
}

A: Installing stylelint globally 'worked' for me. npm i -g stylelint@version
You can try it till a better solution is given.


text:
Q: Derivation of Jensens Inequality with Taylor Series In the proof of Jensen's inequality in a probabilistic setting, the book gives the following demonstration:

Expand the Taylor series of $f(x)$ around $\mu =\mathbb {E}[X]$.
$$f(x)=f(\mu)+f'(\mu)(x-\mu)+\frac {f''(\epsilon)(x-\mu)^2}{2}$$
For $\epsilon$ between $x$ and $\mu$. Since $f$ is convex, $f''(\epsilon)\ge 0$ therefore $f(X)\ge f(\mu)+f'(\mu)(X-\mu)$. Taking expectations of both sides gives
$$\mathbb{E}[f(X)]\ge f(\mu)$$
The part I do not understand is how they truncate the Taylor series to only three terms and are still able to say that the truncated expression equals $f(x)$. In my head, this should only be an approximation.

I suppose one must give $\epsilon$ as a function of $x$ but the justification if this step still eludes me, and if there are terms missing in the expansion, then the inequality does not necessarily follow.

How does justify the step of truncating the Taylor series to only three terms while still maintaining equality?

A: Notice that the last term is "for $\epsilon$ between $x$ and $\mu$." That is the error term, so it isn't an approximation. It is exact.
The error term is given by the mean value theorem.

A: In general, if we have an analytic function $f$, we can write out the Taylor series for $f$ around a point $x$ by
$$f(y)=\sum_{i=0}^\infty f^{(i)}(x)\frac{(y-x)^i}{i!}$$
and we'd have equality for all $y$ in some neighborhood of $x$. In general, when we don't have an analytic function, and say we just have a twice differentiable function (as in your case), the series above doesn't even make sense since we don't necessarily have $f^{(i)}(x)$ defined for $i=3,4,5...$ However it's still always true that for every $y$ is some neighborhood of $x$,we can find $z$ in between $x$ and $y$ (i.e. if $x\leq y$ then $x\leq z\leq y$ and if $x\geq y$ then $x\geq z\geq y$) such that
$$f(y)=f(x)+f'(x)(y-x)+\frac{f''(z)}{2}(y-x)^2.$$
The equality is exact, but just for our choice of $y$. We'd (maybe) have a different $z$ for a different choice of $y$ near $x$. In the proof of Jensen's inequality, the fact that $z$ may vary doesn't pose a problem because we just use the fact that $f''$ is nonnegative.


text:
Q: Retrieving object from mysql-database in spring+hibernate project doesn't work? I  created  2 classes for mapping with hibernate :
package com.pcd.ahmed.model;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name="etudiants")
public class Etudiant {
@Id
@GeneratedValue
@Size(min=4, max=6)
private String student_ID;

@NotEmpty
@Size(min=4, max=45)
private String firstname;

@NotEmpty
@Size(min=4, max=45)
private String lastname;

@NotNull
@Past
@DateTimeFormat(pattern="MM/dd/yyyy")
private Date date_birth;

@NotEmpty
@Size(min=3, max=4)
private String class_ID;
}

and
package com.pcd.ahmed.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name="student")
public class Student {

@Id
@GeneratedValue
private Long id;

@NotEmpty
@Size(min=4, max=20)
private String userName;

@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

@NotEmpty
@Size(min=4, max=8)
private String password;
}

but when I try to Retrieve objects from mysql-database tables using the repositories:
package com.pcd.ahmed.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pcd.ahmed.model.Student;

@Repository("studentRepository")
public interface StudentRepository extends JpaRepository<Student, Long> {

@Query("select s from Student s where s.userName = :userName")
Student findByUserName(@Param("userName") String userName);
}

and
package com.pcd.ahmed.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pcd.ahmed.model.Etudiant;

@Repository("studentRepository1")
public interface StudentRepository1 extends JpaRepository<Etudiant, String> {

@Query("select s from etudiants s where s.student_ID = :student_ID")
Etudiant findBystudent_ID(@Param("student_ID") String student_ID);

}

the error in :
package com.pcd.ahmed.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pcd.ahmed.model.Etudiant;
import com.pcd.ahmed.model.Student;
import com.pcd.ahmed.repository.StudentRepository;
import com.pcd.ahmed.repository.StudentRepository1;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository studentRepository;
private StudentRepository1 studentRepository1;
@Transactional
public Student save(Student student) {
    return studentRepository.save(student);
}
public Student profileget(String userName, String password) {
    Student stud = studentRepository.findByUserName(userName);

    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Parents")) {
        return stud;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Administrateur")) {
        return stud;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Enseignant")) {
        return stud;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Infirmiere")) {
        return stud;
    }

    return null;
}

public Etudiant studentget(String student_ID) {
    Etudiant etud = studentRepository1.findBystudent_ID(student_ID);
    return etud;
}

public int findByLogin(String userName, String password,Student stud) {
    stud = studentRepository.findByUserName(userName);

    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Parents")) {
        return 1;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Administrateur")) {
        return 2;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Enseignant")) {
        return 3;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Infirmiere")) {
        return 4;
    }

    return 0;
}

public boolean findByUserName(String userName) {
    Student stud = studentRepository.findByUserName(userName);

    if(stud != null) {
        return true;
    }

    return false;
}

}

when I call this function:
public Etudiant studentget(String student_ID) {
    Etudiant etud = studentRepository1.findBystudent_ID(student_ID);
    return etud;
}

it said:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [studentHibernateServlet] in context with path [/StudentEnrollmentWithSpring] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at      com.pcd.ahmed.service.StudentServiceImpl.studentget(StudentServiceImpl.java:42)
    at com.pcd.ahmed.controller.StudentController.login(StudentController.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

the first one is working but the second "StudentRepository1" doesn t
so how can I fix it? and thank you

A: I think you just have a typo in your HQL. Instead of etudiants, try changing it to Etudiant
@Repository("studentRepository1")
public interface StudentRepository1 extends JpaRepository<Etudiant, String> {

    // "Etudiant" was previously "etudiants"
    @Query("select s from Etudiant s where s.student_ID = :student_ID")
    Etudiant findBystudent_ID(@Param("student_ID") String student_ID);

}

UPDATE
You're still missing an @Autowired in your question above
@Autowired
private StudentRepository studentRepository;
private StudentRepository1 studentRepository1;

needs to be:
@Autowired
private StudentRepository studentRepository;

@Autowired
private StudentRepository1 studentRepository1;

It's also very confusing to follow your question since you keep editing it.

A: You didn't wire your studentRepository1 in StudentServiceImpl
I reproduced the error in my IDE. Please update this block seen below and then everything is gonna be fine.
@Autowired
private StudentRepository studentRepository;
@Autowired
private StudentRepository1 studentRepository1;


text:
Q: PhoneGap application not working on Google Ripple I'm developing a phoneGap application. When I test my application in the browser there is no problem. Everythings works well. But when I am try it in ripple, my javascript does not work.
In detail: The user can login the system and if it successfully redirects to another page (used jquery mobile) it works well in chrome, internet explorer, and firefox. But does not work in ripple.
My code is shown below:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title></title>
    <link rel="stylesheet" href="css/jquery.mobile-1.3.2.css">

 Ziro

            <form id="loginForm">

                     Kullanıcı Adı:
                    <input name="" id="userName"  placeholder="username" value="" type="text">

                     Password
                    <input name="" id="password"  placeholder="password" value="" type="password">

                <input type="submit" data-theme="a" data- icon="arrow-r" data-iconpos="left"
                value="Login">
            </form>
            Menü

 FF Yazılım

 Ziro Mobilya

                    Panel

                     Hakkımızda

                      Referans Resimleri

                     Servis Resimleri

                     Slogan

                     İstatistikler

                      Button

 FF Yazılım

 Hakkımızda

             Galeriden Resim Seç

                 Başlık:
                <input name="" id="aboutMeTitle" placeholder=""  value="" type="text" data-mini="true">

                 Açıklama
                <textarea name="" id="textarea2" placeholder=""  data-mini="true"></textarea>

             Kaydet

 FF Yazılım

My application structure is shown below:

Error code is:xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//localhost%3A30673/api/user/Get%3Fjson rippleapi.herokuapp.com Status Code:500 Internal Server Error I'am getting data from my localhost post adress:localhost:30673/api/user/Get'; It is working well in browser . And getting data from localhost:30673/api/user/Get. But in ripple it tries to get data from There: xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//localhost%3A30673/api/user/Get%3Fjson rippleapi.herokuapp.com
Need advice guys.

A: The issue that you are likely running into is that you are using Ripple's cross-domain proxy which is turned on in settings by default.
The cross-domain-proxy has 3 settings: "remote", "local" and "disabled".
In my situation I actually had to disable it, but in some cases you would be able to use "local".
Possible scenarios:
1) your local application calls a remote service somewhere on another server:
you would either use "remote" or "disabled" depending on the configuration on the remote server.
2) your local application is on "localhost" and you are making a call to another localhost accessible URL:
you would either use "local" or "disabled" depending on your cross domain settings and such.
3) you are running a local app that calls a server that is also local but in a vm or something that makes it inaccessible to a proxy on "localhost":
you need to have it set to "disabled", and make sure your api server has settings to allow cross-domain requests. Most notably you would want to set the "Access-Control-Allow-Origin" header.

A: I had the same issue. It was happening when I was trying to connect to my WebAPI service hosted on IISExpress.
After I changed hosting to my local IIS server, the error dissapeared and I was able to connect to my WebAPI service using Ripple. Of course, you will have to change url pointing to your service (in your case it is http://localhost:30673).


text:
Q: Proof of Karlin-Rubin's theorem I asked this question on Math Exchange, but as I did not receive a successful answer, maybe you could help me.
Karlin-Rubin's theorem states conditions under which we can find a uniformly most powerful test (UMPT) for a statistical hypothesis:

Suppose a family of density or mass functions $\{f(\vec{x}|\theta):\,\theta\in\Theta\}$ and we want to test $$\begin{cases} H_0:\,\theta\leq\theta_0 \\ H_A:\,\theta>\theta_0.\end{cases}$$If the likelihood ratio is monotone on a statistic $T(\vec{x})$ (that is, for every fixed $\theta_1<\theta_2$ in $\Theta$, the ratio $\frac{f(\vec{x}|\theta_2)}{f(\vec{x}|\theta_1)}$ is nondecreasing on $\{\vec{x}:\,f(\vec{x}|\theta_2)>0\text{ or }f(\vec{x}|\theta_1)>0\}$ as a function of $T(\vec{x})$, interpreting $c/0=\infty$ if $c>0$), then the test of critical region $\text{CR}=\{\vec{x}:\,T(\vec{x})\geq k\}$, where $k$ is chosen so that $\alpha=P(\text{CR}|\theta=\theta_0)$, is the UMPT of size $\alpha$.

In all the proofs I have read (for instance, in page 22 here or in "Statistical inference" by Casella-Berger, 2n edition, page 391), it is (more or less) said: "we can find $k_1$ such that, if $T(\vec{x})\geq k$, then $\frac{f(\vec{x}|\theta_2)}{f(\vec{x}|\theta_1)}\geq k_1$, and if $T(\vec{x})<k$, then  $\frac{f(\vec{x}|\theta_2)}{f(\vec{x}|\theta_1)}< k_1$". I would understand that statement if the likehood ratio were strictly increasing, but what about the case in which it is constant?
For example, if $X\sim U(0,\theta)$, the likelihood ratio is monotone on $T(\vec{x})=\max_{1\leq i\leq n}x_i$ ($n$ is the length of the sample $\vec{x}$), but not strictly increasing.
My questions are:

*

*Is the assertion between quotation marks true for every density or mass function with (not strictly) monotone likelihood ratio on $T$?

*And what about in the case of the uniform distribution?

A: $\newcommand\th\theta\newcommand\al\alpha$Even the following more general assertion is true:

Suppose that there is a statistic $T$ such that for all $\th_0$ and $\th_1$ such that $\th_0<\th_1$ there is a nondecreasing function $g_{\th_0,\th_1}$ such that for all $x$ we have
$$r_{\th_0,\th_1}(x):=\frac{f_{\th_1}(x)}{f_{\th_0}(x)}=g_{\th_0,\th_1}(T(x)).$$
Suppose that a test $\phi$ is such that for some real $k$ and all $x$
$$\phi(x)=\begin{cases}
1&\text{ if }T(x)>k, \\
0&\text{ if }T(x)<k
\end{cases}$$
(the test $\phi$ may be randomized, taking any value $\phi(x)$ in the interval $[0,1]$ if $x$ is such that $T(x)=k$).
Then the test $\phi$ is uniformly most powerful of level $\al:=E\phi(X)$ for the hypotheses as in the OP.

This follows because, for $c:=g_{\th_0,\th_1}(k)$, we have the implications $$r_{\th_0,\th_1}(x)>c\iff g_{\th_0,\th_1}(T(x))>c\implies T(x)>k\implies\phi(x)=1\tag{1}$$
(so that $H_0$ is rejected by the test $\phi$) and
$$r_{\th_0,\th_1}(x)<c\iff g_{\th_0,\th_1}(T(x))<c\implies T(x)<k\implies\phi(x)=0\tag{2}$$
(so that $H_0$ is not rejected by the test $\phi$) -- which means that $\phi$ is a Neyman--Pearson testfor any $\th_0$ and $\th_1$ such that $\th_0<\th_1$.
That $T$ is not strictly increasing causes no problems whatsoever, because in (1) and (2) we only need the left-to-right implications.

A: If it were to be constant then the statistical model $\{f(\vec{x}|\theta):\,\theta\in\Theta\}$ would only contain copies of the same density, i.e. one single density. In this case, inference is quite useless, but nonetheless the test is UMPT (and unbiased) since power and size agree for every test.


text:
Q: Optimalizing large amount of operations on Android I'm working on a particle system. It does a lot a LOT of calculations / calls on openGL Draw. So far I divided up the calculations so on every screen refresh it does a different part of the calculation it helps a lot but it is not enought.
I have 2 other ideas to improve the preformance:
1, Native code I know it should help but I have no idea how much and if it would worth the effort. Setting up and learning something new takes a lot of time.
2, Create threads to calculate different parts. Synchronizing could be a problem but at this point the only thing I care about is speed. The problem again I have no idea if it would help or not
My question is which method would be better or is there a better way that I didn't think about?


text:
Q: Set Dictionary Value to a Class? Is it possible to set a dictionary value to a class?
Not sure if I'm using a class in the proper manner here but something such as:
class ValueClass:

    def __init__(self,foo,foo2,foo3):

        self.foo=foo
        self.foo2=foo2
        self.foo3=foo3

res={}

with open('foo.txt','r') as lines:

     for line in lines:
         k=line.split()[4]
         foo=line.split()[5]
         foo2=line.split()[6]
         foo3=line.split()[7]
         res[k]=ValueClass

A: Using this code, you set res[k] to be the type ValueClass, not actually an instance of it (which I'm guessing isn't your intention?).
You'd probably want to do this:
class ValueClass(object):
   def __init__(self, foo=None, foo2=None, foo3=None):
     self.foo = foo
     self.foo2 = foo2
     self.foo3 = foo3

res = {}

for line in lines:
  k, foo, foo2, foo3 = line.split()[4:7]
  res[k] = ValueClass()

If you want to initialize the class with those values, you can do this:
for line in lines:
  k, foo, foo2, foo3 = line.split()[4:7]
  res[k] = ValueClass(foo, foo2, foo3)

This lets you set the class's properties afterwards, as you made res[k] an instance of ValueClass.


text:
Q: What does formString(System.getenv("...")) mean? In build.gradle, the following is under a product flavor:
buildConfigField 'String', 'API_URL', formString(System.getenv("DEV_API_URL"))
What does formString(System.getenv("DEV_API_URL")) mean?
I am used to seeing the formString as a static value (and I can reference it in code as BuildConfig.API_URL") but am having a hard time figuring out what this code means as well as where "DEV_API_URL" is defined. Guidance and links are appreciated!

A: 1) formString must be a custom function defined somewhere in your build.gradle as there is no such function in Groovy or Java. If you cant figure out where it is, use a text search tool like ag (https://github.com/ggreer/the_silver_searcher)
2) System.getenv is a call that retrieves an environment variable defined on your machine, more here: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getenv(java.lang.String).


text:
Q: Расположение элементов в GridBarLayout Имеется следующий код:
package com.company;

import javax.swing.*;
import java.awt.*;

class MyFrame extends JFrame {
    private static JLabel portText = new JLabel("Port:");

    public static String getPortValue() {
        return port.getText();
    }

    public static String getBrokerAddressValue() {
        return brokerAddress.getText();
    }

    public static String getTopicValue() {
        return topic.getText();
    }

    public static String getMessageValue() {
        return message.getText();
    }

    public static String getUsernameValue() {
        return username.getText();
    }

    private static JLabel brokerAddressText = new JLabel("Broker ip address:");
    private static JLabel topicText = new JLabel("Topic");
    private static JLabel messageText = new JLabel("Message:");
    private static JLabel usernameText = new JLabel("Username:");
    private static JTextField port = new JTextField(4);
    private static JTextField brokerAddress = new JTextField(10);
    private static JTextField topic = new JTextField(10);
    private static JTextField message = new JTextField(20);
    private static JTextField username = new JTextField(10);
    private static JButton connect = new JButton("Connect");
    private static JButton disconnect = new JButton("Disconnect");
    private static JButton subscribe = new JButton("Subscribe");
    private static JButton unsubscribe = new JButton("Unsubscribe");
    private static JButton publish = new JButton("Publish");

    MyFrame(){
        super("MQTT client");
        JPanel jPanel = new JPanel();
        getContentPane().add(jPanel);
        jPanel.setLayout(new GridBagLayout());

        GridBagConstraints constraints1 = new GridBagConstraints();
        constraints1.weightx = 0;
        constraints1.weighty = 0;
        constraints1.gridx = 0;
        constraints1.gridy = 0;
        constraints1.gridheight = 1;
        constraints1.gridwidth = 1;
        constraints1.insets.right = 10;
        constraints1.insets.bottom = 10;
        jPanel.add(portText, constraints1);

        GridBagConstraints constraints2 = new GridBagConstraints();
        constraints2.weightx = 0;
        constraints2.weighty = 0;
        constraints2.gridx = 0;
        constraints2.gridy = 1;
        constraints2.gridheight = 1;
        constraints2.gridwidth = 1;
        constraints2.insets.right = 10;
        constraints2.insets.bottom = 10;
        jPanel.add(port, constraints2);

        GridBagConstraints constraints3 = new GridBagConstraints();
        constraints3.weightx = 0;
        constraints3.weighty = 0;
        constraints3.gridx = 1;
        constraints3.gridy = 0;
        constraints3.gridheight = 1;
        constraints3.gridwidth = 1;
        constraints3.insets.right = 10;
        constraints3.insets.bottom = 10;
        jPanel.add(brokerAddressText, constraints3);

        GridBagConstraints constraints4 = new GridBagConstraints();
        constraints4.weightx = 0;
        constraints4.weighty = 0;
        constraints4.gridx = 1;
        constraints4.gridy = 1;
        constraints4.gridheight = 1;
        constraints4.gridwidth = 1;
        constraints4.insets.right = 10;
        constraints4.insets.bottom = 10;
        jPanel.add(brokerAddress, constraints4);

        GridBagConstraints constraints5 = new GridBagConstraints();
        constraints5.weightx = 0;
        constraints5.weighty = 0;
        constraints5.gridx = 2;
        constraints5.gridy = 0;
        constraints5.gridheight = 1;
        constraints5.gridwidth = 1;
        constraints5.insets.right = 10;
        constraints5.insets.bottom = 10;
        jPanel.add(connect, constraints5);

        GridBagConstraints constraints6 = new GridBagConstraints();
        constraints6.weightx = 0;
        constraints6.weighty = 0;
        constraints6.gridx = 2;
        constraints6.gridy = 1;
        constraints6.gridheight = 1;
        constraints6.gridwidth = 1;
        constraints6.insets.right = 10;
        constraints6.insets.bottom = 10;
        jPanel.add(disconnect, constraints6);

        GridBagConstraints constraints7 = new GridBagConstraints();
        constraints7.weightx = 0;
        constraints7.weighty = 0;
        constraints7.gridx = 0;
        constraints7.gridy = 3;
        constraints7.gridheight = 1;
        constraints7.gridwidth = 1;
        constraints7.insets.right = 10;
        constraints7.insets.bottom = 10;
        jPanel.add(topicText, constraints7);

        GridBagConstraints constraints8 = new GridBagConstraints();
        constraints8.weightx = 0;
        constraints8.weighty = 0;
        constraints8.gridx = 0;
        constraints8.gridy = 4;
        constraints8.gridheight = 1;
        constraints8.gridwidth = 1;
        constraints8.insets.right = 10;
        constraints8.insets.bottom = 10;
        jPanel.add(topic, constraints8);

        GridBagConstraints constraints9 = new GridBagConstraints();
        constraints9.weightx = 0;
        constraints9.weighty = 0;
        constraints9.gridx = 1;
        constraints9.gridy = 3;
        constraints9.gridheight = 1;
        constraints9.gridwidth = 1;
        constraints9.insets.right = 10;
        constraints9.insets.bottom = 10;
        jPanel.add(subscribe, constraints9);

        GridBagConstraints constraints10 = new GridBagConstraints();
        constraints10.weightx = 0;
        constraints10.weighty = 0;
        constraints10.gridx = 1;
        constraints10.gridy = 4;
        constraints10.gridheight = 1;
        constraints10.gridwidth = 1;
        constraints10.insets.right = 10;
        constraints10.insets.bottom = 10;
        jPanel.add(unsubscribe, constraints10);

        GridBagConstraints constraints11 = new GridBagConstraints();
        constraints11.weightx = 0;
        constraints11.weighty = 0;
        constraints11.gridx = 0;
        constraints11.gridy = 6;
        constraints11.gridheight = 1;
        constraints11.gridwidth = 1;
        constraints11.insets.right = 10;
        constraints11.insets.bottom = 10;
        jPanel.add(messageText, constraints11);

        GridBagConstraints constraints12 = new GridBagConstraints();
        constraints12.weightx = 0;
        constraints12.weighty = 0;
        constraints12.gridx = 0;
        constraints12.gridy = 7;
        constraints12.gridheight = 1;
        constraints12.gridwidth = 2;
        constraints12.insets.right = 10;
        constraints12.insets.bottom = 10;
        jPanel.add(message, constraints12);

        GridBagConstraints constraints13 = new GridBagConstraints();
        constraints13.weightx = 0;
        constraints13.weighty = 0;
        constraints13.gridx = 1;
        constraints13.gridy = 6;
        constraints13.gridheight = 1;
        constraints13.gridwidth = 1;
        constraints13.insets.right = 10;
        constraints13.insets.bottom = 10;
        jPanel.add(publish, constraints13);

        GridBagConstraints constraints14 = new GridBagConstraints();
        constraints14.weightx = 0;
        constraints14.weighty = 0;
        constraints14.gridx = 2;
        constraints14.gridy = 3;
        constraints14.gridheight = 1;
        constraints14.gridwidth = 1;
        constraints14.insets.right = 10;
        constraints14.insets.bottom = 10;
        jPanel.add(usernameText, constraints14);

        GridBagConstraints constraints15 = new GridBagConstraints();
        constraints15.weightx = 0;
        constraints15.weighty = 0;
        constraints15.gridx = 2;
        constraints15.gridy = 4;
        constraints15.gridheight = 1;
        constraints15.gridwidth = 1;
        constraints15.insets.right = 10;
        constraints15.insets.bottom = 10;
        jPanel.add(username, constraints15);

        jPanel.revalidate();
        setBounds(750,250,500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

И вроде как некоторые элементы находятся через строку друг от друга, например
constraintsN.gridx = 2;
constraintsN.gridx = 0;

Но расстояние между ними такое же, как и между двумя соседними рядами. Скорее всего, как я думаю, это из-за того, что ряды между ними (в данном случае 1) не заполнены ничем, поэтому имеют высоту 0. Но как это исправить, ну или как-то по другому задать отступы. Или только отступ снизу от элемента? И еще вопрос, как растянуть например кнопку по ширине всей клетки?

A: Вот тут подробно расписано
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
А это пример с комментариями:
package com.company;

import javax.swing.*;
import java.awt.*;

import static java.awt.GridBagConstraints.*;

class MyFrame extends JFrame {
    private static JLabel portText = new JLabel("Port:");

    public static String getPortValue() {
        return port.getText();
    }

    public static String getBrokerAddressValue() {
        return brokerAddress.getText();
    }

    public static String getTopicValue() {
        return topic.getText();
    }

    public static String getMessageValue() {
        return message.getText();
    }

    public static String getUsernameValue() {
        return username.getText();
    }

    private static JLabel brokerAddressText = new JLabel("Broker ip address:");
    private static JLabel topicText = new JLabel("Topic");
    private static JLabel messageText = new JLabel("Message:");
    private static JLabel usernameText = new JLabel("Username:");
    private static JTextField port = new JTextField(4);
    private static JTextField brokerAddress = new JTextField(10);
    private static JTextField topic = new JTextField(10);
    private static JTextField message = new JTextField(20);
    private static JTextField username = new JTextField(10);
    private static JButton connect = new JButton("Connect");
    private static JButton disconnect = new JButton("Disconnect");
    private static JButton subscribe = new JButton("Subscribe");
    private static JButton unsubscribe = new JButton("Unsubscribe");
    private static JButton publish = new JButton("Publish");
    private static JButton publish1 = new JButton("Publish");
    private static JButton publish2 = new JButton("Publish");

    private static GridBagConstraints costs(int location, int fill) {
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weighty = 1.0;
        constraints.weightx = 1.0;
        constraints.fill = fill;
        constraints.anchor = location;
        return constraints;
    }

    private static GridBagConstraints costs(int location, int fill,
                                            int gx, int gy) {
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weighty = 1.0;
        constraints.weightx = 1.0;
        constraints.gridx = gx;
        constraints.gridy = gy;
        constraints.fill = fill;
        constraints.anchor = location;
        return constraints;
    }

    private static GridBagConstraints costs(int location, int fill,
                                            int gx, int gy,
                                            int gw, int gh) {
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weighty = 1.0;
        constraints.weightx = 1.0;
        constraints.gridx = gx;
        constraints.gridy = gy;
        constraints.gridwidth = gw;
        constraints.gridheight = gh;
        constraints.fill = fill;
        constraints.anchor = location;
        return constraints;
    }

    private static GridBagConstraints costs(int location, int fill,
                                            int gx, int gy,
                                            int gw, int gh,
                                            int top, int left, int bottom, int right) {
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weighty = 1.0;
        constraints.weightx = 1.0;
        constraints.gridx = gx;
        constraints.gridy = gy;
        constraints.gridwidth = gw;
        constraints.gridheight = gh;
        constraints.fill = fill;
        constraints.anchor = location;
        constraints.insets = new Insets(top, left, bottom, right);

        return constraints;
    }

    MyFrame() {
        super("MQTT client");

        JPanel jPanel = new JPanel();
        add(jPanel);

        jPanel.setLayout(new GridBagLayout());

        //constraints.anchor: положение (внутри ячейки) элемента относительно сторон (вверх,право,центр,углы и тд)
        //сonstraints.fill: заполнение (внутри ячейки) элемента (растягивание)
        //constraints.gridx: положение элемента по x (номер ячейки)
        //constraints.gridy: положение элемента по y (номер ячейки)
        //constraints.gridwidth: длина элемента по x (количество ячеек)
        //constraints.gridheight: ширина элемента по y (количество ячеек)
        //
        //
        //constraints.insets: поля в пикселях вокруг элемента

        //у метода costs есть перегрузка поэтому вводить не обязательно всё
        // (это сильно экономит место и улучшает читабельность кода)
        JTabbedPane jTabbedPane = new JTabbedPane();
        jPanel.add(jTabbedPane,
                //constraints.anchor, сonstraints.fill,
                costs(LAST_LINE_END, BOTH,
                        //constraints.gridx, constraints.gridy
                        0, 0,
                        //constraints.gridwidth, constraints.gridheight
                        0, 0,
                        //constraints.insets
                        //top,left,bottom,right
                        10, 10, 10, 10));

        JPanel page1 = new JPanel();
        page1.setName("PAGE 1");
        JPanel page2 = new JPanel();
        page2.setName("PAGE 2");
        JPanel page3 = new JPanel();
        page3.setName("PAGE 3");

        jTabbedPane.add(page1);
        jTabbedPane.add(page2);
        jTabbedPane.add(page3);

        page1.setLayout(new GridBagLayout());
        page2.setLayout(new GridBagLayout());
        page3.setLayout(new GridBagLayout());

        page1.add(portText, costs(PAGE_START, NONE, 0, 0));
        page1.add(port, costs(PAGE_START, HORIZONTAL, 1, 0, 2, 1));
        page1.add(brokerAddressText, costs(PAGE_START, NONE, 0, 1));
        page1.add(brokerAddress, costs(PAGE_START, HORIZONTAL, 1, 1, 2, 1));
        page1.add(connect, costs(LAST_LINE_START, NONE, 0, 2));
        page1.add(publish, costs(PAGE_END, NONE, 1, 2));
        page1.add(disconnect, costs(LAST_LINE_END, NONE, 2, 2));

        page2.add(topicText, costs(LINE_START, NONE, 0, 0));
        page2.add(topic, costs(CENTER, BOTH, 1, 0, 2, 1));
        page2.add(subscribe, costs(LAST_LINE_START, NONE, 0, 2));
        page2.add(publish1, costs(PAGE_END, NONE, 1, 2));
        page2.add(unsubscribe, costs(LAST_LINE_END, NONE, 2, 2));

        page3.add(messageText, costs(LINE_START, NONE, 0, 0));
        page3.add(message, costs(CENTER, BOTH, 1, 0, 2, 1));
        page3.add(publish2, costs(PAGE_END, NONE, 1, 2));

        //set design style, depends on OS:
        try {

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(jPanel);

        } catch (Exception ignored) {
        }

        jPanel.revalidate();
        setBounds(750, 250, 500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}


text:
Q: umbraco event generation How can we add events to a button using umbraco? My requirement is I have a button "button1" which is in a usercontrol page "login.ascx".whenever I click the button I need to go to home.ascx

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:TextBox ID="txtpass" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="login" />
<asp:Button ID="Button2" runat="server" Text="Register" onclick="Button2_Click"
    style="height: 26px" />

<asp:Label ID="lblmsg" runat="server"></asp:Label>

Any ideas?

A: you can't redirect to a usercontrol ie can't go from login.ascx to home.ascx.
You can do one thing add the login usercontrol as macro in one content page in umbraco and add home.ascx as other macro in other content page.
Then you can redirect from one content page to other using Response.Redirect.

A: With .NET usercontrols in Umbraco, you write them in exactly the same way you would for any other ASP.NET webforms application/website.
Your code-behind should look like this:
protected void Button1_Click(object sender, EventArgs e) {
    Response.Redirect("~/home.aspx");
}

If you want to specify a particular content node to redirect to, then you can specify a property on your usercontrol, and then when you create your Umbraco macro in the Developer section, you will be able to include the usercontrol property as a macro property, and add a Content Picker type to it to make it user-friendly for an admin to specify which page to redirect to. Example:
partial class MyUserControl : UserControl {
    public int NodeToRedirectTo { get; set; }
    protected void Button1_Click(object sender, EventArgs e) {
        Response.Redirect(umbraco.library.NiceUrl(NodeToRedirectTo));
    }
}

Hope this helps.
Benjamin


text:
Q: Pattern matching within custom toJson implementation Let's say I have a type like so:
data MyError = CustomError | ProcessExecError !SomeException deriving (Show, Generic)

instance ToJSON MyError where
   toJSON = genericToJSON defaultOptions

This fails to compile with:
No instance for (ToJSON SomeException)

So I rewrite like so:
instance ToJSON FlockError where
    toJSON (ProcessExecError _ _) = "ProcessExecError"
    toJSON otherType              = genericToJSON defaultOptions otherType

This still fails with:
    • No instance for (ToJSON SomeException)
    arising from a use of 'genericToJSON'
• In the expression: genericToJSON defaultOptions otherType
  In an equation for 'toJSON':
      toJSON otherType = genericToJSON defaultOptions otherType
  In the instance declaration for 'ToJSON FlockError'
 |
47 |     toJSON otherType              = genericToJSON defaultOptions otherType

My question is why? Why doesn't the pattern match allow me to write this given that only ProcessExecError has a SomeException argument?


text:
Q: Misplaced table in UIView after reordering More-TabBarItems I have a UITabBarController with several UiTabBarItems. Every TabBarItem leads to a NavigationController where the root view contains a UITable that takes the whole screen size.
Let's say the initial order of the TabBarItems is:
"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"
As long as I leave them in that order everything works very well. But not when I reorder the items in the App by tapping "Edit" in the more tab for example to the following order:
"Item9", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item1"
After reordering the Items, "Item 1" misplaces the UITable in the root view. It seems like above the table has been added a space for a second, not visible NavigationBar.
Does anyone know why or has dealed with the same problem and can tell me what to do to prevent that.

A: Are you using xib's for your viewController that is inside the navigation controller? If so open the xib in interface builder and select the main view of controller and in right panel under "Simulated Metrics" set top bar to "Navigation Bar" from dropdown list.


text:
Q: Create React App and Git Hub pages I've never user gh-pages before so I'm pretty confused on how it works. I followed this guide over on the create react app page for how to deploy your app to git hub, however every time I try I get an error:
> gh-pages -d build

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: spawn git ENOENT
    at exports._errnoException (util.js:1018:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
    at onErrorNT (internal/child_process.js:367:16)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    at Module.runMain (module.js:606:11)
    at run (bootstrap_node.js:390:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:505:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myApp_game@0.1.0 deploy: `gh-pages -d build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myApp_game@0.1.0 deploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I have no idea what this means or how to fix it.

A: If anyone has a similar problem its because git is not added to your PATH. I was running npm run deploy from command prompt in windows, when I ran it in the git shell it worked perfectly.


text:
Q: How do I properly get formdata using Python's cgi module? I'm trying to create a date from my form data, but it keeps coming up as an error when running the module. The error is:
Traceback (most recent call last):
  File "/Users/Andrew/Desktop/weekday.py", line 19, in <module>
    weekday = calendar.weekday(year, month, day)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/calendar.py", line 113, in weekday
    return datetime.date(year, month, day).weekday()
TypeError: an integer is required

Here is my code:
import cgi
import calendar

form = cgi.FieldStorage()

print """Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Weekday</title>
</head><body>
"""

year= form.getvalue("year")
month= form.getvalue("month")
day= form.getvalue("day")

weekday = calendar.weekday(year, month, day)

if weekday == 0:
   print "<p> That's a Monday </p>"

A: Try calling int() on the form value like so:
year= int(form.getvalue("year"))
month= int(form.getvalue("month"))
day= int(form.getvalue("day"))


text:
Q: python sqlacademy query filter I am having some trouble with sqlacademy in Python. I am trying to filter a record in a database.
period_filter and process_filter are passed as arguments to this function.
This gives me one record. The one that I expect:
    for x in session.query(ProcessStatus).filter(ProcessStatus.reporting_period == period_filter and
     ProcessStatus.process_name == process_filter):
        print(x.id, x.process_name)

This gives me an error saying there i more than one record:
    id_to_update = session.query(ProcessStatus).filter(ProcessStatus.reporting_period == period_filter
     and ProcessStatus.process_name == process_filter).one()

I tried using the last approach to update a record in database, but I updated an incorrect record (I used .first()  and not .one() in that case), as I knew only one record should satisfy both filter conditions.
I would prefer the last approach as I would like to store the object in a variable directly, as I need to  pass it to another function.


text:
Q: Search for issues in current sprint in JIRA I am trying to pull all issues (resolved or not) from the current sprint and display that information. I am using a JIRA REST Java client to achieve this. I am quite new to JIRA and the JRJC so would like all the help I can get really.
This is the code I have written so far:
SearchResult allIssuesInSprint = restClient.getSearchClient().searchJql("sprint = \"" + 29 + "\" order by rank").claim();
Iterable<Issue> allIssues = allIssuesInSprint.getIssues();
for (Issue issue : allIssues) {
    System.out.println("Key: " + issue.getKey());
    System.out.println("Type: " + issue.getIssueType());
    System.out.println("Status: " + issue.getStatus());
    System.out.println("Priority: " + issue.getPriority());
}

Again, I am new to JIRA's JAR files, so I'm not certain on how to use them. Any help would be appreciated.


text:
Q: PHP class hierarchy - highest class in the hierarchy I am interested to know if PHP has a super class like Java's Object.
The reason I would like to know is that I want to overload it for the purpose of gaining insight to my large PHP project. I aim to overload the class to determine what is being called and develop some knowledge about classes which may be deprecated/aren't used.
Potentially, this may be a question of a tool that you may point me to (as I am sure there would be something like this already). I have searched and couldn't find anything (potentially bad google foo skills) and in the case the tool is found I am happy to alter the question so not as to mislead others who find this.
Many thanks everyone.

A: There is no superclass in php. And there is no overloading since PHP is not type save.
However there are tools detecting dead code in your project, e.g. phpdcd developed primarily by Sebastian Bergmann. Although it has some limitations it should find most of your dead code.
You might want to read this thread on stackoverflow for some more solutions.


text:
Q: How to change a method to work with my 2-D Array in Java I have written a program using 2 separate arrays but want to combine the arrays (velocity and degrees) into one single multidimensional array called distance. I have never used 2-D arrays before and I am sure my code may be hard to understand.
I have rewritten most of the program but I am getting held up in the method "calcDistance". I tried to rewrite the method but it just turned into a big mess.
double [][] distance;

Catapult(double[][] d){
   distance = d;
}

public double [][] calcDistance(){

    double [][] total = {{0,0,0,0,0,0,0} , {0,0,0,0,0,0,0}};

    for (int row = 0; row < distance.length; row++){

        for (int column = 0; column < distance.length; column++){

        total[row][column] = (Math.pow(distance[column]/2.237, 2) * Math.sin(2 * Math.toRadians(distance[column]))/9.8);

       }
    }

    return total;
}

I get a bad operand error when dividing by 2.237 and an incompatible types error when using distance[column]. Now my two problems are
1) How can I fix this method and what did I initially do wrong to cause the error
2) How can I implement both parts of my multi-d array distance in the method because as of right now it only runs through the columns of one row in "distance"

A: I really recommand you to use iterator since it make everything easier:
public class Catapult {
    double [][] distance;

    Catapult(double[][] d){
       distance = d;
    }

    public double [][] calcDistance(){

        double [][] total = new double[2][7];

        int i=0;

        for (double[] row : distance) {

            int j=0;

            for (double value : row) {

                total[i][j] = (Math.pow(value/2.237, 2) * Math.sin(2 * Math.toRadians(value))/9.8);

                ++j;

            }

            ++i;

        }

        return total;
    }
}


text:
Q: If a is a non-zero real number and b is a positive real number and $2ba^4 + ba^3 + a^2 + ba + 2b = ka^2$, then the least possible value of $k$ is? Least possible value of $k$ is:
$2b + 1$
$2b - 1$
I wrote it in the form of dividing the LHS with $a^2$, and dividing each element with $a^2$, and writing down the summation of terms only to be equated with $k$.
But, I can't seem to get anywhere. Some help will surely be appreciated!


text:
Q: XPath getting a sequence of element tags (Java / Saxon) I am using Java with Saxon HE 9.4 so I can have XPath 2.0 support.
Given the following XML instance document:
<entities>
    <entity>
        <person>
            James
        </person>
    </entity>
    <entity>
        <legalEntity>
            ACME
        </legalEntity>
    </entity>
</entities>

I know I can get a list of the entity element tags by doing a:
XPathExpression expr = xpath.compile("/entities/entity/*");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0 ; i < nodes.getLength() ; i++)
    System.out.println("element name = "+ nodes.item(i).getNodeName());

The above will output:
element name = person
element name = legalEntity

... as expected.
However, the logic is spread in two places: the XPath expression itself, and the call to getNodeName method. What I would like is an XPath expression that would return a generic list of results, which I could iterate over by calling some generic method (not getNodeName).
This way, all the logic could reside in the XPath expression itself and my code could just keep the XPath strings in a file and process them at runtime to get lists of results.
Trying the XPAth expression /entities/entity/*/name() only fetches the first value (person):
XPathExpression expr = xpath.compile("/entities/entity/*/name()");
System.out.println("element name = "+expr.evaluate(doc));

... and the code breaks at runtime if I try to cast that to a NodeList:
XPathExpression expr = xpath.compile("/entities/entity/*/name()");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0 ; i < nodes.getLength() ; i++) {
    ...

(the above fails with: net.sf.saxon.trans.XPathException: Cannot convert XPath value to Java object: required class is org.w3c.dom.NodeList; supplied value has type xs:string)
So is there a generic way to get XPath expressions evaluate to list of results (which could be element tags, element values, attribute values and tags, etc.) so that the code iterating over these results is the same in all cases and doesn't have to differentiate between calls to getNodeName() or getNodeValue() ?

A: You're using the JAXP interface to XPath. This is designed for XPath 1.0, and only recognizes the XPath 1.0 data types (string, node-set etc). You want to do a query that returns a list of strings (or perhaps QNames), so you will need to use an API that supports such data types - specifically, you need to move to Saxon's s9api API.
In the s9api interface, the XPathSelector object (see http://www.saxonica.com/documentation/#!javadoc/net.sf.saxon.s9api/XPathSelector) implements Java's Iterable interface, so you can use it directly in a Java "for-each" instruction to process the results as a sequence of XdmItem objects; the XdmItems can be nodes or atomic values, in fact any type defined in the XPath 2.0 data model.
You can use s9api to run XPath expressions against either Saxon's native tree model (built using the s9api DocumentBuilder) or against external models such as DOM, JDOM, XOM etc. Using Saxon's native model is much faster than any of the external models.


text:
Q: Calculate Java Int Overflow Is there a formula to calculate what the overflow of a Java int would be?
Example: if I add 1 to Integer.MAX_VALUE; the answer is not 2147483648, but rather -2147483648.
Question: if I wanted to calculate what Java would print for a value larger than 2^32, is there an easy mathematical expression (theoretical, not in code)?

A: ((x + 231) mod 232) - 231
Is this what you're looking for?  That should be the result of any mathematical operation on a machine that uses 32-bit signed 2's complement integers.  That is, if the mathematical value of an operation returns x, the above formula gives the integer that would actually be stored (if the operation doesn't fault, and it's not a "saturating" operation).
Note that I'm using "mod" with a mathematical definition, not the way the % operator works in Java or C.  That is, A mod B, where A and B are integers and B > 0, always returns an integer in the range 0 .. B-1, e.g. (-1) mod 5 = 4.  More specifically, A mod B = A - B*floor(A/B).

A: In java an int is 32 bits but it is also signed, which means that the first bit is the "negative" sign. 1 means negative and 0 means positive. Because of this, the largest number is 2147483647 (0111 1111 1111 1111 1111 1111 1111 1111). If you add 1 it makes it 1000 0000 0000 0000 0000 0000 0000 0000 which translates to -2147483648. For any values larger than that you would need to use a long

A: I believe this would work:
 int expected = ((val + Integer.MAX_VALUE) % Integer.MAX_VALUE) - Integer.MAX_VALUE;


text:
Q: "Invalid project" error form Google API Javascript client I am starting to play with Google Cloud DNS and I would like to hack a small Javascript project for listing/editing zones / resourceRecords.
I started on the "Getting Started" page which explains and offers some samples of the JS query/edit process. The thing is I got at some point where Google API responds with and "Invalid project" error for all supplied values of the 'project' parameter. I am using the clientID for the web application from the Google Developer Console for the oAuth part.  The project name I am using is the string named PROJECT ID in google (the same one I am using successfully in the gcloud command-line tools or the on-line JS testground).
According to this: https://content.googleapis.com/discovery/v1/apis/dns/v1beta1/rpc the dns.resourceRecordsSets.list requires two parameters: managedZone and project. If I do a call without params I get this:
[
 {
  "error": {
   "code": 400,
   "message": "Required value: managedZone",
   "data": [
    {
     "domain": "global",
     "reason": "required",
     "message": "Required value: managedZone"
    },
    {
     "domain": "global",
     "reason": "required",
     "message": "Required value: project"
    }
   ]
  },
  "id": "gapiRpc"
 }
]

which is perfectly fine...
Next I add the project and the managedZone params and then I get this:
[
 {
  "error": {
   "code": 400,
   "message": "Invalid parameter: project",
   "data": [
    {
     "domain": "global",
     "reason": "invalidParameter",
     "message": "Invalid parameter: project",
     "locationType": "parameter",
     "location": "project"
    }
   ]
  },
  "id": "gapiRpc"
 }
]

Here is my API call code.... I also tried checking the JS code from Google with no success in finding the "Invalid parameter" code...
gapi.client.load('dns', 'v1beta1', function() {

          var request = gapi.client.dns.resourceRecordSets.list({
            'project': 'lolName',
            'managedZone': 'lolZone'
          });

          request.execute(function(resp) {

            console.log(resp);

            if (resp.code == 200) {
                 // do some displaying
            }
            else {
              document.getElementById('content').appendChild(document.createTextNode('Error: ' + resp.message));
            }
          });


text:
Q: Android: cancelling alarm in service I am starting a series of alarms inside an activity to start a service after specific time. After the service is started I want to cancel that particular alarm and not any other alarm.
Below is the code for starting the alarm.
Calendar calendar = Calendar.getInstance();
Intent intent = new Intent(StatAlarmActivity.this, AndroidService.class);
PendingIntent pIntent = PendingIntent.getService(StatAlarmActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), i*24*60*60*1000, pIntent); //i varies, i is no of days after which the service will start

How can I cancel a particular alarm after the service is started? I tried below code inside the AndroidService but I can't access StartAlarmActivity.this and getSystemService here.
Calendar calendar = Calendar.getInstance();
Intent intent = new Intent(StatAlarmActivity.this, AndroidService.class);
PendingIntent pIntent = PendingIntent.getService(StatAlarmActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pIntent);

Please help me out.

A: Try getActivity() instead of StatAlarmActivity.this if you are cancelling the alarm manager in a different activity than you start.
The first argument is the context.
From http://developer.android.com/reference/android/content/Intent.html#Intent(android.content.Context, java.lang.Class)
Syntax :
public Intent (Context packageContext, Class cls)
Parameters :
packageContext  A Context of the application package implementing this class.
cls The component class that is to be used for the intent.


text:
Q: Cannot open Office 2007 files from browser in ASP.NET application I have an ASP.NET web page that opens a requested file and writes it into response so that file is supposed to open in browser.  It works fine, but with Office 2007 file types (.xlsx, .docx, ...) does not work properly.  Basically, it returns nothing, an empty response, a blank response.
Actually, it only happens in my live servers (Windows Server 2008).  In my test servers it works fine (and they are Windows Server 2008 too!).
The code looks like this:
string filePath = @"C:\mytests\test.docx";
string fileName = @"test";

Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = contentType;
Response.AddHeader(
   "content-disposition",
   "inline; filename=\"" + fileName + "\"");
Response.TransmitFile(filePath);

A: Investigate the MIME settings for Internet Explorer on the servers affected with this problem

A: Try adding Response.End() at the end to close.

A: On the live server, check the MIME Types in the Internet Information Services (IIS) Manager.
I think:
.docx should be application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xlsx should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

A: Is it possible your live servers are in a different security zone to your test servers?  e.g. Intranet vs. Internet?


text:
Q: How to use Bootstrap 4 (3) Mixins How to use Bootstrap mixins. I use Bootstrap 4 in combination with CSS Modules, SCSS. For example this is a bootstrap mixins for input-size.
@mixin input-size($parent, $input-height, $padding-y, $padding-x, $font-size, $line-height, $border-radius) {
  #{$parent} {
    height: $input-height;
    padding: $padding-y $padding-x;
    font-size: $font-size;
    line-height: $line-height;
    @include border-radius($border-radius);
  }

  select#{$parent} {
    height: $input-height;
    line-height: $input-height;
  }

  textarea#{$parent},
  select[multiple]#{$parent} {
    height: auto;
  }
}

If I want to use it how would I do it?
First.jsx
<form>
  <div className={`form-group ${styles.formula}`}>
    Email address
    <input type='email' className='form-control' id='exampleInputEmail1' aria-describedby='emailHelp' placeholder='Enter email' />
    We'll never share your email with anyone else.

I am using it like this. The customBtn works good so I know it is not a settings problem. Input element is not?
styles.scss
.customBtn {
  @include button-variant(white, purple, black)
}
.formula {
  @include input-size('.form-control', 70px, 12px, 12px, 32px, 5em, 0)
}

*Update
Fixed it.
It seems there was a problem with CSS Modules and Bootstrap class naming combination. I managed to resolve it like this.
First.jsx
<form>
  <div className={`form-group ${styles.formula}`}>
    Email address
    <input type='email' className={`form-control ${styles.formControl}`} id='exampleInputEmail1' aria-describedby='emailHelp' placeholder='Enter email' />
    We'll never share your email with anyone else.

styles.scss
.customBtn {
  @include button-variant(white, purple, black)
}
.formula {
  @include input-size('.formControl', 70px, 12px, 12px, 32px, 5em, 0)
}

A: Make sure you're passing in the correct param values to the mixin. For example,
@import "bootstrap";
.my-custom-input {
  @include input-size('.form-control', 70px, 12px, 12px, 32px, 5em, 0)
}

http://codeply.com/go/zc544u3kYN
Update the input-size mixin has been removed in Bootstrap 4 Beta.


text:
Q: transfer apps from iPhone 4S to iPad 3 using iTunes 10 on a PC I have an iPad 3 and a iPhone 4S both logged in with the same Apple ID. I have downloaded about a dozen apps on my iPhone 4S and would like to transfer these over to my iPad 3.
I have connected my iPad to my PC with iTunes, however I cannot seem to find the setting that allows me to transfer the apps I have previously downloaded with this Apple ID to my iPad.
I am using iTunes 10.
How can I do this?

A: If you want to simply reinstall the apps, look for the Apps tab in the iPad sync settings on iTunes, tick the boxes of the apps you want to transfer. If you want to copy your save files, etc. then try the following.
Note I haven't tried this
When you reset your iPad or plug it in for the first time, it will ask you if you wish to restore from backup. Try choosing your iPhone 4S's backup if it's in the list.
Also, you can simply re-download from the app store on your iPad at no charge. Instead of a price tag, you will see an Install button.


text:
Q: twisted installed on mac os x but not importing When I try to use twisted from python it fails to load.  Extras path is not in my sys.path.  Even when I add it to sys.path it fails to load twisted.  Any ideas?
sudo find / -name twisted
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted

Python 2.6.6 (r266:84374, Aug 31 2010, 11:00:51)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from twisted.internet.protocol import Factory
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from twisted.internet.protocol import Factory
ImportError: No module named twisted.internet.protocol

A: Have you made sure that all permissions are set properly? If you installed it by hand it might be a problem with the permissions. Check that the permissions are 644 for files and 755 for directories.


text:
Q: Make a linux network device a router I am developing an IPv6 network device driver. It should behaviors like a router, i.e. send router advertisement regularly. But now my device is working like a node, send router solicitation. What should I do to change it to a router? Thanks.

A: The Linux kernel does not know how to send router advertisements; it relies on a userspace daemon for that.  You'll want to install and configure radvd, the Router Advertisement Daemon.  http://tomicki.net/ipv6.router.php is a pretty good tutorial on what you need to do.
Setting the sysctl net.ipv6.conf.all.forwarding = 1 will disable the router solicitations (but will not produce router advertisements).  This setting is also necessary to run radvd.


text:
Q: PoweShell script to show all pages for a site collection SP2013 Is there a PowerShell script that would pull up the pages in a site collection?

A: Try the below script
##If you use SharePoint 2010 PowerShell, this is not required
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

$siteURL = "http://localhost/"
set-variable -option constant -name out -value "C:\temp\PrintAllSitesSubsites.csv"
$spSite = [Microsoft.SharePoint.SPSite] ($siteURL)

if($spSite -ne $null)
{
   "Site Collection : " + $spSite.Url | Out-File $out -Append
   foreach($subWeb in $spSite.AllWebs)
   {
      if($subWeb -ne $null)
      {
         #Print each Subsite
         #Write-Host $subWeb.Url
         "Subsite : " + $subWeb.Name + " - " + $subWeb.Url | Out-File $out -append

         $spListColl = $subweb.Lists
         foreach($eachList in $spListColl)
         {
            if($eachList.Title -eq "Pages")
            {
               $PagesUrl = $subweb.Url + "/"
               foreach($eachPage in $eachList.Items)
               {
                  "Pages : " + $eachPage["Title"] + " - " + $PagesUrl + $eachPage.Url | Out-File $out -append
               }
            }
         }
         $subWeb.Dispose()
      }
      else
      {
         Echo $subWeb "does not exist"
      }
   }
   $spSite.Dispose()
}
else
{
   Echo $siteURL "does not exist, check the site collection url"
}
Echo Finish

Read more here:https://tjendarta.wordpress.com/2013/03/19/powershell-to-loop-through-all-sharepoint-sites-and-pages/
For all site collections in a web application then check this http://www.sharepointfix.com/2012/02/powershell-script-to-enumerate-sites.html

A: Try the following PowerShell code to list the pages within all Pages Libraries in a site collection
$siteCollectionUrl = "http://epm/"
$site =new-object Microsoft.SharePoint.SPSite($siteCollectionUrl)
$query = new-object Microsoft.SharePoint.SPSiteDataQuery
$query.Webs = "<Webs Scope='SiteCollection'>"
$query.Lists = "<Lists ServerTemplate='850' />"
$results = $site.rootweb.GetSiteData($query)
foreach($row in $results.rows)
{
  $listId = $row["ListId"]
  $webId = $row["WebId"]
  $childWeb = $site.OpenWeb([GUID]($webId))
  $pagesList = $childWeb.Lists[[GUID]($listId)];
  $itemUrl = $childWeb.Url + "/" + $pagesList.RootFolder.Url

  foreach($eachPage in $pagesList.Items)
  {
    "AllPages : " + $eachPage["Title"] + " - " + $PagesUrl + $eachPage.Url

  }

  $childWeb.Dispose()
}
$site.Dispose()

Output

For more details check List all Pages Libraries using PowerShell and SPSiteDataQuery?


text:
Q: PostgreSQL how to see particular query have run or not I have Postgres db. My NodeJs application connects it and runs a job every 30 minutes. In that job it runs a query.
I want to check, that query is actually running or not after every 30 minutes. How can I check a particular query runs or not in Postgres DB

A: If you use the log_min_duration_statement = 0 parameter, the PostgreSQL log will indicate when the query has finished running.  Also, if you wish to print the query when it is about to start running, you can use log_statement = 'all'
The way to set these parameters would be simply by calling:
> ALTER SYSTEM SET log_min_duration_statement to 0;
ALTER SYSTEM
> ALTER SYSTEM SET log_statement to 'all';
ALTER SYSTEM
> SELECT pg_reload_conf();

Note that it is possible for these two parameters to produce a lot more log traffic and take up disk space, so use at your own risk.
More information about logging can be found in the documentation

A: Use the following:
SELECT * FROM pg_stat_activity WHERE state='active' AND query='{your query}';

You can see query_start, state_change or even if it has a LOCK on wa
Additional, you can filter by other fields like "username", "client_hostname","client_addr", etc...
More info: PostgreSQL doc
You can put the statement in a function in which you can decide what to do with the queries that are running for longer than 30 min.


text:
Q: Custom Blog Post Listing in Genesis Sample Child Theme I want to add several images and divs and also customize the look of my Blog post listing... But i can't find the way to do it.
Here's the Blog Template code
<?php
/*
 WARNING: This file is part of the core Genesis framework. DO NOT edit
 this file under any circumstances. Please do all modifications
 in the form of a child theme.
 */

/**
 * Template Name: Blog
 * This file handles blog post listings within a page.
 *
 * This file is a core Genesis file and should not be edited.
 *
 * The blog page loop logic is located in lib/structure/loops.php
 *
 * @category Genesis
 * @package  Templates
 * @author   StudioPress
 * @license  http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later)
 * @link     http://www.studiopress.com/themes/genesis
 */
genesis();

and just above the genesis(); code.. i tried to put some divs and images there.. But i guess that's not the way it works. ..
I also tried to make my own Blog listing template using a normal wordpress code theme..
<?php /*
Template Name: List Post Pages
*/
?>
<?php get_header(); ?>
<?php if ( has_post_thumbnail() ) { ?>

  <?php the_post_thumbnail(); ?>

<?php } ?>

  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink() ?>">
      <?php the_title(); ?>

      <?php the_content(); ?>

      <?php the_tags('Tags: ', ', ', '
'); ?>
      Posted in
      <?php the_category(', ') ?>
      |
      <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

  <?php endwhile; ?>
  <?php else : ?>

Not Found

  <?php endif; ?>
  <?php genesis_after_loop(); ?>

<?php get_footer(); ?>

But no luck, what's the right way to do this?
***Update -code below is the one i want.. but instead of having the Content of the page. I want the list of Post with excerpts ....How can i do that????
<?php /*
Template Name: Page Template
*/ ?>
<?php get_header(); ?>
<?php if ( has_post_thumbnail() ) { ?>

  <?php the_post_thumbnail(); ?>

<?php } ?>

<?php genesis_before_content_sidebar_wrap(); ?>

  <?php genesis_before_content(); ?>

    <?php genesis_before_loop(); ?>
    <?php genesis_loop(); ?>
    <?php genesis_after_loop(); ?>

  <?php genesis_after_content(); ?>

<?php genesis_after_content_sidebar_wrap(); ?>
<?php get_footer(); ?>

A: Im shocked that no one answered my question.. anyway, if someone bumps onto this post with similar problem. The answer is adding
<?php query_posts( $args );  ?>

just above the <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
All in all, my code looks like this ...
<?php /*
Template Name: Page Template
*/ ?>
<?php get_header(); ?>
<?php if ( has_post_thumbnail() ) { ?>

  <?php the_post_thumbnail(); ?>

<?php } ?>

<?php genesis_before_content_sidebar_wrap(); ?>

  <?php genesis_before_content(); ?>

    <?php genesis_before_loop(); ?>
    <?php query_posts( $args );  ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink() ?>">
        <?php the_title(); ?>

        <?php the_content(); ?>

        <?php the_tags('Tags: ', ', ', '
'); ?>
        Posted in
        <?php the_category(', ') ?>
        |
        <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

    <?php endwhile; ?>
    <?php else : ?>

Not Found

    <?php endif; ?>
    <?php genesis_after_loop(); ?>

  <?php genesis_after_content(); ?>

<?php genesis_after_content_sidebar_wrap(); ?>
<?php get_footer(); ?>


text:
Q: C++/CLI calling Interop wrapper methods with out parameters I've got an Interop wrapper to some unmanaged DLL calls that return details through out paremeters. The functions appear like this:
_myWrapper->My_Method( ... out UInt32 value ... );

So assuming the method is declared like this:
void My_Method(out UInt32 value);

How do I then call this method from within my C++/CLI code? I know how to call reference methods such as this easy enough:
void Another_Method(ref UInt32 value);

UInt32 _value;
_myWrapper->Another_Method(%_value);

I'm doing a little reading and I am reading it can't be done? I don't believe it... Likely this isn't impossible to overcome or workaround, but you've got to be kidding me? Is that really true?
Thank you...

A: In C++, there's no special call syntax for calling a function with a reference parameter, you just write the call like it was pass-by-value.  Of course, you need to supply an lvalue to be overwritten, the rvalue (temporary) result of an arithmetic expression can't be used.
BTW, your code for calling a ref function is wrong too, that might be the source of your troubles.
Example:
C# definition:
 void MySharpRef(ref int i)  { i = 4; }
 void MySharpOut(out int i)  { i = 5; }

C++/CLI definition:
 void MyPlusRef(System::Int32% i) { i = 14; }
 void MyPlusOut([System::Runtime::InteropServices::OutAttribute] System::Int32% i) { i = 15; }

C# call:
 int j;
 o.MyPlusOut(out j);
 o.MyPlusRef(ref j);

C++/CLI call:
 System::Int32 k;
 p->MySharpOut(k);
 p->MySharpRef(k);


text:
Q: inpout32.dll missing Qt C++ In my project I need to access the parellel port, to do that I wand to use the library inpout32.dll. So far I copied this dll in the folder "system32" and I followed this example http://www.qtfr.org/viewtopic.php?id=7770
My problems are :

*

*I can't use the type inpfuncPtr and oupfuncPtr because it's not declared

*To resolve the first issus I thought that maybe the library was not added to the project. So I test just the part of the code to load it. But this time it saids that my library is missing. "error: inpout32.dll: No such file or directory"
#include <QCoreApplication>
#include <QLibrary>
#include <QFile>
#include <QString>
#include <QtDebug>

#include <windows.h>

int main(int argc, char *argv[])
{

QCoreApplication a(argc, argv);

HINSTANCE hLib;

int Size = MultiByteToWideChar(CP_ACP, 0, "inpout32.dll", -1, NULL, 0);
LPWSTR wUnicode = new WCHAR[Size];
MultiByteToWideChar(CP_ACP, 0, "inpout32.dll", -1, wUnicode, Size);

hLib = LoadLibrary(wUnicode);

return a.exec();
}

Thank you for your help.


text:
Q: pyqt5 closing a child window from a parent window I have created 2 windows, win1 and win2, using qt designer and have added two buttons: btn_open_win2 to open win2 from win1 and btn_close to close win2.
When I run win2 directly the close method works correctly but when I run win1 and call win2 from it, the close button on win2 doesn't operate correctly.
I know that the problem arises from the point that win2 has been defined inside the if __name__ =='__main__'  part as shown in the below codes but I can't solve this problem.
win1:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow

class Ui_Win1(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("Win1")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_open_win2 = QtWidgets.QPushButton(self.centralwidget)
        self.btn_open_win2.setGeometry(QtCore.QRect(250, 170, 131, 101))
        self.btn_open_win2.setObjectName("btn_open_win2")
        self.btn_open_win2.clicked.connect(self.on_open_win2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Win1"))
        self.btn_open_win2.setText(_translate("MainWindow", "open win2"))

    def on_open_win2(self):
        from win2 import Ui_Win2
        self.win = QMainWindow()
        self.ui = Ui_Win2()
        self.ui.setupUi(self.win)
        self.win.show()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win1 = QMainWindow()
    ui = Ui_Win1()
    ui.setupUi(win1)
    win1.show()
    sys.exit(app.exec_())

win2:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow

class Ui_Win2(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("Win2")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_close = QtWidgets.QPushButton(self.centralwidget)
        self.btn_close.setGeometry(QtCore.QRect(260, 180, 131, 101))
        self.btn_close.setObjectName("btn_close")
        self.btn_close.clicked.connect(self.on_close)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Win2"))
        self.btn_close.setText(_translate("MainWindow", "close"))

    def on_close(self):
        # win2 = QMainWindow()
        # ui = Ui_Win2()
        # ui.setupUi(win2)
        win2.close()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win2 = QMainWindow()
    ui = Ui_Win2()
    ui.setupUi(win2)
    win2.show()
    sys.exit(app.exec_())

A: change win2 like this:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow

class Ui_Win2(object):
    def setupUi(self, MainWindow):
        self.MainWindow = MainWindow
        MainWindow.setObjectName("Win2")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_close = QtWidgets.QPushButton(self.centralwidget)
        self.btn_close.setGeometry(QtCore.QRect(260, 180, 131, 101))
        self.btn_close.setObjectName("btn_close")
        self.btn_close.clicked.connect(self.on_close)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Win2"))
        self.btn_close.setText(_translate("MainWindow", "close"))

    def on_close(self):
        # win2 = QMainWindow()
        # ui = Ui_Win2()
        # ui.setupUi(win2)
        self.MainWindow.close()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win2 = QMainWindow()
    ui = Ui_Win2()
    ui.setupUi(win2)
    win2.show()
    sys.exit(app.exec_())

call close function from self.MainWindow instead of self. and set self.MainWindow in first line of setupUi function