text:
Q: Reading a persistent object's variable prevents it from being added to an object later I am trying to make a new object Session and persist it to the database. It has a persistent variable of object User. I query the DB for the user I want to add to the session. If the user's password doesn't match "hello" (for now obviously), stop. If it does, make a new session, set the regular variables and add sOwner (just set Session's User variable). Like this, the code works but doesn't check the password...
try {
    Query u = pm.newQuery(User.class); //Query for user
    u.setFilter("email == eaddr");
    u.declareImports("import java.lang.String");
    u.declareParameters("String eaddr");
    @SuppressWarnings("unchecked")
    List<User> res = (List<User>)u.execute(email);
    sOwner = res.get(0);
    //if (!sOwner.getPassword().equals("hello")) {  // comment out
    //throw new Exception("password not correct");  // these three lines
    //}                                 // and it works
    sNew = new Session();
    sNew.setUser(sOwner);
    sNew.setIpAddr(ipAddr);
    sNew.setStartedOn(new Date());
    sNew.setToken(token);
    pm.makePersistent(sNew);
} catch (Exception e) {
}

but without the if statement commented out, the final committing of the changes has this error:
2385571 [btpool0-0] DEBUG DataNucleus.Persistence  - Object "com.yachtcloser.server.om.Session@14446bce" (id="com.yachtcloser.server.om.Session:381") is having the value in field "startedOn" replaced by a SCO wrapper
2385571 [btpool0-0] DEBUG DataNucleus.Datastore.Native  - INSERT INTO `SESSION` (`TOKEN`,`STARTEDON`,`USERAGENT`,`IPADDR`,`USER_ID_OID`,`ID`) VALUES (<'90a9d90f325c3b'>,<2011-02-24 19:12:15.595>,<null>,<'127.0.0.5'>,<21>,<381>)
2385572 [btpool0-0] DEBUG DataNucleus.Datastore.Persist  - Execution Time = 1 ms (number of rows = 1)
2385572 [btpool0-0] DEBUG DataNucleus.Persistence  - Insert of object "com.yachtcloser.server.om.Session@14446bce" is calling insertPostProcessing for field "com.yachtcloser.server.om.Session.user"
2385572 [btpool0-0] DEBUG DataNucleus.Persistence  - Insert of object "com.yachtcloser.server.om.Session@14446bce" is calling insertPostProcessing for field "com.yachtcloser.server.om.Session.transaction"
2385572 [btpool0-0] DEBUG DataNucleus.Datastore.Retrieve  - Closing PreparedStatement org.datanucleus.store.rdbms.ParamLoggingPreparedStatement@2ac7bf18
2385572 [btpool0-0] DEBUG DataNucleus.Persistence  - Insert of object "com.yachtcloser.server.om.Session@14446bce" is calling postInsert for field "com.yachtcloser.server.om.Session.user"
2385572 [btpool0-0] DEBUG DataNucleus.Persistence  - Insert of object "com.yachtcloser.server.om.Session@14446bce" is calling postInsert for field "com.yachtcloser.server.om.Session.transaction"
2385584 [btpool0-0] DEBUG DataNucleus.Persistence  - Object "com.yachtcloser.server.om.Session@14446bce" field "transaction" is replaced by a SCO wrapper of type "org.datanucleus.store.types.sco.backed.List" [cache-values=true, lazy-loading=true, queued-operations=false, allow-nulls=true]
2385585 [btpool0-0] DEBUG com.yachtcloser.server.DispatchServlet  - Response Sent:{"cmds":[{"response":"Session 381 created by user 0"}]}
2385585 [btpool0-0] DEBUG DataNucleus.Persistence  - ObjectManager internalFlush() process started - 1 dirty objects
2385585 [btpool0-0] DEBUG DataNucleus.Persistence  - ObjectManager internalFlush() process finished
2385589 [btpool0-0] ERROR DataNucleus.Persistence  - java.lang.NullPointerException
2385590 [btpool0-0] DEBUG DataNucleus.Persistence  - Disconnecting com.yachtcloser.server.om.Session@14446bce from StateManager[pc=com.yachtcloser.server.om.Session@14446bce, lifecycle=P_NEW]

Here's the stack trace of the NPE I think:
NestedThrowablesStackTrace:
java.lang.NullPointerException
    at org.datanucleus.store.rdbms.sql.SQLStatementHelper.selectMemberOfSourceInStatement(SQLStatementHelper.java:723)
    at org.datanucleus.store.rdbms.request.FetchRequest.processMembersOfClass(FetchRequest.java:478)
    at org.datanucleus.store.rdbms.request.FetchRequest.<init>(FetchRequest.java:166)
    at org.datanucleus.store.rdbms.RDBMSPersistenceHandler.getFetchRequest(RDBMSPersistenceHandler.java:329)
    at org.datanucleus.store.rdbms.RDBMSPersistenceHandler.fetchObject(RDBMSPersistenceHandler.java:306)
    at org.datanucleus.jdo.state.JDOStateManagerImpl.loadFieldsFromDatastore(JDOStateManagerImpl.java:2028)
    at org.datanucleus.jdo.state.JDOStateManagerImpl.loadUnloadedFields(JDOStateManagerImpl.java:1685)
    at org.datanucleus.jdo.state.JDOStateManagerImpl.runReachability(JDOStateManagerImpl.java:3295)
    at org.datanucleus.ObjectManagerImpl.performReachabilityAtCommit(ObjectManagerImpl.java:3415)
    at org.datanucleus.ObjectManagerImpl.preCommit(ObjectManagerImpl.java:3268)
    at org.datanucleus.ObjectManagerImpl$2.transactionPreCommit(ObjectManagerImpl.java:324)
    at org.datanucleus.TransactionImpl.internalPreCommit(TransactionImpl.java:394)
    at org.datanucleus.TransactionImpl.commit(TransactionImpl.java:279)
    at org.datanucleus.jdo.JDOTransaction.commit(JDOTransaction.java:90)
    at com.yachtcloser.server.UserContext.finishRequest(UserContext.java:181)
    at com.yachtcloser.server.DispatchServlet.doPost(DispatchServlet.java:185)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at com.yachtcloser.server.DispatchServlet.service(DispatchServlet.java:55)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
        at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)

I tried detaching a copy, and comparing that password, then adding the original query result
to the session, that didn't work either.  Here's the important part of Session which I can't edit by the way:
@PersistenceCapable(identityType=IdentityType.APPLICATION)
public class Session  implements Comparable<Session> {

    @PrimaryKey
  @Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT)
  private long id;

  @Persistent
  private User user;

datanucleus-core-2.2.2.jar, datanucleus-connectionpool-2.0.3.jar, datanucleus-googlecollections-2.2.0-release.jar, datanucleus-jdo-query-2.2.1.jar, datanucleus-rdbms-2.2.2.jar, jdo2-api-2.3-ec.jar, datanucleus-enhancer-2.1.3.jar, asm-3.3.1.jar   those are the jar files I see

A: A query generates SQL. That is printed in the DataNucleus log. Consequently you ought to check the SQL generated for your query. The stack trace is created from tx.commit() yet you don't mention such a call.
You don't say the version of DataNucleus in use ... of each plugin jar.


text:
Q: Rigorous Proof for the Unique Existence of a Function in Introducing Adjoint in Linear Algebra, Considering First-Order Logic and Axiomatic Set Theory $\newcommand{\linearmaps}[2]{\mathcal{L}\left({#1},{#2}\right)}$
$\newcommand{\linearoperators}[1]{\mathcal{L}\left(#1\right)}$
$\newcommand{\innerprod}[2]{\left\langle #1,#2 \right\rangle}$
$\newcommand{\powerset}[1]{\mathcal{P}\left(#1\right)}$
According to the rule of extensions by definitions in mathematical logic (link at https://en.wikipedia.org/wiki/Extension_by_definitions), to introduce a function symbol $*$ to denote adjoint, we need to prove the following theorem: for all $T \in \linearmaps{V}{W}$, there exists a unique function $S: W \to V$ such that for every $v \in V$ and $w \in W$,
\begin{equation}
\innerprod{Tv}{w} = \innerprod{v}{Sw}.
\end{equation}
My proof goes as follows. Suppose that $w \in W$. Then there exists a function $\varphi: V \to W$ such that for an arbitrary $v \in V$,
\begin{equation}
\varphi\left(v\right) = \innerprod{Tv}{w}.
\end{equation}
It is obvious that $\varphi$ is a linear functional. According to Riesz Representation theorem, there exists a unique $s \in V$ such that for every $v \in V$,
\begin{equation}
\varphi\left(v\right) = \innerprod{v}{s}.
\end{equation}
We may conclude that for all $w \in W$, there exists a unique $s \in V$ such that for all $v \in V$,
\begin{equation}
\innerprod{Tv}{w} = \innerprod{v}{s}.
\end{equation}
Next we would like to prove the follow set (function) uniquely exists:
\begin{equation}
S = \left\{\left(w, s\right) \in V^{2} \vert \textrm{for all }v \in V, \innerprod{Tv}{w} = \innerprod{v}{s}\right\}.
\end{equation}
The existence of the set comes from set theory (Axiom schema of specification, if I recall correctly). The uniqueness comes from the immediate previous conclusion. Finally we may conclude that there exists a unique function $S: W \to V$ such that for all $v \in V$ and for all $w \in W$,
\begin{equation}
\innerprod{Tv}{w} = \innerprod{v}{Sw}.
\end{equation}
Only with the above proof can we introduce the function symbol for adjoint. I am verifying if relating this problem to first-order logic and set theory is the only rigorous way to introduce math symbols.

Here are some of my thoughts. The proof itself is not too hard. However, it seems that to thoroughly understand why this proof is needed in introducing the adjoint concept and to prove the existence of a function, we need to understand set theory and first-order logic. This reminds me of the difficulty to educate students, especially those in engineering departments about true math. After all, it is very hard for general students (including me) to go deep to mathematical logic and axiomatic set theory to know the necessity of a proof before using a new concept, and to rigorously prove the existence of a function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the sum of all $x$, $1 \le x \le 100$, such that $7$ divides $x^2+15x+1$.
Find the sum of all $x$, $1 \le x \le 100$, such that $7$ divides
  $x^2+15x+1$.

I am clueless about how to approach this problem.
Trying some values of $x$ I've found $2,4,9,11,16$ to satisfy the restriction after that I found it to be harder to find another good $x$.
I think I have to solve $x^2+15x+1 \equiv 0 \mod 7$ for $x$.
Solving this I would get $x \equiv \sqrt{\cfrac{13}{2}} -\cfrac{15}{2}$ but this doesn't help as I would get this result for any modulo $n$...

A: Another hint:  Once you get used to replacing coefficients with modular equivalents, it's useful to note that $x^2+15x+1\equiv x^2+x-6$ mod $7$, because then what you need to solve is
$$(x+3)(x-2)\equiv0\mod7$$

A: Hint You have to solve
$$x^2+x+1 \equiv 0 \pmod{7}$$
Modulo $7$ $x$ is equivalent to its remainder. So check which numbers between 0 and 6 satisfy your relation, and then which numbers between $1$ and 100 (formula, do not check them 1 by 1) are equivalent with those two remainders...

A: A table of $f(x)=x^2+x+1$ in $\mathbb F_7$ gives for $1,2,3,4,5,6,0$ the values $3,7,6,7,10,8,1$ respectively. Hence the only numbers to be considered are of the form $7m+2$ and $7m+4$.
We have $$2+(2+7)+(2+14)+.....+(2+14\cdot7)=\frac{15(100+2)}{2}=765$$
$$4+(4+7)+(4+14)+.........+(4+13\cdot7)=\frac{14(95+4)}{2}=693$$
Thus the asked sum is $765+693=\color{red}{1458}$


text:
Q: Use matplotlib to plot a heat map with split diagonal I would like to use matplotlib to make a heat map that simultaneously represent two symmetric matrices, say A and B, so that the squares above the diagonal will be colored according to the elements in A, and the squares below the diagonal will be colored according to the elements in B.
There are two things that I do not know how to do:

*

*The squares in the diagonal should be split across the diagonal line so that the upper triangles are colored according to the diagonal elements in A, and the lower triangles are colored according to the diagonal elements in B.  How can this be done?

*Two separate color maps should be used for A and for B, because the ranges of the values in A and B are disparate.  How can two color maps be applied to the same heat map?  A related question is how to place two corresponding color bars, one on the right of the heat map for A and one on the bottom for B.
Any help will be much appreciated.

A: I had a similar requirement,followed this Python package to plot two heatmaps in one (split each square into two triangles) and tried to modify it according to my need.
In my code below my x-axis should be the list of SOMA values and y-axis should be the list of Q values. QPrecision and Precision are my two values varying which I am representing in the two triangles of cell. The location of the colorbars can be modified by changing the location attribute to 'bottom' or 'top'.
One thing I noticed was PyCharm was not able to display the figure correctly but the saved image looks as the attached Image

M = len(SOMA)
N = len(Q)
x = np.arange(M + 1)
y = np.arange(N + 1)

xs, ys = np.meshgrid(x, y)

zs1 = result['PRECISION']
zs2 = result['QPRECISION']
zs1 = zs1.astype(dtype=float)
zs2 = zs2.astype(dtype=float)

triangles1 = [(i + j*(M+1), i+1 + j*(M+1), i + (j+1)*(M+1)) for j in range(N) for i in range(M)]
triangles2 = [(i+1 + j*(M+1), i+1 + (j+1)*(M+1), i + (j+1)*(M+1)) for j in range(N) for i in range(M)]
print(np.shape(triangles1))
print(np.shape(triangles2))
fig = plt.figure()
ax = fig.add_subplot(111)

triang1 = Triangulation(xs.ravel(), ys.ravel(), triangles1)
triang2 = Triangulation(xs.ravel(), ys.ravel(), triangles2)

newcmp = ListedColormap(['#DAFFAC','#8FFD03'])

img1 = ax.tripcolor(triang1, zs1, cmap=plt.get_cmap('Blues'))
img2 = ax.tripcolor(triang2, zs2, cmap=plt.get_cmap(newcmp))

cb1 = plt.colorbar(img2, ax=[ax], ticks=[5, 4] , location='left',label='Q based Precision', pad=0.15)
cb2 = plt.colorbar(img1, ax=[ax], ticks=[5, 4, 3, 2, 1, 0],location='right',label='Suppported Precision', pad =0.05)

labels = np.arange(4, int(5) + 1, 1)
cb1.set_ticks([4.25, 4.75])
cb1.set_ticklabels(labels)

for tick in ax.xaxis.get_majorticklabels():
    tick.set_horizontalalignment("center")

plt.xlim(x[0], x[-1])
plt.ylim(y[0], y[-1])
plt.xlabel("SOMA")
plt.ylabel("Q")

x = np.arange(0.5,22,1) #range of SOMA
y = np.arange(0.5,14,1) #range of Q

plt.xticks(x, SOMA, rotation=90)
plt.yticks(y, Q)
plt.title(PLOT_TITLE)
plt.savefig('fig.png',bbox_inches='tight')

plt.show()

Sample Output Image


text:
Q: Read a file as byte array using C++? I want to read my .exe file as byte so can i edit its bytes later, i tried to write a code but it gives me this error :

error: invalid conversion from 'LPVOID {aka void*}' to 'LPBYTE {aka
unsigned char*}' [-fpermissive]|

this is my code:
HANDLE hFile = CreateFile("0x2.exe", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        // get file size
        DWORD dwFileSize = GetFileSize(hFile, NULL);

        // decrypt and obtain decrypted bytes
        LPVOID lpFileBytes = Crypt(hFile, dwFileSize);
        CloseHandle(hFile);
        //free(lpFileBytes);

         //execute file
         //

    LPBYTE lpBuffer = lpFileBytes ;

i crypt the file 0x2.exe, and i decrypt it by this line :
LPVOID lpFileBytes = Crypt(hFile, dwFileSize);

now i issume i have the orignal bytes in lpFileBytes , so when i do this :
LPBYTE lpBuffer = lpFileBytes

it gives me that error .


text:
Q: c++ need help to understand So I have this piece of code.
I understand all the things beside the fact that when does the loop actually take place again. I mean what is meant by the e(!valid) statement. Does it refer to its numeric value or what? Can somebody please explain this to me. Consider all required variable declared. And ignore uppercase.
The code is:
do
{

    valid=1;
    gotoxy(22,7);
    gets(emailid);
    int flag=0;
    for (int i = 0; emailid[i] != '\0'; i++)
        if (emailid[i] == '@')
            flag++;
    If(!flag)
    {
        valid = 0;
        cout << "not a valid id. Try again";
        getch();
    }
} while(!valid);

So mainly I want to know that it is working, with emphasis on what does !valid and !fail mean.
From what I could get, it has to do with its numeric values but I am still confused.

A: To answer the question:
} while (!valid);

means: treat the integer behind valid as a boolean.  (assuming it is an integer, as it was given a value of 1)
i == 0 -> false
i != 0 -> true

!valid:
valid == 0 -> true
valid != 0 -> false

A: In C++ the value 0 is considered "false" and any other integer is considered "true". In this case while valid is equal to 0 the loop runs.

A: Numeric value can be promoted to bool type this way:
Zero means false and other values mean true. So !valid will return true only if valid == 0.
What it means is your do while() loop will repeat itself until valid equals value other than 0.


text:
Q: How to set up DBI and OBDC in R Docker image to run PSQL queries through DBI? I was trying to find a docker image with R, ODBC and DBI installed and I could not find any. So I created one - anirbans96/rodbcdbi
Now, when I am trying to run queries on PostgresSQL using psqlodbcw.so as driver, it fails by saying that it couldn't find the driver. However, I copied over this file from laudio/pyodbc:1.0.38 docker image at `us/lib/x86_64-linux-gnu/odbc/psqlodbcw.so' to the same location on my Docker Image.
However, when I am initiating a connection using
DBI::dbConnect(
    odbc::odbc(),
    Server=server,
    Database=database,
    UID=user,
    PWD=password
)

It is throwing the error : nanodbc/nanodbc.coo:1118: 0000: [unixODBC][Driver Manager] Can't open lib '/usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so' : file not found
I verified that the file exists using:
if test -f "/usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so"; then
    echo "File Exists"
fi

My Dockerfile -
FROM rocker/r-ubuntu

RUN apt-get update -y && apt-get install -y build-essential curl gnupg2 software-properties-common dirmngr apt-transport-https apt-utils lsb-release ca-certificates
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update -y
RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17 unixodbc-dev mssql-tools

# Install R packages (odbc R package must be installed AFTER installing ODBC in the OS)
RUN Rscript -e "install.packages('odbc')"
RUN Rscript -e "install.packages('DBI')"

# Copy and execute R script
# RUN mkdir /home/analysis
# COPY transformdata.r /home/analysis/transformdata.r
# CMD R -e "source('/home/analysis/transformdata.r')"

This has been pushed as anirbans96/rodbcdbi
Dockerfile file where I copied pysqlodbc.so:
FROM anirbans96/rodbcdbi
RUN mdkir /usr/lib/x86_64-linux-gnu/odbc/
COPY psqlodbcw.so /usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so

What else do we need to configure?

A: As suggested by @r2evans
I add apt-get odbc-postgresql postgresql-client and it solved the issue.
The new Dockerfile looks like:
FROM rocker/r-ubuntu

RUN apt-get update -y && apt-get install -y build-essential curl gnupg2 software-properties-common dirmngr apt-transport-https apt-utils lsb-release ca-certificates odbc-postgresql postgresql-client unixodbc-dev
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list

RUN Rscript -e "install.packages('odbc')"
RUN Rscript -e "install.packages('DBI')"
RUN Rscript -e "install.packages('stringr')"

This has been added to Dockerhub as the new anirbans96/rodbcdbi


text:
Q: how to set default values for all new users in firebase using android studio How to set a default integer(0) value for all the new user who signup for the first time using google sign in, but for old users(who signed up earlier) the value should not change on clearing app data of the app.
For example, I am new user who signed up for the first time I got 30 points in score, and in the app, I play some task to earn more and now I got 60 points, but when I delete app data again I am getting 30 points on sign in
Please see the code
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    //getting the auth credential
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

    //Now using firebase we are signing in the user here
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    progressDialog.dismiss();
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
                        DatabaseReference UserId = databaseReference.child(mAuth.getCurrentUser().getUid());
                        if (user.getUid() != null){
                            UserId.getDatabase();
                            Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                            Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
                            main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(main2);
                        }else {
                            UserId.child("Score").setValue(30);
                            Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                            Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
                            main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(main2);
                        }

                    } else {
                        // If the sign in fails displays a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();

                    }

                }
            });
}

When I replace this code
if (user.getUid() != null){
                        UserId.getDatabase();
                        Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                        Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
                        main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(main2);
                    }else {
                        UserId.child("Score").setValue(30);
                        Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                        Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
                        main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(main2);
                    }

To
         UserId.child("Score").setValue(30);

         Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
         Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
                            main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(main2);

New uid with score is created in my firebase database but the problem is when I clear app data and again sign in score become 30, but if I dont replace the code new user is not created in database but they are authenticated with score null
So please tell me how I can make this work?
I am using their uid to track
Thanks, any help will be appreciated

A: Now I made it work by myself by creating two functions to check if user is new or not then added simultaneously using uid through valueaddedeventlistener
Here is the code for sign in
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    //getting the auth credential
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

    //Now using firebase we are signing in the user here
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    progressDialog.dismiss();
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
                        FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                        final DatabaseReference UserId = databaseReference.child(mAuth.getCurrentUser().getUid());
                        final String uid = currentFirebaseUser.getUid();
                        databaseReference.child("Users").addListenerForSingleValueEvent(
                                new ValueEventListener() {

                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {

                                        //String uid1 = dataSnapshot.hasChild(uid);

                                        if (dataSnapshot.hasChild(uid)) {
                                            //Old User
                                            userAlreadyExistsScore();

                                        } else {
                                            // User Not Yet Exists
                                            newUserScore();
                                        }
                                    }
                                    @Override
                                    public void onCancelled (DatabaseError databaseError){

                                    }
                                }

                        );

                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();

                    }

                    // ...
                }
            });
}

Here is code for new user
private void newUserScore(){
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
    final DatabaseReference UserId = databaseReference.child(mAuth.getCurrentUser().getUid());

    UserId.child("Score").setValue(30);
    Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
    Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
    main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(main2);

}

Here is code for user already exists
private void userAlreadyExistsScore(){

    FirebaseUser user = mAuth.getCurrentUser();
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
    final DatabaseReference UserId = databaseReference.child(mAuth.getCurrentUser().getUid());

    if (user != null){

        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Integer Score = dataSnapshot.getValue(Integer.class);
                UserId.child("Score").setValue(Score);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        UserId.child("Score").addListenerForSingleValueEvent(valueEventListener);
        Toast.makeText(MainActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
        Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
        main2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(main2);

    }
}


text:
Q: EasyAdminBundle - Unrecognized option "sort" under "easy_admin.list" I've been looking for a way to override the default sorting of data which is based on primary key.
I found some configuration examples for sorting data from the documentation but it doesn't work.
It says

Unrecognized option "sort" under "easy_admin.list"

easy_admin:
   entities:
      Customer:
          class: AppBundle\Entity\Customer
          list:
              sort: 'name'
          form:
              title: 'Add Customer'
              form_options: {validation_groups:['Default']}

              fields:
                  - name
                  - {property: 'gender', type: 'choice', type_options:
                                                  {
                                                    placeholder: 'Select your gender',
                                                    choices: {
                                                        Female: 'female',
                                                        Male: 'male'
                                                    }
                                                  } }
                  - {property: 'birthdate', type: 'date', type_options: {widget: 'single_text'}}
                  - isActive
          new:
              form_options: {validation_groups: ['Default','Customer']}
          edit:
              title: 'Edit Customer'

site_name: 'Premiere Sales'

A: You use sort option in the wrong place. You should set sort option under your entity scope of configuration:
easy_admin:
    entities:
        User:
            # ...
            list:
                # if the sort order is not specified, 'DESC' is used
                sort: 'createdAt'

A: It seems that the configuration I posted above is correct and I just restarted the server and the browser and it works fine


text:
Q: What is the advantage of using annotation over interface type? In this example, below annotation type(@interface):
@interface ClassPreamble {
       String author();
       String date();
       int currentRevision() default 1;
       String lastModified() default "N/A";
       String lastModifiedBy() default "N/A";
       // Note use of array
       String[] reviewers();
    }

gets compiled to interface type:
interface annotationtype.ClassPreamble extends java.lang.annotation.Annotation{
    public abstract java.lang.String author();
    public abstract java.lang.String date();
    public abstract int currentRevision();
    public abstract java.lang.String lastModified();
    public abstract java.lang.String lastModifiedBy();
    public abstract java.lang.String[] reviewers();
}

So, the annotation type is getting compiled to interface type, before runtime.
In java, What is the advantage of using annotation type(@interface) over the interface type?

A: Interfaces are a technique for object modeling, that allow objects to implement behaviors (but not state) associated with multiple types.
Annotations are a technique for embedding typed metadata in your code; this metadata is intended to be consumed by tools (test frameworks, code generators, etc), but they have no language-level semantics.  You could think of them as structured/typed comments attached to certain program elements, that can be accessed via reflection.
Under the hood, annotations are implemented as interfaces, largely as a matter of convenience, but the similarity is probably more confusing than helpful in understanding what they are for.

A: If you do manually what compiler did automatically, you would not define an annotation. According to Oracle documentation,

an interface that manually extends [java.lang.annotation.Annotation] does not define an annotation type.

Therefore, @interface syntax is required to define an annotation in Java.


text:
Q: Определить попадание точки в круг Добрый день.
В базе хранятся координаты точки (тип float) из google-maps. Нужно при получении подобных координат определить какие хранящиеся в базе точки попадают в круг полученной точки.
Т.е. есть координата в базе 5, 5. Поступает координата 6, 6. Есть радиус определенны (скажем 5 метров), нужно узнать - попадает ли 6, 6 в круг.
Вопрос вроде не сложный, но сообразить не могу как правильно все это рассчитать
A: Вам можно воспользоваться следующим условием:
(x - x0)^2 + (y - y0)^2 <= R^2

где x и y  - координаты вашей точки, x0 и y0 - координаты центра окружности, R - радиус окружности, ^2 - возведение в квадрат. Если условие выполняется, то точка находится внутри (или на окружности, в случае равенства левой и правой частей). Если не выполняется, то точка вне окружности.
Необходимое уточнение - это будет работать в случае небольших радиусов (до нескольких километров). В случае же окружностей с большими радиусами допущение о том, что поверхность плоская станет неверным - нужно будет принимать во внимание кривизну поверхности Земли и вносить коррективы с учетом пространственной геометрии


text:
Q: iOS App Intents UI Extension calling configureView multiple times and displaying my view multiple times I am using the IntentsExtension and IntentsUIExtension for a messaging app to allow a user to send messages using Siri.
It all works and the message is sent once, however when the extension UI is displayed, the view I define in configureView is displayed 3 times.
This is the default code intent handler.  Either using this default code or my custom code the result is the same.  UI extension IntentViewController configureView method called 3 times:
class IntentHandler: INExtension, INSendMessageIntentHandling, INSearchForMessagesIntentHandling, INSetMessageAttributeIntentHandling {

    override func handler(for intent: INIntent) -> Any {
        // This is the default implementation.  If you want different objects to handle different intents,
        // you can override this and return the handler you want for that particular intent.

        return self
    }

    // MARK: - INSendMessageIntentHandling

    // Implement resolution methods to provide additional information about your intent (optional).
    func resolveRecipients(for intent: INSendMessageIntent, with completion: @escaping ([INSendMessageRecipientResolutionResult]) -> Void) {
        if let recipients = intent.recipients {

            // If no recipients were provided we'll need to prompt for a value.
            if recipients.count == 0 {
                completion([INSendMessageRecipientResolutionResult.needsValue()])
                return
            }

            var resolutionResults = [INSendMessageRecipientResolutionResult]()
            for recipient in recipients {
                let matchingContacts = [recipient] // Implement your contact matching logic here to create an array of matching contacts
                switch matchingContacts.count {
                case 2  ... Int.max:
                    // We need Siri's help to ask user to pick one from the matches.
                    resolutionResults += [INSendMessageRecipientResolutionResult.disambiguation(with: matchingContacts)]

                case 1:
                    // We have exactly one matching contact
                    resolutionResults += [INSendMessageRecipientResolutionResult.success(with: recipient)]

                case 0:
                    // We have no contacts matching the description provided
                    resolutionResults += [INSendMessageRecipientResolutionResult.unsupported()]

                default:
                    break

                }
            }
            completion(resolutionResults)
        } else {
            completion([INSendMessageRecipientResolutionResult.needsValue()])
        }
    }

    func resolveContent(for intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Void) {
        if let text = intent.content, !text.isEmpty {
            completion(INStringResolutionResult.success(with: text))
        } else {
            completion(INStringResolutionResult.needsValue())
        }
    }

    // Once resolution is completed, perform validation on the intent and provide confirmation (optional).

    func confirm(intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
        // Verify user is authenticated and your app is ready to send a message.

        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
        let response = INSendMessageIntentResponse(code: .ready, userActivity: userActivity)
        completion(response)
    }

    // Handle the completed intent (required).

    func handle(intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
        // Implement your application logic to send a message here.

        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
        let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity)
        completion(response)
    }

    // Implement handlers for each intent you wish to handle.  As an example for messages, you may wish to also handle searchForMessages and setMessageAttributes.

    // MARK: - INSearchForMessagesIntentHandling

    func handle(intent: INSearchForMessagesIntent, completion: @escaping (INSearchForMessagesIntentResponse) -> Void) {
        // Implement your application logic to find a message that matches the information in the intent.

        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSearchForMessagesIntent.self))
        let response = INSearchForMessagesIntentResponse(code: .success, userActivity: userActivity)
        // Initialize with found message's attributes
        response.messages = [INMessage(
            identifier: "identifier",
            content: "I am so excited about SiriKit!",
            dateSent: Date(),
            sender: INPerson(personHandle: INPersonHandle(value: "sarah@example.com", type: .emailAddress), nameComponents: nil, displayName: "Sarah", image: nil,  contactIdentifier: nil, customIdentifier: nil),
            recipients: [INPerson(personHandle: INPersonHandle(value: "+1-415-555-5555", type: .phoneNumber), nameComponents: nil, displayName: "John", image: nil,  contactIdentifier: nil, customIdentifier: nil)]
            )]
        completion(response)
    }

    // MARK: - INSetMessageAttributeIntentHandling

    func handle(intent: INSetMessageAttributeIntent, completion: @escaping (INSetMessageAttributeIntentResponse) -> Void) {
        // Implement your application logic to set the message attribute here.

        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSetMessageAttributeIntent.self))
        let response = INSetMessageAttributeIntentResponse(code: .success, userActivity: userActivity)
        completion(response)
    }
}

and the UI code:
class IntentViewController: UIViewController, INUIHostedViewControlling {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    // MARK: - INUIHostedViewControlling

    // Prepare your view controller for the interaction to handle.
    func configureView(for parameters: Set<INParameter>, of interaction: INInteraction, interactiveBehavior: INUIInteractiveBehavior, context: INUIHostedViewContext, completion: @escaping (Bool, Set<INParameter>, CGSize) -> Void) {
        // Do configuration here, including preparing views and calculating a desired size for presentation.
        completion(true, parameters, self.desiredSize)
    }

    var desiredSize: CGSize {
        return self.extensionContext!.hostedViewMaximumAllowedSize
    }

}

Putting a breakpoint on the completion handler in configureView I can see it is called 3 times.  In my app this causes the custom view to appear 3 times one after another stacked vertically.


text:
Q: elastic search count don't add up after using aggregation I have an ES index, and I want to count the number of distinct CONTACT ID where [Have Agreement] flag is Y and N. The flag is unique for each CONTACT. However, when I add the contact with Y flag and N flag , the total count is different from total CONTACT number.
1.Total distinct CONTACT_ID count:
POST /dashboard/_search?size=0
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "CREATED": {
              "gte": "2021-07-04T00:00:00.001Z",
              "lte": "2021-12-31T00:00:00.001Z"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "UniqueContact": {
      "cardinality": {
        "field": "CONTACT_ID.keyword"
      }
    }
  }
}

result is 27588

2.Distinct CONTACT_ID count for Y and N flags respectively:
POST /dashboard/_search?size=0
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "CREATED": {
              "gte": "2021-07-04T00:00:00.001Z",
              "lte": "2021-12-31T00:00:00.001Z"
            }
          }
        }
      ]
    }
  },"aggs": {
    "CVID": {
      "terms": {
        "field": "Have Agreement.keyword",
        "order": {
          "type_count": "desc"
        }
      },
      "aggs": {
        "type_count": {
          "cardinality": {
            "field": "CONTACT_ID.keyword"
          }
        }
      }
    }
  }
}

result is 2692 and 2158. They add up  to  4850.

*Evidence that shows the flag is unique for each contact
POST /dashboard/_search?size=0
{
"query": {
"bool": {
"must": [
{
"range": {
"CREATED": {
"gte": "2021-07-04T00:00:00.001Z",
"lte": "2021-12-31T00:00:00.001Z"
}
}
}
]
}
},"aggs": {
"CVID": {
"terms": {
"field": "CONTACT_ID.keyword",
"order": {
"type_count": "desc"
}
},
"aggs": {
"type_count": {
"cardinality": {
"field": "Have Agreement.keyword"
}
}
}
}
}
}

A: Results seems to be coherent, according to your example.
Keep in mind cardinality are an approximation (you can set it to win some precision)
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html

*

*You have around 27588 distinct uniqueContact matching your query (cardinality is around 5% precision)

*Top aggregation by Y or N (Have Agreement.keyword)
In the result we can read:
16725 documents with N
11190 documents with Y

*

*For the N group, you have around 2692 different uniqueContact

*For the Y group, you have around 2158 different uniqueContact

So you have "duplicate" matching documents, we can see this in your 3) part.

*

*10 doc with 3-QV3ZBW uniqueContact

*10 doc with 3-QV3ZC3 uniqueContact

=>
So your second request is correct, you have around 2692 distinct uniqueContact with N value (2158 for Y)
The 2692 uniqueContact are present in 16725 docs, the 2158 others refers to 11190
16725 + 11190 => in the 27588 -+ 5%
PS: Add a query term on 3-QV3ZBW for example, I think this will answer to your question with a simple example.


text:
Q: Como mostrar e esconder elemento de acordo com scroll? Quero esconder a imagem quando o scroll da página for maior que 147, até ai tudo bem, o problema é que não consigo esconder a imagem novamente quando o scroll  for menor que 146. O objetivo é esconder e mostrar a imagem de acordo com o scroll.
Abaixo deixei um exemplo:

 $(document).ready( () => {
    var logo = $("#img-logo-fixed");
    $(document).scroll( function() {
      var scroll = $(document).scrollTop();
      if(scroll >= 147)  $("#img-logo-fixed").css("display", "block");
      if(scroll < 146 ) $("img-logo-fixed").css("display", "none");
    });
   });
#img-logo-fixed {
  position:fixed;
  top:0;
  display:none;
}

Alguém pode me ajudar?

A: Meu caro está faltando um "#" no seu script
Mais precisamente aqui: if(scroll < 146 ) $("img-logo-fixed") faltou o # do ID
Veja funcionando direitinho nesse snippet, só adicionei o # como diti e ficou 100%, mostrando e escondendo.

 $(document).ready( () => {
    var logo = $("#img-logo-fixed");
    $(document).scroll( function() {
      var scroll = $(document).scrollTop();
      if(scroll >= 147)  $("#img-logo-fixed").css("display", "block");
      if(scroll < 146 ) $("#img-logo-fixed").css("display", "none");
    });
   });
html, body {
    width: 100%;
    height: 300%;
    margin: 20px;
    padding: 0;
}
#img-logo-fixed {
  position:fixed;
  top:0;
  display:none;
}

Se vc quiser fazer uma transição suave da imagem aparecendo use o fadeIn e o fadeOut. Veja como fica no exemplo. Assim vc não precisa do CSS dando display block/none. Outra coisa, se vc criou a variável use-a...
  var logo = $("#img-logo-fixed");

  if(scroll >= 147)  $(logo).fadeIn();
  if(scroll < 146 ) $(logo).fadeOut();

Veja como fica no exemplo:

 $(document).ready( () => {
var logo = $("#img-logo-fixed");
$(document).scroll( function() {
    var scroll = $(document).scrollTop();
    if(scroll >= 147)  $(logo).fadeIn();
    if(scroll < 146 ) $(logo).fadeOut();
});
});
html, body {
    width: 100%;
    height: 200%;
    margin: 20px;
    padding: 0;
}
#img-logo-fixed {
  position:fixed;
  top:0;
  display:none;
}


text:
Q: file size method boost library oddity I am having an odd issue when using the file_size method from the boost library. If the path that I try to dereference using a directory iterator is not the current path where the executable is, then I get a value of 0 for any file sizes I try to return. So if my path variable is instantiated to "." for the current folder it will return byte sizes no problem but if I go one folder up or a path anywhere on the C drive the byte size of files is not returned. Is this an issue with scope or is there something I'm missing?

A: Turns out that if you are using a directory_iterator and are trying to find the file_size( dirIter->path() ) it will only work for the current folder the executable is in. However, if you concatenate the path of the directory you are searching using the variable name you assigned (for instance path p = "." ) it will return byte sizes for any file in any folder searched (an example of how to make it work would be file_size( p / dirIter->path() ) where the / is the overloaded concatenation operator in the boost library).


text:
Q: Parsing a string To Obtain two values What would be the simplest way of parsing this string I just want to get the two values out of it. I need to get the value after QueryParameter Parameter=\ and then the value from after \"$MPElement[Name='
Any help apreciated I did try the following code
string myString = listQueryParameter[0]._parameter.ToString();
string text= myString.Split(new [] {"QueryParameter Parameter="}, StringSplitOptions.None)[1];

But it still gave me everything after value along with it thanks.
<QueryParameter Parameter=\"TypeProjectionId\" Value=\"$MPElement[Name='System.WorkItem.Incident.View.ProjectionType']$\" xmlns=\"clr-namespace:Microsoft.EnterpriseManagement.UI.ViewFramework;assembly=Microsoft.EnterpriseManagement.UI.ViewFramework\" />"

A: Your input looks like XML, but isn't really valid XML.
My recommendation is to investigate where this stuff comes from, and fix the source so that it will produce correct XML. My guess is that in actuality you already have valid XML, but you looked at the string in the VS debugger and saw it with the backslashes added and then assumed that they are part of the string. If this is the case, then rest assured that they are not.
For reference, valid XML might look like this:
<QueryParameter Parameter="TypeProjectionId" Value="$MPElement[Name='System.WorkItem.Incident.View.ProjectionType']$" xmlns="clr-namespace:Microsoft.EnterpriseManagement.UI.ViewFramework;assembly=Microsoft.EnterpriseManagement.UI.ViewFramework" />

In other words, it's the same as yours but without the backslashes.
Now we can use XElement.Parse to turn this into a parsed value:
var xml = XElement.Parse(myString);

If you feed the invalid XML to this, this will throw.
Now we want to look at the values of the two attributes Parameter and Value:
var parameter = xml.Attribute("Parameter").Value;
var value = xml.Attribute("Value").Value;

At this point, value contains the string $MPElement[Name='System.WorkItem.Incident.View.ProjectionType']$. You said you wanted the part after Name=, so let's use a regular expression for that:
var match = Regex.Match(value, @"\bName='([^']*?)'");
if (!match.Success)
    throw new Exception("The Value attribute is not in a recognized format.");
var innerValue = match.Groups[1].Value;


text:
Q: Wordpress WP-Config and Functions? Working on a friend's site - that had no Editor or Plugin control in the WordPress CMS. I go to WP-Config and change:
define( 'DISALLOW_FILE_EDIT', true );
define( 'DISALLOW_FILE_MODS', true );
both to false which works fine.
Then I look in Functions.php (in the theme) and see at the top:
define( 'DISALLOW_FILE_EDIT', true );
define( 'DISALLOW_FILE_MODS', true );
Does this actually work? It doesn't seem to have any effect.

A: In PHP, define() is used to define a constant. Constants are so named because they cannot be redefined by subsequent define() calls using the same identifier.
So those definitions in functions.php are just (probably silently) ignored. Maybe they show up in a log file somewhere, though.


text: Q: What are the key phonetic differences between British English and Australian English? Due to historic reasons, they are somewhat similar (for example, both British and Australian speakers usually pronounce 'a' in words like 'hat' as [a] instead of [æ] as Americans would do). However, they sound distinctly different, but it's hard for me to point out those differences exactly. Would you do that?


text:
Q: Updating two tables with one to many relationship via form I am trying to update my two tables through my form but I am getting this error:
Started POST "/test" for ::1 at 2014-12-02 00:15:21 -0800
Processing by UsersController#create as JS
  Parameters: {"utf8"=>"✓", "users"=>{"first_name"=>"sdfdsfdsf", "last_name"=>"dsfdsfds", "email"=>"3213213@hotmail.com", "phone_number"=>"23123213", "message"=>"sdfdsfsdfdsfkjsdfksdfk;adklsfjksadfksjdfklsdf"}, "commit"=>"Save Users"}
Completed 500 Internal Server Error in 1ms

ArgumentError (wrong number of arguments (1 for 0)):
  app/controllers/users_controller.rb:32:in `create'

  Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (2.6ms)
  Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.text.erb (0.4ms)
  Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.text.erb (0.6ms)
  Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/diagnostics.text.erb (12.2ms)

I have been reading examples and documentation and I think I wrote my form correctly but I think my controller is missing some aspects because I am new to rails.

Here is my schema:
ActiveRecord::Schema.define(version: 20141130075753) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "contact_requests", force: true do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.text     "message",    null: false
    t.integer  "user_id"
  end

  add_index "contact_requests", ["user_id"], name: "index_contact_requests_on_user_id", using: :btree

  create_table "users", force: true do |t|
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.string   "first_name",   null: false
    t.string   "last_name",    null: false
    t.string   "email",        null: false
    t.string   "phone_number"
  end

end

Models:
class User < ActiveRecord::Base
  has_many :contact_requests
  validates(:first_name, presence: true)
  validates(:last_name, presence: true)
  validates(:email, presence: true)
  accepts_nested_attributes_for :contact_requests

end

class ContactRequest < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true
  validates :message, presence: true, length: { maximum: 500 }
end

user controller:
  def create
    if !(User.find_by(email: params[:users][:email]))
      @user = User.new(user_params)
      @contact_request = ContactRequest.new(contact_request_params)
      @contact_request.save
      @user.save
    else
      @contact_request = ContactRequest.new(contact_request_params)
      @contact_request.save
    end

  end

  private

    def user_params
      # strong_parameters, which requires us to tell Rails exactly which parameters
      # we want to accept in our controllers
      params.require(:users).permit(:first_name, :last_name, :email, :phone_number)
    end

end

form:

Contact Us

Reach us at (415)-911-9999

    <%= form_for(:users, remote: true, id: "contact-form", class: "contact-input") do |f| %>

            <%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>

            <%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>

            <%= f.email_field(:email, class: "form-control", placeholder: "Email") %>

            <%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>

            <%= f.fields_for :contact_requests do |builder| %>
              <%= f.text_area(:message, class: "form-control contact-margin", rows: "8", placeholder: "Message...") %>
              <% end %>

      <%= f.submit(class: "btn btn-xl") %>
    <% end %>


text:
Q: What is the difference between {} and ${} in JSX? The ${} is template literals. What's {} without the $ sign?
In React:
function App(){
    return(

);
}

(I was looking up the difference and nothing came up. So, I think this question is needed as I couldn't know if I was using JS or JSX.)

A: You're quite correct that javascript uses ${} to make use of template literals within strings surrounded by backticks `
The code you pasted is not javascript, it is JSX and the { and } is how you embed expressions within it.


text:
Q: Active Record save or create command $model = Person::findOne($person_id);
$model->status = $status;
$model->save();

or
Yii::$app->db->createCommand()->update('person',
              ['status'=>$status],
              'person_id='.$person_id)
         ->execute();

In terms of performance, how this two snippet different from each other although the result is the same?

A: The firts is based on the fact the related active record is obtained  by a preliminary select and then the change is performed  by an update    when the save() (and the related validation)  method is invoked ..
The second don't perform a select for get the related activeRecord ..
and perform the update only
so the second should be  more fast then the first ..

A: Using ActiveRecord (the first example) is generally more memory intensive (because of the object setup, teardown, validation etcetera).
The second one will be much faster but it does not validate the data. Most of the time you will want to work with a "small" set of ActiveRecords objects (that's why Yii2 has pagination in it's DataProviders). ActiveRecord is more powerful since you can traverse relations, use virtual attributes etc.
But for batch inserts the second one it is much better. And you can also use it like this to insert multiple rows in one query:
Yii::$app->db->createCommand()->batchInsert('tableName', ['id', 'title', 'created_at'], [
    [1, 'title1', '2015-04-10'],
    [2, 'title2', '2015-04-11'],
    [3, 'title3', '2015-04-12'],
])->execute();


text:
Q: jQuery - A Problem with nested each() I tried to look after a similar problem but couldn't find any here. So here is my problem.
I have a structure with multiple h2. Each h2 have an image inside that points to a different url. I need to fetch this url from each image and assign it to the correspondent h2.
Here is my code (this one works, but it only fetches the first link):
    $("h2").each(function() {

        var $link = $('a[rel=example_group]').attr("href");

        $(this).append($link);
    });

So I tried this:
    $("h2").each(function() {

        var $link = $('a[class=button zoom]').each(function(){$(this).attr("href")});

        $(this).append($link);
    });

but it is not working
Could you help? Thanks

A: $("h2").each(function(i,n) {

        var $link = $(n).find('a[rel=example_group]').attr("href");

        $(n).append($link);
    });

try this....

A: The problem is that you are not scoping your search for the a tag.
Just cache $(this) and do a find use it and it should work for you:
$("h2").each(function() {
    var h2 = $(this),
        $link = h2.find('a[rel=example_group]').attr("href");

    h2.append($link);
});

A: In your first example you always append the same link over each iteration.
Not sure what you're trying to do with the second example.
In your first example try to just add a context to your selector changing:
var $link = $('a[rel=example_group]').attr("href");

by
var $link = $('a[rel=example_group]',this).attr("href");

and it should work.
You also can do something like:
$("h2 a[rel=example_group]").each(function() {
    var $link = $(this).attr('href');
    // ... do what you need with $link ...//
});

It should work too if i understand well your request.

A: howabout
$("h2").each(function() {

    var $link = $(this).find('a[class=button zoom]').attr("href")});

    $(this).append($link);
});


text:
Q: Angular Displacement If something is rotating about a point and it covers a complete circle, should we take its angular displacement as 360 degree or 0?
Please give link to some established material on this subject which defines your answer, whether it is that it should be taken as 0 or 360 degrees.
Question that led to this problem : The angular speed of a motor wheel is increased from 1200 rpm to 3120 rpm in 16 seconds. 1. What is its angular acceleration, assuming the acceleration to be uniform, 2. How many revolutions does the wheel make during this time.
In the solution to above question the author(s) for solving part 2 have used equation of motion and mentioned that they have obtained angular displacement for it, it basically implied that the equations of motion used for rotation provide angular displacement which does not become zero on returning to original point which is not followed when we consider it analogous to displacement of linear motion.
Addendum : Even here ( Angular displacement and the displacement vector ) the selected answer says that on completing the circle, angular displacement is 360 degrees, is there some established text to support this ?
Similarly here ( http://www.ask.com/question/calculating-angular-displacement ) something else is said in the answer, is then angular displacement ambigous and hence has no correct definition, if there is please guide me to some established text.

A: The answer to your question is sometimes!
In most cases when we're dealing with angles we are using the trigonometric functions, and since these are periodic in angle with period $2\pi$ it doesn't matter whether you use zero, $2\pi$ or any multiple of $2\pi$ as your equations will give the same result.
Alternatively you could be describing some object moving in a circle in an external field e.g. a gravitational field, and again most of the time tracing one circle is the same as tracing any number of circles. This is true of all conservative fields.
The exception is in electrodynamics e.g. when you're a charged object moving in a circle, because in that case you will be generating a magnetic field and each revolution of the circle puts energy into the magnetic field. In that case how many times you go round the circle does matter.
Re the edit to the question:
Aha, you're mixing up two different concepts. The angle can mean the position or it can mean the total angle moved. Let me attempt to given example. Suppose you walk 1 km north then turn round and walk 1 km south back to where you started. Then your position in space hasn't changed, but you have still walked 2 kms. Likewise if you rotate an object by $2\pi$ its angle hasn't changed, but it has still travelled through $2\pi$ radians.
In the question you cite the total angle moved is just the integral of angular velocity wrt time, just as in linear motion the total distance moved is the integral of velocity wrt time.

A: Answer
Basically there are three different definitions assigned to the term angle as explained here. I am not familiar with the notations used in the link that I've given. So I cannot comment on it.
Your question is completely legitimate because in some circumstances the angle is taken as 0 degree if something is been rotated one complete circle(e.g. in case when we are talking of angle between vectors.)
When we use the term angle in the definition of Angular displacement$^{[1]}$ we are infact referring to the term rotated angle for the term angle. So in the situation that you have depicted in your question the definition of an angle as given in the established-text$^{[2]}$ is applicable for the term angle.
From the definition of an angle given in the referred established text it is clear that if something is rotating about a point and it covers a complete circle, we should take its angular displacement as 360 degree not 0 degree.
Your main question is:
"If something is rotating about a point and it covers a complete circle, should we take its angular displacement as 360 degree or 0?"
In short the answer is:
We should take its angular displacement as 360 degree not 0 degree because of its(angular displacement's) definition.
You also say "Is angular displacement ambiguous?"
No, suppose something covers one rotation in anticlockwise direction then we say it is rotated through an angle $+2\pi$ but if it is suddenly rotated back in clockwise direction we say it has covered an angle $-2\pi$ now so the net angle it covers is $0$. this is what displacement is all about i.e net change in parameters which is now $\theta$.

${}^{[1]}$Definition of Angular displacement:
Angular displacement of a body is the angle in radians (degrees, revolutions) through which a point or line has been rotated in a specified sense about a specified axis.

References
A Paragraph written in the Book: Fundamentals of Physics (8th Edition)
"we do not reset $\theta$ to zero with each compelete rotation of reference line about the rotation axis. if the reference line completes two rotations from the zero angular position then the angular position of the line is $\theta = 4\pi$ rad."
  Established text

"Unified algebra and trigonometry (Addison-Wesley mathematics series) article 3-5"
${}^{[2]}$3-5 Angles.
In geometry an angle has usually been defined as the configuration consisting of two half-lines (rays) radiating from a point. However in trigonometry we generalize the definition by stating that an angle thus defined by two half lines has a measure which corresponds to the amount of rotation required to move a ray from the position of one of these lines to the other. consider the figure$^{[3]}$ with two lines $m$ and $n$ intersecting at $o$ and lying in a plane prependicular to our line of vision. if we consider $m$ as initial line and $n$ as terminal side of the angle $o$ as its vertex, there are two possible directions of rotation of the initial side $m$. The angle is said to be positive if the rotation is counter clockwise, but negative if clockwise. A curved arrow will indicate the direction of rotation.
let us now consider a ray m which issues from the origin of a rectangular coordinate system and coincide with the positive x-axis(Fig 3-9). As this ray rotates, any point $P$ on $m$ will trace out part or all of the circumference of circle of radius $OP$. In fact the circumference may be traced several times.
 After the rotation  $OP$ will be in some position $OP'$, where the circular arc $\stackrel \frown {PP}^{'}$ denoted by $s$, may be used to measure the $POP^{'}$ is said to be standard position, and to be in quardrant in which its terminal side $OP^{'}$ is located .
The most logical units for measuring the magnitude of an angle $POP^{'}$. An angle would seem to be the number of revolutions due to the rotation from the initial to the terminal side of the angle. since the number of revolutions of any angle is determined by the ratio of the intercepted circular arc length $s$ to circumference of the circle we define, magnitude of an angle in revolutions as
Angle in revolutions$ = \frac{s}{2\pi r}$
For example if $P$ traces out an arc half the circumference, the corresponding angle is one of one-half a revolution. Likewise if arc is twice the circumference, the angle measure is two revolutions.
Consider the two coencentric circles at $o$, in Fig.3-10, with $\stackrel \frown {PP}^{'}$ as arc of length $s$ on the circle of radius $r$, and $QQ^{'}$ an arc of length $s^{'}$ on the circle of radius $r{'}$. By using the theorem that similar triangles have propotional sides, and recalling the definition of arc length from article 3.4 it can be proved that
$$\frac{s^{'}}{r^{'}} = \frac{s}{r},$$  and therefore,
$$\frac{s^{'}}{2\pi r^{'}} = \frac{s}{2\pi r}$$
The magnitude of any angle is thus independent of the length of its initial or terminal side. Although the use of revolutions is the most natural method for measuring angles, there are other more convenient systems.
The system most commonly used in elementary work such as survyeing and nevigation is sexagesimal, in which the degree is the fundamental unit. In this system one revolution = $360^0$, $1^0 = 60^0$(minutes) and $1^{'} = 60^{''}$(seconds)
Angle in degrees = (revolutions) $360^0$
For example, one-half a revolution is $180^0$, or an angle of two revolutions is $720^0$.
The other important system used in ...  ...
Angle in radians = (revolution) $2\pi$
                     __________________________
${}^{[3]}$I could not add the figure. Please refer to the original context.

A: An angle is a ratio. The ratio of arc length to radius. So if you want to consider zero arc length or full circle is really up to you. It depends on the situation. If you are using the angle for orientation it does not matter, but if you are using it for angular displacement it depends on the initial conditions.


text:
Q: text-overflow ellipsis doesnt work in css what can i do to make it work with one or two lines both?
can anyone help me? thank you in advance

322333333333333333333344444444444444444333333333333333333.png

.fileManager-file-name {
    font-size: 14px;
    cursor: pointer;
    vertical-align: middle;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 10px;
    width: 50px;
    white-space: nowrap;
}

A: It is because of the display: -webkit-box;. What happens is that it actually does work, you just can't see it. The text is cut off after width: 50px; and then the ellipsis are put behind the first word. In this case you have a really long word which means the ellipsis won't show up in the 50px.
You can see the difference it the code snippet below, the first div has the original content and the second one also does but with spaces between every number. (I also removed the white-space: nowrap; btw)

.fileManager-file-name {
    font-size: 14px;
    cursor: pointer;
    vertical-align: middle;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 10px;
    width: 50px;
}

322333333333333333333344444444444444444333333333333333333.png

3 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 44444444444444333333333333333333.png


text:
Q: How to get associated values from an array I am reading a JSON file and adding a list with its element in a menu button in the browser, then I would like to get the values from the element that I have selected in the drop down list, so I am trying something like this below but it returns:

"TypeError: selectedArray.values is not a function".

json = require('/myjsonFile');
event = json['foo']['bar'][0]['fooBar'];
var array = event.map( item => Object.keys(item) );

Template.board.helpers({
    'categories': function() {
        return array;
    }
});

Template.board.events({
    "change #category-select": function(event, template) {
        var selectedArray = $( event.currentTarget ).val();
        var data = selectedArray.values();
        console.log(data);
    }
});


text:
Q: How can racket run from the CMD I am trying to run racket form the command prompt and have the program output go to a textfile.
C:\Downloads>racketprogram.rkt 'run-file > output.txt
What am I doing wrong?

A: Have you tried looking at the Racket documentation about running a script or compiling a program?
Basics are that you can call a script with racket:
racket racketprogram.rkt 'run-file > output.txt

It says you can in both Windows and Unix add lines in the beginning that makes your program able to be run without being an argument to racket executable. In Windows it means you need to call your script racketprogram.bat while in Unix you just have to make it executable.
It's also possible to make an executable.
A compiled executable runs faster than a script so you get some benefits from it too:
raco exe racketprogram.rkt #makes either racketprogram or racketprogram.exe

Now the result won't run on a machine that doesn't have exact the same racket version installed so toyou have a different command to make a package with all dependencies. Thus. The result cannot cross OS borders but will be able to run on same OS elsewhere:
raco distribute racketprogram-package racketprogram[.exe]

A: The best way of running a Racket program I could figure out so far is:
racket -l errortrace -t <YOUR SOURCE CODE FILE.rkt>

This shows more about errors should they occur.


text:
Q: Silverlight4 WebContext I have built a Silverlight 4 application and I have hit a problem.
I have split my application into multiple xaps(different sub-systems) to reduce downloading / improve performance as not all subsystems are needed by every user.
However I want to share the WebContext between the xaps, rather than authenticating again and setting WebContext for each xap.
Is this possible? If so how can I achieve it?

A: You need to share a library with all your applications. So, let's assume you have 3 XAP projects called Project1.xap, Project2.xap, and Project3.xap. All these projects should reference another silverlight class library that has shared logic. In this shared project, you can create an interface that's implemented by the root application. Let's call this IApplicationContext.
The root application is the XAP file that loads all the other XAPs. Let's call it Root.xap. This one will manage the authentication and create an implementation of IApplicationContext which it will pass to the other XAPs upon creation.
// This is available for all projects (shared.dll)
public interface IApplicationContext
{
    string Username { get; }
    Guid SessionId { get; }
    // ...
}

// This is implemented in the root application (Root.xap)
public class MyAppContext : IApplicationContext
{
    public string Username { get; private set; }
    public Guid SessionId { get; private set; }
    // ...
}

You can share anything between the applications, and it will keep your separate projects testable because you can always stub/mock the IApplicationContext.


text:
Q: Tensorflow in_top_kv Hi there i'm trying to build a simple rnn with 11 inputs and 2 outputs
X=tf.placeholder(tf.float32,[None,n_steps,n_inputs])
y=tf.placeholder(tf.int32,[None,n_steps,n_outputs])
I know the rnn excepts an input in the shape of [batch_size,n_steps,n_inputs] so that's why i have shaped my placeholders like this
However when i run the code i get an error

ValueError: Shape must be rank 2 but is rank 3 for 'in_top_k/InTopKV2' (op: 'InTopKV2') with input shapes: [1,270,2], [1,270,2], [].

The error seems to originate here : correct = tf.nn.in_top_k(logits,tf.reshape(y,[1,n_steps,n_outputs]),1)
I have tried reshaping the logits, squeezing the logits, expanding the y dimensions, but nothing seems to work.
One difference that i have noticed is that when i squeeze the logits with
tf.squeeze(logits)

The error now says

ValueError: Shape must be rank 1 but is rank 3

That is the only 'progress' that i have been able to make, any help would be appreciated.
p.s go easy on me this is my first question ever

A: You have to reshape the inputs as 2D tensors, then you can reshape the result back to the desired shape:
logits_res = tf.reshape(logits, (-1, n_outputs))
y_res = tf.reshape(y, (-1, n_outputs))
correct_res = tf.nn.in_top_k(logits_res, y_res, 1)
correct = tf.reshape(correct_res, (-1, n_steps))


text:
Q: ¿Cómo puedo hacer que el usuario solo ingrese numeros y lo intente de nuevo en Java? Se supone que el funcionamiento es así, el programa solicita un numero y el usuario debe ingresarlo, en dado caso que el usuario ingrese una letra, un numero menor a 0 o no ingrese nada, le salte un error y le mencione que lo intente de nuevo, dándole al usuario intentos infinitos.
Lo he intentado pero solo consigo un bucle infinito dentro del catch, ¿me podrían ayudar?
public static void numero(){
        Scanner in = new Scanner(System.in);
        int i, numero;

        System.out.print("Ingresa solamente un numero: ");
        while(true){
            try {
                numero = in.nextInt();
                if(numero > 0){
                    break;
                } else {
                    System.out.print("Error, intenta de nuevo: ");
                }
            } catch (Exception e){
                System.out.print("Error, intenta de nuevo: ");
            }
        }

A:  public static boolean isNumeric(String cadena) {

        boolean verdad;

        try {
            Integer.parseInt(cadena);
            verdad = true;
        } catch (NumberFormatException excepcion) {
            verdad = false;
        }

        return verdad;
    }
    public static void main(String[] args) {

       Scanner in = new Scanner(System.in);
        int  numero;
        System.out.println("Ingresa solamente un numero:");
        String cadena= in.nextLine();
        while(isNumeric(cadena)==false ||  Integer.parseInt(cadena)<=0){
            System.out.println("La entrada no era un numero vuelva a intentarlo");
            cadena= in.nextLine();
        }

        if (isNumeric(cadena) == true) {
            numero = Integer.parseInt(cadena);
            System.out.println("Numero: " + numero);
        } else {
            System.out.println("No es un numero");
        }
    }

Necesitas hacer un método booleano isNumeric para verificar si una cadena x posee un número o letras. Al método se le pasa una cadena, y se verifica que si la misma es un número la bandera booleana seguirá en verdadero, en caso de que no sea un número, se llama a la excepción NumberFormatException se produce cuando intenta analizar una cadena no numérica. Luego en el main solo se invoca el método isNumeric y le pasamos la cadena que entre el usuario.
Puedes revisar tambien este link https://es.stackoverflow.com/questions/92139/cómo-verificar-que-el-valor-de-una-variable-string-es-un-integer-en-java


text:
Q: WMTS Layer Syntax for Leaflet I already tried to implement "http://api.ign.fr/tech-docs-js/examples/js/geoportalLeaflet.js, but it does not work for me.
I want to implement the following WMS Tile Layer:
https://www.wmts.nrw.de/geobasis/wmts_nw_dop20
Could someone help me ?


text:
Q: LINQ way to change my inefficient program Please consider the following records

I'm trying to flatten and group the data by Robot Name then by date + Left Factory time then group the address(es) for that date and time.  Notice that some of the Left Factory times are identical.
I wrote the code below and it works. It gives me the output that I want. I was a Perl developer so what you see below is from that mentality.  I'm sure there is a better way of doing it in LINQ.  A little help please.
static void Main(string[] args)
{
    if (args.Length < 0){
        Console.WriteLine("Input file name is required");
        return;
    }

  List<string>  rawlst = File.ReadAllLines(args[0]).ToList<string>();

    Dictionary<string, Dictionary<DateTime, List<string>>> dicDriver = new Dictionary<string, Dictionary<DateTime, List<string>>>();

    foreach (string ln in rawlst)
    {
        try
        {
            List<string> parts = new List<string>();
            parts = ln.Split(',').ToList<string>();

            string[] dtparts = parts[1].Split('/');
            string[] dttime = parts[15].Split(':');
            DateTime dtrow = new DateTime(
                int.Parse(dtparts[2]), int.Parse(dtparts[0]), int.Parse(dtparts[1]),
                int.Parse(dttime[0]), int.Parse(dttime[1]), int.Parse(dttime[2]));

            string rowAddress = parts[7] + " " + parts[9] + " " + parts[10] + " " + parts[11];

            if (!dicDriver.Keys.Contains(parts[3]))
            {
                Dictionary<DateTime, List<string>> thisRec = new Dictionary<DateTime, List<string>>();
                thisRec.Add(dtrow, new List<string>() { rowAddress });

                dicDriver.Add(parts[3], thisRec);

            }
            else
            {
                Dictionary<DateTime, List<string>> thisDriver = new Dictionary<DateTime, List<string>>();

                thisDriver = dicDriver[parts[3]];
                if (!thisDriver.Keys.Contains(dtrow))
                {
                    dicDriver[parts[3]].Add(dtrow, new List<string>() { rowAddress });
                }
                else
                {
                    dicDriver[parts[3]][dtrow].Add(rowAddress);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("ERROR:" + ln);
        }
    }

 //output
    string filename = DateTime.Now.Ticks.ToString() + ".out";
    foreach (var name in dicDriver.Keys)
    {
        foreach (var dd in dicDriver[name])
        {

                Console.Write(name + "," + dd.Key + ",");
            File.AppendAllText(filename, name + "," + dd.Key + Environment.NewLine);
            foreach (var addr in dd.Value)
            {
                Console.Write("\t\t" + addr + Environment.NewLine);
                File.AppendAllText(filename, "\t" + addr + Environment.NewLine);
            }

        }
        Console.Write(Environment.NewLine);
        File.AppendAllText(filename, Environment.NewLine);
    }

    Console.ReadLine();
}

A: You should separate your concerns: separate your input from the processing and from the output.
For example: suppose you would have to read your input from a database instead from a CSV file? Would that seriously change the way your process your fetched data? In your design, fetching the data is mixed with processing: although you know that the data that you want to process contains something like FactoryProcesses, you decide to present eache FactoryProcess as a string. A FactoryProcess is not a string. It describes how and when and who processed something in your factory. That is not a string, is it? However, it might be represented internally as a string, but the outside world should not know this. This way, if you change your FactoryProcess from being read by a CSV-file, to something provided by a database, the users of your FactoryProcess won't see any difference.
Separation of concerns makes your code easier to understand, easier to test, easier to change, and better to re-use.
So let's separate!
IEnumerable<FactoryProcess> ReadFactoryProcesses(string fileName)
{
     // TODO: check fileName not null, file exists
     using (var fileReader = new StreamReader(fileName))
     {
         // read the file Line by Line and split each line into one FactoryProcess object
         string line = fileReader.ReadLine();
         while (line != null)
         {
              // one line read, convert to FactoryProcess and yield return:
              FactoryProcess factoryProcess = this.ToFactoryProcess(line);
              yield return factoryProcess;

              // read next line:
              line = fileReader.ReadLine();
         }
    }
}

I'll leave the conversion of a read line into a FactoryProcess up to you. Tip: if the items in your lines are separated by a comma, or something similar, consider using Nuget Package CSVHelper. It makes if easier to convert a file into a sequence of FactoryProcesses.

I want to group the data by Robot Name then by date + Left Factory time then group the address(es) for that date and time.

First of all: make sure that the FactoryProcess class has the properties you actually need. Separate this representation from what it is in a file. Apparently you want to tread date + left factory as one item that represents the Date and Time that it left the factory. So Let's create a DateTime property for this.
class FactoryProcess
{
    public int Id {get; set}
    public int PartNo {get; set;}
    public string RobotName {get; set;}      // or if desired: use a unique RobotId
    ...

    // DateTimes: ArrivalTime, OutOfFactoryTime, LeftFactoryTime
    public DateTime ArrivalTime {get; set;}
    public DateTime OutOfFactoryTime {get; set;}
    public DateTime LeftFactoryTime {get; set;}

}
The reason that I put Date and Time into one DateTime, is because it will solve problems if an item arrives on 23:55 and leaves on 00:05 next day.
A procedure that converts a read CSV-line to a FactoryProcess should interpret your dates and times as strings and convert to FactoryProcess. You can create a constrcuctor for this, or a special Factory class
public FactoryProcess InterpretReadLine(string line)
{
    // TODO: separate the parts, such that you've got the strings dateTxt, arrivalTimeTxt, ...
     DateTime date = DateTime.Parse(dateTxt);
     TimeSpan arrivalTime = TimeSpan.Parse(arrivalTimeTxt);
     TimeSpan outOfFactoryTime = TimeSpan.Parse(outOfFactoryTimeTxt);
     TimeSpan leftFactoryTime = TimeSpan.Parse(leftFactoryTimeTxt);

    return new FactoryProces
    {
        Id = ...
        PartNo = ..
        RobotName = ...

        // The DateTimes:
        ArrivalTime = date + arrivalTime,
        OutOfFactoryTime = date + outOfFactoryTime,
        LeftFactoryTime = date + leftFactoryTime,
    };
}

Now that you've created a proper method to convert your CSV-file into a sequence of FactoryProcesses, let's process them

I want to group the data by Robot Name then by date + Left Factory time then group the address(es) for that date and time.

var result = fetchedFactoryProcesses.GroupBy(

    // parameter KeySelector: make groups of FactoryProcesses with same RobotName:
    factoryProcess => factoryProcess.RobotName,

    // parameter ResultSelector: from every group of FactoryProcesses with this RobotName
    // make one new Object:
    (robotName, processesWithThisRobotName) => new
    {
        RobotName = robotName,

        // Group all processes with this RobotName into groups with same LeftFactoryTime:
        LeftFactory = processesWithThisRobotName.GroupBy(

            // KeySelector: make groups with same LeftFactoryTime
            process => process.LeftFactoryTime,

            // ResultSelector: from each group of factory processes with the same LeftFactoryTime
            (leftFactoryTime, processesWithThisLeftFactoryTime) => new
            {
                LeftFactoryTime = leftFactoryTime,
                FactoryProcesses = processesWithThisLeftFactoryTime,

                // or even better: select only the properties you actually plan to use
                FactoryProcesses = processesWithThisLeftFactoryTime.Select(process => new
                {
                     Id = process.Id,
                     PartNo = process.PartNo,
                     ...

                     // not needed: you know the value, because it is in this group
                     // RobotName = process.RobotName,
                     // LeftFactoryTime = process.LeftFactoryTime,
                }),
            })
});

For completeness: grouping your code together:
void ProcessData(string fileName)
{
     var fetchedFactoryProcesses = ReadFactoryProcess(fileName);  // fetch the data
     var groups = fetchFactoryProcesses.ToGroups();               // put into groups
     this.Display(groups);                                        // output result;
}

Because I separated the input from the conversion of strings to FactoryProcesses, and separated this conversion from the grouping, it will be easy to test the classes separately:

*

*your CSV-reader should return any file that is divided into lines, even if it does not contain FactoryProcesses

*your conversion from read line to FactoryProcess should convert any string that is in the proper format, whether it is read from a file or gathered any other way

*your grouping should group any sequence of FactoryProcesses, whether they come from a CSV-file or from a database or List<FactoryProcess>, which is very convenient, because in your tests it is way easier to create a test list, than a test CSV-file.

If in future you decide to change the source of your sequence of FactoryProcesses, for instance it comes from a database instead of a CSV-file, your grouping won't change. Or if you decide to support entering and leaving factories on different dates (multiple date values) only the conversion changes. If you decide to display the results in a tree-like fashion, or decide to write the groups in a database, your reading, conversion, grouping, etc won't change: what a high degree or re-usability!
Separating your concerns made it much easier to understand how to solve your grouping problem, without the hassle of splitting your read lines and converting Date + LeftFactory into one value.


text:
Q: Need to exclude some external links from receiving this notification I am using this code to notify a user they are going to a 3rd party site but I want to exclude some URLs that are external. How/where can I do that in this code?
<script>
   $('a').each(function() {
      if (this.href !== "#" && this.href.indexOf('/') !== 0 && this.href.indexOf(location.hostname) === -1) {
        $(this).attr('target', '_blank')
          .click(function() {        return confirm('NOTICE: You are leaving our website and will enter a website maintained by a third party. We are providing a link to the third party website solely as a convenience to you, because we believe that website may provide useful content. We are not, by referring or linking to the third party website, incorporating its contents into our own website. We do not endorse or guarantee, and we disclaim any responsibility for: the content, products or services offered on that website, its performance or interaction with your computer, its security and privacy policies and practices, and any consequences that may result from visiting that website. By clicking OK, you acknowledge this statement.');
       });
      }
    });
});
</script>

A: You will need to check if the site is within a white list. So you will need to create something to allow you to check a list if sites.
I also would recommend that you extract the logic to a function to make it a bit easier to maintain.
  function IsNoticeRequired(url)
  {
      // Makes dealing with exclusions easier.
      url = url.toLowerCase();

      // Put the white listed sites here.
      var excludedSites =
      [
          "stackoverflow.com"
      ];

      // Determine if the site is in the exclusion list.
      var isInExclusion = false;
      for(var i = 0; i < excludedSites.length; i++)
      {
          // Need to check if url contains site.
          if(url.indexOf(excludedSites[i]) !== -1)
          {
              isInExclusion = true;
              break;
          }
      }

      var isNoticeRequired = url !== "#";
      isNoticeRequired = isNoticeRequired && url.indexOf("/") !== 0
      isNoticeRequired = isNoticeRequired && url.indexOf(location.hostname) === -1;
      isNoticeRequired = isNoticeRequired && !isInExclusion;

      return isNoticeRequired;
  }

$('a').each(function() {
  if (IsNoticeRequired(this.href)) {
    $(this).attr('target', '_blank')
      .click(function() {        return confirm('NOTICE: You are leaving our website and will enter a website maintained by a third party. We are providing a link to the third party website solely as a convenience to you, because we believe that website may provide useful content. We are not, by referring or linking to the third party website, incorporating its contents into our own website. We do not endorse or guarantee, and we disclaim any responsibility for: the content, products or services offered on that website, its performance or interaction with your computer, its security and privacy policies and practices, and any consequences that may result from visiting that website. By clicking OK, you acknowledge this statement.');
   });
  }
});

JSFiddle of it in action: https://jsfiddle.net/9n7v67xa/


text:
Q: UITextView Select All I'm using UITextView, How can I show Select All in edit menu? then when user click Select All edit menu will show just copy and define?
This code doesn't work:
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(copy:) || action == @selector(select:) || action == @selector(selectAll:))
    {
        return [super canPerformAction:action withSender:sender];
    }

    self.TextArea.selectedTextRange = nil;

    return NO;

}

-(void)select:(id)sender
{

}

-(void)selectAll:(id)sender
{
    [self.TextArea setSelectedTextRange:[self.TextArea textRangeFromPosition:self.TextArea.beginningOfDocument toPosition:self.TextArea.endOfDocument]];

}

-(void)copy:(id)sender
{
    self.TextArea.selectedTextRange = nil;
}


text:
Q: How to turn String Value into Number - Google Tag Manager Im setting up my Google Tag Manager and I want to grab the purchase value from my Data Layer. This works fine, but Facebook doesn't recognize this value as its a "String" and not a number.
Therefore my question is: How can I convert this String (Return Type) to a Number (Return Type) in order for Facebook to pick it up? If that helps, its a currency.

A: Create JavaScript Variable named "String2Number Convertor"
function(){
  return function(s){
    return +s;
  }
}

Create another JavaScript Variable named "Facebook Purchase Value"
function(){
  return {{String2Number Convertor}}({{DataLayer Conversion Value}})
}

I assume you have your purchase value in data layer variable I called in this example as DataLayer Conversion Value
With this approach you can convert any other variables into number.


text:
Q: How to see al the commit tree in git bash? Suppose i have this log in my git bash
a16asd
jh243f
h32khk
324io2
k32lji

and a16asd is my HEAD. Now when i do
git reset --hard jh243f

Now i have this log
jh243f
h32khk
324io2
k32lji

But the commit a16asd is still available to jump to, although not visible when using git log command in the bash. The question is, how to see all the tree, including the commits that are not present in the current tree.

A: You cannot easily visualize 'all of the tree' as you asked and hope to see the commit you just reset, because it's not referred to any more.
You can still see the 'lost' commit a16asd with git reflog. http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html gives a good overview.
If what you want to do is see all commits in all branches, git log --all is what you need.


text:
Q: Message after sending email (mailer: flutter) I'm trying to put a pop or even an alertedialog to announce that the message is sent or not.
Currently I only have a print that displays but in the console .. So not useful for the user.
How do I get to my goal?
  sendMail() async {
    // Information connexion serveur smtp
    String username = 'xxx';
    String password = 'xxxx';
    String domainSmtp = 'xxx';

    final smtpServer = SmtpServer(domainSmtp,
        username: username, password: password, port: 587);

    //Création du message
    final message = Message()
      ..from = Address(username, '')
      ..recipients.add('xxxx')

      //..ccRecipients.addAll(['destCc1@example.com', 'destCc2@example.com'])
      //..bccRecipients.add(Address('bccAddress@example.com'))
      ..subject =
          "Demande ::  :: ${DateTime.now()}"
      ..text = ''
      ..html =
          "
Nom: ${nomController.text}

 Prénom: ${prenomController.text}

 Email: ${emailController.text}
   \n

";

    try {
      final sendReport2 = await send(message, smtpServer);
      var connection = PersistentConnection(smtpServer);
      await connection.send(message);
      await connection.close();
      print('Message envoyé: ' + sendReport2.toString());
    } on MailerException catch (e) {
      print('cMessage envoyé.');
      for (var p in e.problems) {
        print('Probleme: ${p.code}: ${p.msg}');
      }
    }
  }
}

A: Use a snackbar or a AlertDialog
More info on snackbar :https://flutter.dev/docs/cookbook/design/snackbars

A: I managed to solve my problem with fluttertoast.
https://pub.dev/packages/fluttertoast
At the moment I am looking to add an icon .. If you had an idea I am a taker.
try {
  final sendReport2 = await send(message, smtpServer);
  print('Message envoyé: ' + sendReport2.toString());
  Fluttertoast.showToast(
      msg: "Demande envoyé avec succes",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.green,
      textColor: Colors.white,
      fontSize: 16.0);
} on MailerException catch (e) {
  print('cMessage envoyé.');
  for (var p in e.problems) {
    Fluttertoast.showToast(
        msg: "Erreur",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
    print('Probleme: ${p.code}: ${p.msg}');
  }
}


text:
Q: DATEDIFF vs (w1.date = w2.date +1) difference? MySQL syntax I was working on a SQL database question using MySQL. The goal is to find all IDs that satisfy today is warmer than yesterday. I'll show you my original code, which passed 2 out of 3 test cases and then a revised code which satisfies all 3.
What is the functional difference between these two? Is it a MySQL thing, leetcode thing, or something else?
Original
SELECT DISTINCT w2.id
FROM weather w1, weather w2
WHERE w2.RecordDate = w1.RecordDate +1 AND w2.temperature > w1.temperature

Revised
SELECT DISTINCT w2.id
FROM weather w1, weather w2
WHERE DATEDIFF(w2.RecordDate,w1.RecordDate) =1 AND w2.temperature > w1.temperature

The only differences is the use of DATEDIFF or use of w2.recordDate = w1.recordDate + 1.
I'd like to know, what is the difference between these two?
Edit: here's the LC problem https://leetcode.com/problems/rising-temperature/

A: This does not do what you want:
w2.RecordDate = w1.RecordDate + 1

Because you are using number arithmetics on date, this expression implicitly converts the dates to numbers, adds 1 to one of them, and then compares the results. Depending on the exact dates, it might work sometimes, but it is just a wrong approach. As an example, say your date is '2020-01-31', then adding 1 to it would produce integer number 20200132.
MySQL understands date arithmetics, so I would use:
w2.RecordDate = w1.RecordDate + interval 1 day


text:
Q: What is a good handwriting recognition software? I bought a Livescribe pen which records whatever I write (and say).
However, it can only give me pdf versions of what I wrote. Using MyScript (an paid extension) I can have it convert my handwritten notes to digital text.
But it turns out it doesn't like Dutch very much and isn't working perfect.
So my question is: does anyone know of a handwriting recognition software that can convert my pdf files to digital text?
Preferably free and for Windows 7.

A: Tesseract.
From Wikipedia:

It was originally developed as
  proprietary software at
  Hewlett-Packard between 1985 until
  1995. After ten years without any development taking place, Hewlett
  Packard and UNLV released it as open
  source in 2005. Tesseract is currently
  developed by Google and released under
  the Apache License, Version 2.0.
Tesseract is considered one of the
  most accurate free software OCR
  engines currently available

The drawback is that it only processes tiff file, maybe you can use other convertor to convert pdf to tiff and let Tesseract does the job.

A: I don't have much experience with these applications, but you can take a look at this list and try out some of them.

A: Handwriting is very hard to convert after the fact, there is a digital ink format that captures the time related portion of the info, which makes it doable.  Good luck, write in English (larger and thus more money spent on development)? It is a hard problem.


text:
Q: Okta as IDP for Azure So I want to provide access to users over Okta to Azure.
We have local AD which is not synced to MS Azure account
We have custom domain inside Azure AD
There is also 2nd part of this where we want to sync local AD mail field to Workday and add some O365 users to the same tenant which is another (native) Okta app.
So looking at docs, it seems I need to install ADConnect client which will import all users to the same O365/Azure tenant. Then on the Okta, there is native o365 app that I simply need to configure (it didn't look like problematic). But for the Azure part, the documentation is not really good and I am confused what should I do with Azure.
It seems I need to add Custom SAML 2.0 Application on Okta for Azure and configure External Identities-->New SAML connection on Azure. There also should be a way how to link Okta users to AzureAD ones but they have different domains. Did I get this correctly?
Thank you!

A: You can do the following:

*

*Use AAD Connect to sync on-premise users to Azure AD

*Integrate on-premise AD with Okta

*Use Okta's native Office 365 application to integrate Okta with Azure AD for Single Sign On. When you use this application, you don't have to do anything on Azure AD. Okta will take care of everything for you. All you need to do is follow these steps: https://help.okta.com/en/prod/Content/Topics/Apps/Office365-Deployment/configure-sso.htm