text:
Q: WebLogic 9.2 Loadbalancing problem I have a setup of 2 independent WebLogic 9.2.1 servers (they are Managed servers with their own Admin server). So no Clustering has been setup. They are configured with JDBC Session Persistence. Furthermore each of the WebLogic servers have their own Apache 2 Front-End with the WebLogic plugin only forwarding traffic to their respective WebLogic server.
In front of the Apache 2 servers I have a hardware Load Balancer.
Currently we are getting Constraint Violations from the Oracle database that hosts the table used for session persistence.
I found out that the hardware load balancer is using sticky IP's (so sessions should also be sticky as a result). But it escapes me what is wrong in the setup?
WebLogic log:

####<Apr 26, 2011 13:00:08.0428 CEST> <Error> <HTTP Session> <sktpens01por02> <SktEnsPorServer1> <[ACTIVE] ExecuteThread: '230' for queue: 'weblogic.kernel.Default (self-tuning)'> <skatGuid=6fa90948-b285-45a5-954b-45e22bfc26c2,ou=company,ou=external,ou=entities,dc=skat,dc=dk> <> <> <1303815608428> <BEA-100087> <The jdbc session data for session id: lZbJN2jTbPZjTf81vSrKytxDdYCpwTgblJhnck3RhTcPf3FQr1Pw ctx:front dblat:1303815595796 triggerLAT:0 has been modified by another server in the cluster.
java.sql.SQLException: ORA-00001: unique constraint (FRONTSESSIONS.SYS_C0056504) violated

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:219)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:970)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3370)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3454)
    at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:128)
    at weblogic.servlet.internal.session.JDBCSessionData.dbCreate(JDBCSessionData.java:181)
    at weblogic.servlet.internal.session.JDBCSessionData.dbUpdate(JDBCSessionData.java:242)
    at weblogic.servlet.internal.session.JDBCSessionData.syncSession(JDBCSessionData.java:583)
    at weblogic.servlet.internal.session.JDBCSessionContext.sync(JDBCSessionContext.java:232)
    at weblogic.servlet.internal.ServletRequestImpl$SessionHelper.syncSession(ServletRequestImpl.java:2507)
    at weblogic.servlet.internal.ServletRequestImpl$SessionHelper.syncSession(ServletRequestImpl.java:2482)
    at weblogic.servlet.internal.ServletResponseImpl$1.run(ServletResponseImpl.java:1308)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.ServletResponseImpl.send(ServletResponseImpl.java:1302)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1368)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
>
####<Apr 26, 2011 13:00:08.0436 CEST> <Error> <HTTP Session> <sktpens01por02> <SktEnsPorServer1> <[ACTIVE] ExecuteThread: '230' for queue: 'weblogic.kernel.Default (self-tuning)'> <skatGuid=6fa90948-b285-45a5-954b-45e22bfc26c2,ou=company,ou=external,ou=entities,dc=skat,dc=dk> <> <> <1303815608436> <BEA-100060> <An unexpected error occurred while retrieving the session for Web application: weblogic.servlet.internal.WebAppServletContext@26f86bfb - appName: 'Portal-Front', name: 'front', context-path: '/front'.
java.sql.SQLException: ORA-00001: unique constraint (FRONTSESSIONS.SYS_C0056504) violated

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:219)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:970)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3370)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3454)
    at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:128)
    at weblogic.servlet.internal.session.JDBCSessionData.dbCreate(JDBCSessionData.java:181)
    at weblogic.servlet.internal.session.JDBCSessionData.dbUpdate(JDBCSessionData.java:242)
    at weblogic.servlet.internal.session.JDBCSessionData.syncSession(JDBCSessionData.java:583)
    at weblogic.servlet.internal.session.JDBCSessionContext.sync(JDBCSessionContext.java:232)
    at weblogic.servlet.internal.ServletRequestImpl$SessionHelper.syncSession(ServletRequestImpl.java:2507)
    at weblogic.servlet.internal.ServletRequestImpl$SessionHelper.syncSession(ServletRequestImpl.java:2482)
    at weblogic.servlet.internal.ServletResponseImpl$1.run(ServletResponseImpl.java:1308)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.ServletResponseImpl.send(ServletResponseImpl.java:1302)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1368)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
>

Oracle Table definition:
CREATE TABLE "FRONTSESSIONS"."WL_SERVLET_SESSIONS"
  (
    "WL_ID"           VARCHAR2(100 BYTE) NOT NULL ENABLE,
    "WL_CONTEXT_PATH" VARCHAR2(100 BYTE) NOT NULL ENABLE,
    "WL_IS_NEW"       CHAR(1 BYTE),
    "WL_CREATE_TIME"  NUMBER(20,0),
    "WL_IS_VALID"     CHAR(1 BYTE),
    "WL_SESSION_VALUES" LONG RAW,
    "WL_ACCESS_TIME"           NUMBER(20,0),
    "WL_MAX_INACTIVE_INTERVAL" NUMBER(*,0),
    PRIMARY KEY ("WL_ID", "WL_CONTEXT_PATH") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "FRONTSESSIONS" ENABLE
  )
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE
  (
    INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT
  )
  TABLESPACE "FRONTSESSIONS" ;

Thanks!

A: The fact that those are 2 independent servers (without clustering in WebLogic sense) does not stop WebLogic to generate same ids for sessions. If those 2 servers where in a cluster, then WebLogic would add node id as part of the session id. But becuase servers are not in the cluster, of course, there is a chance that at some point they will generate same session id.
The only way you can avoid that exception is to configure both servers to use different tables or database for session storage.


text:
Q: Unique Keys for Options in React I'm trying to implement a an array of options for a form. Even though I have already implemented the key prop, I keep getting this error:
Each child in an array should have a unique "key" prop.
The options are taken from the following array of options:
[
  {
    "id": 1,
    "label": "Active",
    "value": "Active"
  },
  {
    "id": 2,
    "label": "Inactive",
    "value": "Inactive"
  },
  {
    "id": 3,
    "label": "Alert",
    "value": "Alert"
  }
]

Below follows my code:

    Status
    <select
      value={camposFormulario?.status}
      onChange={(event) =>
        setCamposFormulario((prev) => ({
          ...prev,
          ['status']: event.target.value,
        }))
      }
    >
      {statusList.map((option: any) => {
        return (
          <option key={option.id} value={option.value}>
            {option.label}
          </option>
        );
      })}
    </select>

I have read this topic: Understanding unique keys for array children in React.js and I believe I have followed the indications.
Any help would be much appreciated.
Thanks a lot!
Edit:
Also, if I change the map function by this it works:
<option>Ativo</option>
<option>Inativo</option>
<option>Em Alerta</option>

A: although your id should be unique, you could use the provided index:
statusList.map((option, index) => { ... })

where index is the array-index

A: Got it. Thanks for the help in the comments Jan!
Since statusList comes from an api call, its value is 0 when the page first renders. That's when the error is being displayed.
Any suggestions on how to render AFTER statusList is returned are very welcome!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is R showing mixed German/French messages when no locale is set? I've installed R 4.2.1 (arm64) from CRAN on macOS Monterey. My system's preferred language is set to English, yet R uses a weird mix of French and German to show error messages, and this is breaking tests and CI pipelines:
base::xyz
# Fehler: Objekt 'xyz' nicht gefunden

utils::xyz
# Fehler: 'xyz' n'est un object exporté depuis 'namespace:utils'

I have no specific locale set (note in particular the setting of LC_MESSAGES):
$ locale
LANG=""
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=

$ env | grep 'LANG\|LC'
LC_TERMINAL_VERSION=3.4.16
LC_CTYPE=UTF-8
LC_TERMINAL=iTerm2

And this is also what R is seeing:
lapply(.LC.categories, Sys.getlocale) |>
    structure(names = .LC.categories, class = 'simple.list')
               _
LC_ALL         C/UTF-8/C/C/C/C
LC_COLLATE     C
LC_CTYPE       UTF-8
LC_MONETARY    C
LC_NUMERIC     C
LC_TIME        C
LC_MESSAGES    C
LC_PAPER
LC_MEASUREMENT

Furthermore, this behaviour seems to only extend to messages: when parsing or formatting numbers or dates, R's behaviour is locale independent.
I can stop this behaviour by explicitly setting LC_MESSAGEs or LANG, e.g.:
$ LANG=en_GB.utf-8 Rscript -e 'utils::foo'
Error: 'foo' is not an exported object from 'namespace:utils'

However, I don't understand why this is required, and where R is getting its weird localisation preference from (especially since LC_MESSAGES is set to C).

For completeness, my current location is in Switzerland, as is my public IP address. And the computer model was purchased on the Swiss Apple Store. But the system's language is set to English in the Preference Pane (although by default the shell doesn't seem configured to see this). I should also note that I am launching R via the command line, not via any kind of GUI.


text:
Q: Different alignments in same environment? How do I get different alignments in the same align environment? Here some (pseudo)-code to illustrate my idea:
\begin{align}
a = &2\\
&+ 3 + 4 \notag\\
&= now I would like the equation sign to be aligned with the first equation sign at line 1
\end{align}

Is there any of you LaTeX wizards who can help me?

A: You have a few choices:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{align}
\begin{split}
a &= 2+2+2+2+2 \\
  &\quad +3+4
\end{split}
\\
  &= x+y+z
\end{align}

\begin{align}
a &= \begin{aligned}[t]
       & 2+2+2+2+2 \\
       & +3+4
     \end{aligned}
\\
  &= x+y+z
\end{align}

\end{document}

A: For my tastes I will do your code with this MWE where there is a perfect vertical alignment between 2 and + as by screenshot and between two equal signs.

\documentclass[a4paper,12pt]{article}
\usepackage{amsmath}

\begin{document}
\begin{align}
a &= 2\\
&\phantom{{}=}+ 3 + 4 \notag\\
&= \dotsb
\end{align}
\end{document}


text:
Q: Python: I am trying to use a function returned by another function I am learning Python for scientific computing, and there is an exercise where I create a polynomial using its roots:

Exercise 3.5
from sympy import symbols, expand

def poly(roots):            #Pass real and/or complex roots

    x = symbols('x')
    f = 1
    for r in roots:
        f *=(x - r)

    return expand(f)

Test:
from numpy.lib.scimath import sqrt
poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])

Gives:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0

I am trying to return the polynomial and use it by passing  a x value:
f = lambda x: poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
f(-1/2)

Gives:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0

The problem is that f(-1/2) is not giving 0, which it should. How can I tell Python to use the expression algebraically? Thank you!

A: You have to substitute for x and evaluate the polynomial to a float:
poly(...).subs('x', y).evalf()

Try with it:
from sympy import symbols, expand, sqrt

def poly(roots):  # Pass real and/or complex roots
    x = symbols('x')
    f = 1
    for r in roots:
        f *= (x - r)

    return expand(f)

f = lambda y: poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73), (-7 / 2) - (1 / 2) * sqrt(73)]).subs('x',
                                                                                y).evalf()
print(f(-1 / 2))

Output:
-1.06581410364015e-14

A: You can also use python's builtin eval() and str() function. eval() takes a string as an input.
from sympy import symbols, expand,sqrt

def poly(roots):            #Pass real and/or complex roots

x = symbols('x')
f = 1
for r in roots:
    f *=(x - r)

return str(expand(f))

f = lambda x: eval(poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73),(-7 / 2) - (1 / 2) * sqrt(73)]))
print(f(-1/2))

Output:
    0.0


text:
Q: How do I make an SVG dynamically scale with it's parent div? I have a small HTML file with an inline SVG object. Currently, the displayed SVG is quite large and the user needs to zoom out to see it fully. I want to make it so that 100% of the SVG is scaled within it's parent div, but I'm having issues doing this through CSS. Additionally, I'm trying to find a way to do this without needing to edit the SVG file itself, and hopefully I could cycle between any SVG file and it would scale the same.
As an example, here are small chunks of the actual files I'm working with:
HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">

        <link rel="stylesheet" type="text/css" href="styles/styles.css">
        <title>OMIX Map</title>

OMIX MAP

            <object id="map-svg" type="image/svg+xml" data="images/map.svg" onload="loadSVG()"></object>

SVG:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:omix="http://www.omix.bio/xsd/omixsvg" xmlns:xlink="http://www.w3.org/1999/xlink" baseProfile="tiny" height="2541" version="1.2" width="2298" xmlns="http://www.w3.org/2000/svg">
  <title>Network 'Homo sapiens'</title>
  <desc>Created with Omix</desc>
  <defs>
    <clipPath id="clipPath1">
      <path d="M0,0 L2298.591,0 L2298.591,2541.682 L0,2541.682 L0,0"/>
    </clipPath>
  </defs>
  <g clip-path="url(#clipPath1)" fill="none" fill-rule="evenodd" font-family="Helvetica" font-size="7.5px" font-style="normal" font-weight="400" id="ID3f9bfff0" stroke="#000000" stroke-linecap="square" stroke-linejoin="bevel" stroke-opacity="1" stroke-width="1">
    <g class="Metabolite" id="Metabolite$NADH$3" name="NADH" omix:clone="3">
      <g class="Shape" id="Shape_of_Metabolite$NADH$3">
        <path d="M-30,-15 C-30,-17.761 -27.851,-20 -25.2,-20 L25.2,-20 C27.851,-20 30,-17.761 30,-15 L30,15 C30,17.761 27.851,20 25.2,20 L-25.2,20 C-27.851,20 -30,17.761 -30,15 L-30,-15" fill="#a28dff" fill-opacity="1" fill-rule="evenodd" id="ID3f089e5e" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-opacity="1" stroke-width="1" transform="matrix(1.0,0.0,0.0,1.0,1206.0929206118517,898.2429901388446)" vector-effect="none"/>
      </g>
      <g class="Label" id="Label_of_Metabolite$NADH$3">
        <text fill="#000000" fill-opacity="1" font-family="Helvetica" font-size="18px" font-style="normal" font-weight="700" id="ID4037e797" stroke="none" transform="matrix(1.0,0.0,0.0,1.0,1173.6866706118517,883.2429901388446)" x="4.812" xml:space="preserve" y="22">NADH</text>
      </g>
    </g>
  </g>
</svg>

CSS:
#map {
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
}

#map-svg {
  height: 100%;
  width: 100%;
}


text:
Q: How to return response to AWS API Gateway after several AWS Lambda invocations Sorry if the title is not good enough, I am trying to achieve the following:

*

*API Gateway get Request 'A' and triggers Lambda Function B

*Lambda Function B writes to queue C

*Lambda Function D is listening on queue C (and gets triggered and process data and writes to queue E)

*Lambda Function F is listening on queue E (gets triggered and send response to the Request 'A'.

My question is how to maintain track of the request that was originated and how to properly respond to the API Gateway instance that was triggered.

A: The chaining of Lambda processing could be achieved by AWS Step Functions.
Step functions implement a state machine for synchronization among Lambda calls.
You can achieve the same with a synchronous Lambda invocation, but you have to pay double (waiting time of the caller and processing time of the callie).
The benefit of Step functions is, you don't pay for waiting.

A: To my knowledge, you cannot do that. After Lambda Function B writes to Queue C, it is done. Invocation of Lambda Function D is event-driven and not on-demand and you cannot wire up multiple individual processes in the original request A as it is done by that time.


text:
Q: overflow-x not working css I am trying to create a simple scrolling parent div. in which child div should be stacked horizontally.
slackblitz
But it is not working. child divs are wrapped after div width end. Please help.

#outerContainer {
      width: 100%;
      height: 150px;
      background: red;
      overflow: hidden;
      overflow-x: scroll;
    }

    .card {
      float: left;
      display: inline-block;
      width: 100px;
      height: 150px;
      margin-right: 10px;
      background: #fff;
    }

A: #outerContainer {
  width: 100%;
  height: 150px;
  background: red;
  overflow: hidden;
  overflow-x: scroll;
  white-space:nowrap;
}

.card {
  display: inline-block;
  width: 100px;
  height: 150px;
  margin-right: 10px;
  background: #fff;
}

A: Just remove float:left; from .card class and add white-space:nowrap; in #outerContainer

#outerContainer {
  width: 100%;
  height: 150px;
  background: red;
  overflow: hidden;
  overflow-x: auto;
  white-space: nowrap;
}

.card {
  display: inline-block;
  width: 100px;
  height: 150px;
  margin-right: 10px;
  background: #fff;
}

A:

#outerContainer {
  width: 100%;
  height: 150px;
  background: red;
  overflow: hidden;
  overflow-x: scroll;
  display: flex;
}

.card {
  min-width: 100px;
  height: 150px;
  margin-right: 10px;
  background: #fff;
}

Your card elements go to second row. flex can make it a bit easier.


text:
Q: Help with the posterior of a uniform distribution with a parameter that is uniformly distributed Here is the question:

My main issue is with the marginal distribution of θ, I know that the sampling distribution is 1/(θ^n), but what interval do we integrate on, it can't be [0, 1] because that would give an error with 1/0, but I can't figure it out.

A: Your statement of the sampling density is incorrect, since it does not take account of the bounds of the distribution.  (This is a common error for novices working with problems involving bounded distributions.  You will find the same error in many questions involving the uniform distribution on this site.)  Taking account of the bounds of the distribution, the correct sampling density is:
$$\begin{aligned}
p(\mathbf{x}_n|\theta)
&= \prod_{i=1}^n p(x_i|\theta) \\[6pt]
&= \prod_{i=1}^n \frac{\mathbb{I}(0 \leqslant x_i \leqslant \theta)}{\theta} \\[6pt]
&= \frac{\mathbb{I}(0 \leqslant x_{(1)} \leqslant x_{(n)} \leqslant \theta)}{\theta^n}. \\[6pt]
\end{aligned}$$
(In this equation I have used the standard notation for order statistics.)  So, assuming you have a valid sample (i.e., with $0 \leqslant x_{(1)} \leqslant x_{(n)} \leqslant 1$) you should get the posterior density kernel:
$$\begin{aligned}
\pi(\theta|\mathbf{x}_n)
&\propto p(\mathbf{x}_n|\theta) \cdot \pi(\theta) \\[12pt]
&\propto \frac{\theta \geqslant x_{(n)}}{\theta^n} \cdot \mathbb{I}(0 \leqslant \theta \leqslant 1) \\[6pt]
&\propto \frac{1}{\theta^n} \cdot \mathbb{I}(x_{(n)} \leqslant \theta \leqslant 1). \\[6pt]
\end{aligned}$$
The corresponding posterior density is obtained by finding the normalising constant by integrating the density kernel over its range.  Observe that the posterior density has support on the interval $x_{(n)} \leqslant \theta \leqslant 1$, which is the appropriate range ensuring that all the observed data are no greater than $\theta$.


text:
Q: Reverse engineering error during migration of SqLite to MySql using MySql workbench I am migrating an SQLite database to MySql using the MySQL workbench migration wizard (Community Edition).  I have downloaded the ODBC drivers for SQLite.  I am able to connect to SQLite and retrieve the schema (See Figure One).
However, an error is produced during the reverse engineering phase of migration (See Figure Two). In this example the error reads "ERROR: Line 1: syntax error, unexpected TEXT_STRING. Statement skipped."  Because reverse engineering terminated with errors the schema is not reverse engineered.
Does anyone know how to resolve the issue?
Thank you,
Camille
Figure One.

Figure Two.

A: In my experience, Workbench used to be quite buggy, and probably this is a bug too. In case no-one answers with a real solution, I suggest you look at this SO question:
Quick easy way to migrate SQLite3 to MySQL?
I'm only afraid it might not be that quick and easy. Most methods revolve around dumping your SQLite database to an SQL script, converting the script to MySQL syntax and importing/executing it in MySQL.

A: From what I just experienced, that kind of error will happen if the syntax from the database file in entry (here SQLite) isn't compatible with MySQL. In my case, it was reporting "syntax error, unexpected IDENT_QUOTED, expecting ')'" when facing the word "autoincrement" (which doesn't exist in MySQL syntax).
A way to do your migration would be to dump your SQLite DB in a .sql script, modify it to respect MySQL's syntax and import it in MySQL.
See Shalmanese's answer here https://stackoverflow.com/a/87531/1324798 for a list of differences between syntaxes and a script to convert it.
Sadly, I don't know if there is still a way to use Workbench's migration wizard with this kind of problem.
Good luck.


text:
Q: Prove that a solution for non homogeneous equation is bounded Consider $$x'=Ax+g(t)$$
for some $g(t):\mathbb{R} \rightarrow \mathbb{R}^n.$ Assume that $A$ is hyperbolic i.e it has no eigenvalues on the imaginary axis. Assume that $g(t)$ is uniformally continuous and bounded. Verify that $$x(t)=e^{At}P_sv+\int_0^te^{A(t-\tau)}P_sg(\tau)d \tau-\int_0^{\infty} e^{A(t- \tau)}P_u g(\tau) d\tau$$
is a sulotion for any $v \in \mathbb{R}^n.$ What is the initial condition? and prove that the solution is bounded.
I differentiate $x(t)$ but still having a problem with show it equals to $Ax+g(t)$, what I have is $$ x'(t)=Ae^{At}P_sv+e^{A(t-\tau)}P_sg(t)+\int_0^tAe^{A(t-\tau)}P_sg(\tau)d \tau-\int_0^{\infty} Ae^{A(t- \tau)}P_u g(\tau) d\tau- e^{A{(t-\tau)}}P_u g(t) $$
$$=A[e^{At}P_sv+\int_0^te^{A(t-\tau)}P_sg(\tau)d \tau-\int_0^{\infty} Ae^{A(t- \tau)}P_u g(\tau) d\tau]+g(t)[e^{A(t-\tau)}P_s -e^{A{(t-\tau)}}P_u]=Ax+g(t)[e^{A(t-\tau)}P_s -e^{A{(t-\tau)}}P_u]$$
I am getting stuck here. Also in the part of showing that is actually bounded
I would appreciate any help!


text:
Q: Electrostatic Potential of a Hollow sphere When calculating the electric potential inside the hollow portion why are we adding all the electric potentials of the previous cases??? Instead when calculating for other cases i.e the cases before this hollow portion case we only consider the electric potential of that case only.
See the image for more clearer meaning.....
Also please note that only one charge +q is present inside the conducting hollow sphere.

A: The space inside a hollow sphere of radius $\:R\:$ with charge $\:Q\:$ uniformly distributed on its surface [surface charge density $\:\sigma=Q/(4\pi R^2\:$)]  is an equipotential region. That is with your choice of $\:V=0\:$ as $\:r\longrightarrow \infty\:$ the potential is $\:V_{inside}=0\:$. The potential outside is that of a point charge $\:Q\:$ positioned at the center of the sphere
\begin{equation}
   V=
   \begin{cases}
   \hphantom{\dfrac{1}{4\pi}}0 & \text{for}\quad r<R\\
   \dfrac{1}{4\pi \epsilon_{0}}\dfrac{Q}{r} & \text{for}\quad r\ge R
   \end{cases}
  \tag{01}
\end{equation}

Related : see my answer as user82794 (former diracpaul) here Would you be weightless at the center of the Earth?

A: Outside the shell, at a distance $r>b$, the potential $V(r)$ would be:
$$ V(r)= \frac{kq}{r} + \frac{k(-q)}{r} + \frac{kq}{r} $$
The first term in the above expression corresponds to the potential due to point charge, the second corresponds to potential due to charges induced on the inner surface of the conductor and the third term corresponds to the potential due to the charges induced on the outer surface of the conductor, all at a distance $r \geq b$ from the centre. As we see that the potential due to point charge and charges induced on the inner surface are equal and opposite, we need not mention them separately in the expression for $V(r)$ as they cancel out.
That's what the solution intends to convey for potential $V(r)$ for $a \leq r < b$ and $r<a$ too.
P.S. $k= \frac{1}{4πε₀}$


text:
Q: Pandas change the dataframe shape column values to row I have a dataframe which is looking as below
df
     school1    game1   game2   game3
     school2    game1
     school3    game2   game3
     school4            game2

output
       game1    school1 school2
       game2    school1 school4 school3
       game3    school1         school3

can any one suggest me how can I get the out put i am new to pandas please help me
Thank you

A: Here is one way that relies on the melt() method to first make a long table out of the original and then on the pivot() method to transform it to the new wide format:
import pandas as pd
import numpy as np

# Code that creates your input dataframe (replace column names as needed)
df = pd.DataFrame(
    {'school':['school1', 'school2', 'school3', 'school4'],
     'g1':['game1', 'game1', 'game2', None],
     'g2':['game2', None, 'game3', 'game2'],
     'g3':['game3', None, None, None],
    }
)

# Convert to long format (one row per school-game)
long_df = df.set_index('school').melt(ignore_index=False).reset_index()
# Remove null (non-existing) school-game combinations
# Also, convert index to column for next step
long_df = long_df[long_df.value.notnull()].reset_index(drop=True).reset_index()

# Convert to dataframe with one row per game ID
by_game_df = long_df.pivot(index='value',columns='index',values='school')

At this point, the dataframe will look like this:
index  value        0        1        2        3        4        5        6
0      game1  school1  school2      NaN      NaN      NaN      NaN      NaN
1      game2      NaN      NaN  school3  school1      NaN  school4      NaN
2      game3      NaN      NaN      NaN      NaN  school3      NaN  school1

You can perform these additional steps to shift non-null school values to the left and to remove columns with only NaN's remaining:
# per https://stackoverflow.com/a/65596853:
idx = pd.isnull(by_game_df.values).argsort(axis=1)
squeezed_df = pd.DataFrame(
    by_game_df.values[np.arange(by_game_df.shape[0])[:,None], idx],
    index=by_game_df.index,
    columns=by_game_df.columns
)
result = squeezed_df.dropna(axis=1, how='all')
result
# index  value        0        1        2
# 0      game1  school1  school2      NaN
# 1      game2  school3  school1  school4
# 2      game3  school3  school1      NaN

A: Or with a Series of lists and a much maligned loop:
d = {'School': ['s1','s2','s3','s4'], 'c1': ['g1','g1','g2',np.nan], 'c2': ['g2',np.nan,'g3','g2'], 'c3': ['g3',np.nan,np.nan,np.nan]}
df = pd.DataFrame(d)
df

  School   c1   c2   c3
0     s1   g1   g2   g3
1     s2   g1  NaN  NaN
2     s3   g2   g3  NaN
3     s4  NaN   g2  NaN

gg = pd.Series(dtype=object)

def add_gs(game, sch):
    if type(game) is str:
        if game in gg.keys():
            gg[game] += [sch]
        else:
            gg[game] = [sch]

cols = df.filter(regex='c[0-9]').columns

for i in range(len(df)):
    for col in cols:
        add_gs(df.loc[i,col],df.loc[i,'School'])

gg

g1        [s1, s2]
g2    [s1, s3, s4]
g3        [s1, s3]

A: A solution that relies on defaultdict() for reshaping the data:
from collections import defaultdict
import pandas as pd

# Code that creates your input dataframe (replace column names as needed)
df = pd.DataFrame(
    {'school':['school1', 'school2', 'school3', 'school4'],
     'g1':['game1', 'game1', 'game2', None],
     'g2':['game2', None, 'game3', 'game2'],
     'g3':['game3', None, None, None],
    }
)

# convert df to dictionary
d = df.set_index('school').to_dict(orient='index')

# reshape the dictionary
def_d = defaultdict(list)
for k, v in d.items():
    for i in v.values():
        if i is not None:
            def_d[i].append(k)
d_rs = dict(def_d)

# prepare dictionary for converting back to dataframe
dict_for_df = {
    k: pd.Series(
        v + [None] * (len(max(d_rs.values(), key=lambda x: len(x))) - len(v))
    ) for k, v in d_rs.items()
}

# convert dictionary to dataframe
final_df = pd.DataFrame.from_dict(dict_for_df, orient='index')
}
#              0        1        2
# game1  school1  school2     None
# game2  school1  school3  school4
# game3  school1  school3     None


text:
Q: How to skip nextLinks during initailization of delta query Is there any way to skip processing nextLinks after the initialization of delta query for AD. Paging through it takes to much time and all I need is delta link.

A: You can use $deltaToken=latest and the response will contain a @odata.deltaLink.
See here.


text:
Q: xrdp - auto join session I have an xrdp setup on my raspberry pi.
XRDP:

I only have one session in the list (PI).
Is it possible to skip this screen and go directly to the remote control after connecting?
Thanks

A: For anyone dealing with this, I'd try saving the configuration on your RDP client. For Windows RDP go to "Options" on the bottom left, and then under "General" enter your specifications. In this case, leave the username and password blank and make sure to save it. From then on those credentials will be used to auto login.
For other clients like Royal TS, right-click on the connection and open the "Properties" dialog. Going to "Credentials" located on the left navigation bar will allow you to save any log in configurations you want to use.
I've never tried this without a username and password, so if it doesn't work with blank configurations, I'd consider setting up a username and password if you want to bypass this page.


text:
Q: How do I convert ushort to short in C#? One version is
short value = unchecked((short)0x8010);

Other versions like below will not work, and will throw an exceptions
short value = Convert.ToInt16(0x8010);
short value = (short)(0x8010);

Is there any other version without unchecked keyword?
Updated: expected is negative value of -32752

A: What do you expect value to be?
0x8010 = 32784
The range of a short is -32768 to 32767 so the value 32784 cannot be expressed by a short. A short stored as 0x8010 will be interpreted as a negative number. Is it that negative number you want?
According to another SO question C#, hexadecimal notation and signed integers the unsafe keyword must be used in this case in C# if you want it to be interpreted as a negative number.

A: The following will work to convert all ushort values which fit into short and replace all values which don't with short.MaxValue.  This is lossy conversion though.
ushort source = ...;
short value = source > (ushort)short.MaxValue
  ? short.MaxValue
  : (short)source;

If you are looking for a straight bit conversion you can do the following (but I wouldn't recommend it)
[StructLayout(LayoutKind.Explicit)]
struct EvilConverter
{
    [FieldOffset(0)] short ShortValue;
    [FieldOffset(0)] ushort UShortValue;

    public static short Convert(ushort source)
    {
        var converter = new EvilConverter();
        converter.UShortValue = source;
        return converter.ShortValue;
    }
}

A: I would suggest:
ushort input;
short output;
output = short.Parse(input.ToString("X"), NumberStyles.HexNumber));


text:
Q: Group and Aggregate with LINQ I have a timesheet entries as below
ActivityCode : Duration

*

*Project A: 12h:31mins

*Project B: 00h:10mins

*Project A: 01h:10mins

*Project A: 12h:31mins

*Project C: 12h:31mins

*Project B: 00h:10mins

*Project B: 01h:10mins

*Project A: 12h:31mins

What is the correct way to group the projects and aggregate their total time spent? i'm trying the below
    var summary = from entry in DbSet
                  where entry.Timesheet.UserID == userid &&
                  entry.Timesheet.DateSubmitted >= startdate &&
                  entry.Timesheet.DateSubmitted <= enddate
                  group entry by entry.ActivityCode.ActivityCode1
                      into groupEntry
                      select new TimeSheetSummary()
                      {
                          ActivityCode = groupEntry.Key,
                          HourSpent = Convert.ToInt32(groupEntry.Sum(x => x.Duration)),
                          Percentage = (Convert.ToInt32(groupEntry.Sum(x => x.Duration)) / 8) * 100,
                          MinuteSpent = Convert.ToInt32(groupEntry.Sum(x => x.Duration)) * 60,
                      };

A: If you want to get a percentage, get a count of the number of activites and use that to divide by.
Not sure if you will need a divide by 0 check here.  I'm not sure what the second LINQ will do if there's no data to begin with.  Not sure if that would raise an error or not.
Int32 numberOfProjects = (from entry in DbSet
              where entry.Timesheet.UserID == userid &&
                  entry.Timesheet.DateSubmitted >= startdate &&
                  entry.Timesheet.DateSubmitted <= enddate
              select entry.ActivityCode.ActivityCode1).Distinct().Count();

var summary = from entry in DbSet
              where entry.Timesheet.UserID == userid &&
              entry.Timesheet.DateSubmitted >= startdate &&
              entry.Timesheet.DateSubmitted <= enddate
              group entry by entry.ActivityCode.ActivityCode1
                  into groupEntry
                  select new TimeSheetSummary()
                  {
                      ActivityCode = groupEntry.Key,
                      HourSpent = Convert.ToInt32(groupEntry.Sum(x => x.Duration)),
                      Percentage = (Convert.ToInt32(groupEntry.Sum(x => x.Duration)) / numberOfProjects) * 100,
                      MinuteSpent = Convert.ToInt32(groupEntry.Sum(x => x.Duration)) * 60,
                  };

A: Here's what i found as answer based on the inputs by others in the thread. thanks!
    var groupEntries = from entry in DbSet
                       where entry.Timesheet.UserID == userId &&
                             entry.Timesheet.TimeSheetDate <= endDate.Date &&
                             entry.Timesheet.TimeSheetDate >= startDate.Date
                       group entry by entry.ActivityCode
                           into groupEntry
                           select new
                           {
                               ActivityCode = groupEntry.Key,
                               Duration = Convert.ToInt16(groupEntry.Sum(r => r.Duration))
                           };

    var totalDuration = groupEntries.Sum(r => r.Duration);

    var result = from groupEntry in groupEntries
                 select new TimeSheetSummary()
                            {
                                ActivityCode = groupEntry.ActivityCode,
                                HourSpent = groupEntry.Duration / 60,
                                MinuteSpent = groupEntry.Duration % 60,
                                Percentage = groupEntry.Duration / totalDuration * 100
                            };


text:
Q: Detect how many elements have changed in JSON array with jQuery I'm very new to web development, so this may seem trivial to you:
I'm building a wall that displays a mosaic of 100 miniatures of landscape pictures. I get the URLs of these pictures from a remote JSON which only contains the 100 latest uploaded pictures, starting from the most recent. That JSON is constantly updated.
JSON structure :
[
{
    "name": "Blue Mountains",
    "url": "http://foo.com/url-to-picture", // <- Most recent
    "location": "Canada"
},
{
    "name": "Yellow Lake",
    "url": "http://foo.com/url-to-picture", // <- Second most recent
    "location": "Greece"
}, ...
]

I'd like to check the JSON every 10 seconds and detect if new pictures have been uploaded and, if so, I'd like to know how many and then replace the oldest pictures from the wall by the new ones.
All I could really come up with is this:
function getNewPictures() {
    $.getJSON("http://bar.com/url-to-json", function(result) {
        latest100 = result;
        checkIfNewPictures(); // I don't know how to do this
        old100 = latest100;
    });
}

setInterval(getNewPictures, 10000);

As you can see, I have no clue as to how I could compare old100 and latest100. I also suppose it'd be easier for me if I could store the X new pictures into another array so that the process of updating the wall would be easier.
What would be the most practical way to achieve this?
Thanks!

A: There are a few ways to go about it, but here is how I would do it.
It appears that the data structure you are working with does not contain a unique identifier for each picture. You will need a way to uniquely identify each picture, so you will have to create something.
Say you are outputting the images initially like this:
$.getJSON("http://bar.com/url-to-json", function(result) {
    $.each(result, function(index, picture) {
        $('.wrapper').append("");
    });
});

You will also need to give each element a unique identifier so that it can be referred to.
    ...
    $.each(result, function(index, picture) {
        var pictureID = picture.name + 'something' + picture.location;
        pictureID = pictureID.replace(' ','');
        $('wrapper').append("");
    });
    ...

Here is a function to remove the images that are not in the latest json.
function removeImages(json) {
    var newImageIDs = [];
    $.each(json, function(index, picture) {
        //make an array of all the new image ID's
        var pictureID = picture.name + 'something' + picture.location;
        pictureID.replace(' ','');
        newImageIDs.push(pictureID);
    });

    $('.json-image').each(function() {
        if ( newImageIDs.indexOf($(this).attr('id')) < 0 ) {
            //this image is no longer in the json, remove it
            $(this).remove();
        }
    });
}

Now, when you get the latest JSON you can add the new ones and remove ones that no longer exist.
$.getJSON("http://bar.com/url-to-json", function (result) {
    $.each(result, function (index, picture) {
        var pictureID = encodeURIComponent(picture.name + 'something' + picture.location);
        //only add new images
        if ( !$('#' + pictureID).length ) {
            $('.wrapper').append("");
        }
    });
    removeImages(result);
});


text:
Q: Inserting HTML with PHP does not work on JavaScript When inserting HTML code with PHP the ";

Is my syntax wrong or is later inserted JavaScript just not being executed?
Thanks a lot!

A: your javascript does not know about the signalframe1 element, because this runtime (later added) javascript only knows about the html added with this php script, for that you can add one copy of the script in the html page so that its present when the html is loaded, and the other in php if you need bcz later if you want to add some html there in the php and that should work on that html doc. hope it will help. Thanks


text:
Q: Set ContentView and inflater in android please can anybody tell the basic difference between the following

setContentView(R.layout.content_main);

and

View row = layoutInflater.inflate(R.layout.view, parent, false);

from the above two method we get the view , and i know the second method generally use in Adapter to inflate the view.
But My question is ---

Can we use setContentView method in place of inflator to get the views in adapters... i am confused please help me out????

A: public void setContentView (View view): Is only used for setting the Activity content to an explicit view.
public View inflate (int resource, ViewGroup root, boolean attachToRoot):
Used for inflating a new view hierarchy from the specified xml resource.
You can't use setContentView(View view) in Adapter, it's exclusively available for Activity.

A: LayoutInflator class is used to instantiate layout XML file into its corresponding View objects.
In other words, it takes as input an XML file and builds the View objects from it.
whereas setContentView() is an Activity method only. Each Activity is provided with a FrameLayout with id "@+id/content" (i.e. the content view). Whatever view you specify in setContentView will be the view for that Activity. Note that you can also pass an instance of a view to this method, e.g. setContentView(new WebView(this)); The version of the method that you are using will inflate the view for you behind the scenes.
For further info, consider reading:

*

*this

*this

*this

A: Each Activity is provided with a FrameLayout with id "@+id/content" (i.e. the content view).setContentView is an Activity method only.Whatever view you specify in setContentView will be the view for that Activity.Fragments, on the other hand, have a lifecycle method called onCreateView which returns a view (if it has a view). The most common way to do this is to inflate a view in XML and return it in this method. In this case you need to inflate it yourself though. Fragments don't have a "setContentView" method
LayoutInflater.inflate just inflates and returns a view (you can use this anywhere). You still need to set that view as the content view within an Activity.

A: every activity is shown to the user by its relevant view
otherwise we cant see theme on the screen
so every activity needs a view to be displayed with
setContentView() is a method defined in activity class and is used to define a view for the activity and nothing more
but an inflater is a way to grab a view from xml file
after we get the view from the xml file with inflaters we can use them anywhere
for example in OnCreateOptionsMenu() we should get the view from the xml file with inflaters


text:
Q: Error: The Component for route 'HomeScreen' must be a React Component while using Redux connect() I'm Getting this error - "The Component for route 'HomeScreen' must be a React Component while using Redux connect()" while applying Redux connect() and while removing connect() the app works fine in react native.
Below I have mentioned the code:
import React, { Component, Fragment } from 'react';
import { View, Text } from 'react-native';
import {connect} from 'react-redux';

class Sample extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            dataSource: {}
        };
    }
    render() {
        return (
            <View>
                <Text>Hi</Text>
            </View>
        )
    }
}

const container = connect()(Sample);
export default container;

Also I have tried to downgrade React Redux version from 7.0.1 to 6.0.1, But still I'm facing the same issue.
Also I have tried the Solution, but still the problem exists.

A: Finally, I solved my problem by downgrading react-redux from 7.0.2 to 5.1.1, the problem is that in react-redux 7.0.2 connect() method returns object but in react-navigation 2.18.2 it assumed to be function I guess, so there is a type mismatch, therefore I have to downgrade react-redux to 5.1.1.


text:
Q: Div will not sit above Jquery slider I have a simple basic JQuery image slider which works great but I am trying to place a div over the top. Now it works if I place the div to each slide but I wish to have one div sitting there while the images fade in to the next.

        <?php include("profileuserdata.php"); ?>

Change

Upload File

From Your Folio...

The reason it cannot be applied to each slide is because the div I am overlaying contains user data which can be edited on the fly by the user but if the div is sitting on a slide when it moves to the next image the edit box will only show when it comes back around to that slide...
I have used z-index and can see the div underneath the sliding images when it fades out here is the css for the slider:


text:
Q: Move Vertical annotation only across datapoints I have a chart with many datapoints and a vertical annotation. I want the vertical annotation to be moved only from datapoint to datapoint and not between them.
I have written this in order to set the Vertical annotation :
 VA.X = chart1.Series[0].Points[0].XValue;
            VA.AllowMoving = true;
            VA.IsInfinitive = true;
            VA.AnchorDataPoint = chart1.Series[0].Points[0];
            VA.LineColor = Color.Red;
            VA.LineWidth = 2;
            VA.LineDashStyle = ChartDashStyle.Solid;

and this is how the Vertical annotation gets its values
 private void chart1_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e)
{

   var pt1 = (int)VA.X;
    int i = 0;

        foreach (var signal in Signals)
        {
            valtot = signal.Points[pt1].YValues[0];

            i++;
        }

How could I just move from one datapoint to another? I don't want the values between the datapoints and therefore the VA should not be able to be placed only on datapoints.
EDIT :
Here is a picture of what I want to achieve.

the little blue circles represent datapoints. I want my red line to move only across these little blue circles and not in the area between them.


text:
Q: How do I make the guards in Markarth stop being hostile? I killed some Imperial Soldiers in the Reach far away from the city, then ported back to Markarth via fast travel. I have no bounty in the Reach, I checked, but all the guards and NPCs in the city either run or attack me on sight. Nobody ever confronted me about having a bounty even when I sheathed my weapon repeatedly.
I tried to run away to get them to stop, but that only ended with me standing a long ways outside the city with 20+ guards, thalmor, and the jarl, his housecarl, and his steward all attacking me. I used "setbountygold" (or whatever that command is) and it did nothing. I tried stealing cabbages, but I never got any bounty notifications.
What is going on and how can I stop the guards being hostile?

A: Try killing a chicken in one of the farms. Killing a chicken is considered a crime. They are considered NPC owned in the farm that you find them. Killing one chicken will net you a small bounty, which you can payoff and it should reset this for you.
Usually this has worked for me. If this does not work, the only option is to reload a prior save game.

A: You could use the console code TCAI to toggle everybody's ability to fight, but that's probably not what you want. Calm spells are another temporary solution. Other than that, have you tried waiting 30 days away from the Reach and coming back? A more random thing to try would be stealing something cheap in Markarth, then paying the bounty (find a bounty hunter if the guards continue to ignore your yielding). If that doesn't work, you just might have to reload to the previous save.


text:
Q: Time difference between callings of a method One part of my program calls a certain method several times.
How can this method track the time between each time it is called?
I thought to use some global variables:
var lastTime = ?;
var currentTime = ?;
var elapsedTime = ?;

public DoSomething()
{
    currentTime = TimeRightNowInSeconds;
    elapsedTime = currentTime - lastTime;
    // do stuff with elapsedTime...
    lastTime = TimeRightNowInSeconds;
}

but I have no idea how I measure the time in seconds.

A: Consider using DateTime and TimeSpan (Be careful to use DateTime.UtcNow to avoid issues with daylight saving boundaries)
e.g.
var start = DateTime.UtcNow;
...
var end = DateTime.UtcNow;
var elapsed = end.Subtract(start); //elapsed is a TimeSpan
var elapsedSeconds = elsapsed.Seconds;

This can also be done with a Stopwatch (which is more accurate and doesn't suffer from problems with daylight saving boundaries)
var stopwatch = Stopwatch.StartNew();
...
stopwatch.Stop();
var elapsedSeconds = stopwatch.Elapsed.Seconds; //stopwatch.Elapsed is a TimeSpan

A: In this solution you will see how to get the time between the method call
Link
class Program
{
  static Stopwatch _stopWatch = new Stopwatch(); // stopwatch
  static long  _lastTime; // time in milliseconds

  static void Main(string[] args)
  {
     /* _lastTime will be 0 when first call ElapsedTime(). */
     ElapsedTime();

     /* Hold the current thread for 1000 milliseconds */
     Thread.Sleep(1000);

     /* _lastTime will be 1000  when second call ElapsedTime(). */
     ElapsedTime();
     Thread.Sleep(2000);

     /* _lastTime will be 3000 when third call ElapsedTime(). */
     ElapsedTime();

     /* Thread.Sleep() is to simulate time between the calls of the method */
     /* _lastTime is in milliseconds*/
   }

   public static void ElapsedTime()
   {
     // check if stopwatch already started once
     if (_stopWatch .IsRunning)
     {
         /* get the totlal elapsed milliseconds */
         _lastTime += _stopWatch .ElapsedMilliseconds;
         /* Restart stopwatch */
         _stopWatch .Restart();
      }
      else
      {
        _stopWatch .Start();
      }

     Console.WriteLine(_lastTime);
   }
}


text:
Q: Does Silex support custom user roles I been playing with Silex for the past few weeks and I'm about to start a major stepping stone. Authentication has always caused me some trouble.
I been looking at documentations / examples for the past few days and I can't seem to find any answers to what I am seeking.
I can tell Silex supports ROLE_ADMIN and ROLE_USER but I don't see any ROLE_SUPER_ADMIN. Is it possible to modify the user provider/interface to handle this extra role and if so where could I find the proper documentation for it.

A: I believe that roles are "mostly" arbitrary in that you can define whatever role you want (like: ROLE_AWESOME_USER, etc...) but ROLE_USER and ROLE_ADMIN seem to be referenced in Symfony tests as well as the core UserInterface.php class.
The Silex documentation covering security should have most of what you need. There is also a pretty good example of a firewall setup in this so question here
Here is my default firewall config at current:
'security.firewalls' => array(
    'main' => array(
        'pattern' => '^/',
        'anonymous' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/login_check',
            'username_parameter' => 'form[username]',
            'password_parameter' => 'form[password]',
            'form_login' => array(
                'csrf_provider' => 'form.csrf_provider',
            ),
        ),
        'logout' => array('logout_path' => '/logout'),
        'users' => array(
            'username' => array(
                '%security.role%',
                '%security.password%',
            ),
        ),
    ),
),
'security.role_hierarchy' => array(
    'ROLE_USER' => array(),
    'ROLE_ADMIN' => array('ROLE_USER'),
    'ROLE_SUPER_ADMIN' => array('ROLE_USER','ROLE_ADMIN','ROLE_ALLOWED_TO_SWITCH'),
),
'security.access_rules' => array(
    array('^/user', 'ROLE_USER'),
    array('^/admin', 'ROLE_ADMIN'),
    array('^/root', 'ROLE_SUPER_ADMIN'),
),


text:
Q: asp mvc partial view model binding I've this data model
public partial class UsersInfo
{
    public int UserID { get; set; }
    public string Name_f { get; set; }
    public string Name_l { get; set; }
    public string Photo { get; set; }
    public bool ActiveAccount { get; set; }
}

public partial class Employee
{
    public int EmpID { get; set; }
    public int BranchID { get; set; }
    public virtual UsersInfo UsersInfo { get; set; }
}

and i'm rendering this form
@model LoanApp.Models.DataBaseModel.Employee
@using (Html.BeginForm((string)ViewBag.Contoler, "Employe", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.Partial("~/Views/Shared/_userInfo.cshtml",Model.UsersInfo)
    <label class="control-label">يعمل في فــرع</label>
    @Html.DropDownList("BranchID", null, htmlAttributes: new { @class = "form-control" })
    <input type="submit" value="Save" class="btn btn default" />
}

and this is my partial view
@model LoanApp.Models.DataBaseModel.UsersInfo
@Html.TextBoxFor(x => x.Name_f, new { @class = "form-control", @placeholder = "الاسم الاول", @required = "" })
@Html.TextBoxFor(x => x.Name_l, new { @class = "form-control", @placeholder = "الاسم الاخير", @required = "" })
@Html.TextBoxFor(x => x.PhoneNumber, new { @class = "form-control", @required = "", @number = "true" })

I want my post edit method to has the object from userinfo instead of null, I'm not sure what i'm missing
I've one to one relation between table employee and users info
enter image description here

A: The problem is your post method [Bind(Include = "some property")]. Which means you specified the list of properties only included in the model object, Other properties are not included in the model object.


text:
Q: Is there a way to visualise a query in a kanban style board view? In my organization, our Azure DevOps setup has individual projects for individual areas. We have several areas in the 'digital' space and we need to be able to track activity and prioritize across these projects together.
So far we've managed to set up cross-project queries which are working reasonably well, but we want to visualize the work items in a kanban style board.
I've found an extension that shows a query in a board view but it hasn't been updated for some time and doesn't fully solve our issue (it's not listing the cards in priority order). https://marketplace.visualstudio.com/items?itemName=realdolmen.querybasedboards
Is there another option?
Thanks
Callum


text:
Q: Trying to display the registered name in my home screen Hi so I have an application where the person registers himself and gets taken to the home screen where I have a flatlist of everyone who has registered. I want to make it so that it can display the users name who has signed in on the home screen like Welcome {user}. I am still a beginner so any help would be useful. Here is my code:-
Sign Up Screen:-
function SignupScreen(props) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');

  const sendCred = async (props) => {
    fetch('http://10.0.0.2/signup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email,
        password: password,
        name: name,
      }),
    })
      .then((res) => res.json())
      .then(async (data) => {
        try {
          await AsyncStorage.setItem('token', data.token);
          props.navigation.navigate('Home');
        } catch (e) {
          console.log('error', e);
        }
      });
  };
  return (
        <TextInput
          label="Email"
          mode="outlined"
          value={email}
          style={{ marginLeft: 18, marginRight: 18, marginTop: 18 }}
          theme={{ colors: { primary: 'blue' } }}
          onChangeText={(text) => setEmail(text)}
        />
        <TextInput
          label="password"
          mode="outlined"
          secureTextEntry={true}
          value={password}
          onChangeText={(text) => {
            setPassword(text);
          }}
          style={{ marginLeft: 18, marginRight: 18, marginTop: 18 }}
          theme={{ colors: { primary: 'blue' } }}
        />
        <TextInput
          label="Name"
          value={name}
          mode="outlined"
          onChangeText={(text) => setName(text)}
          style={{ marginLeft: 18, marginRight: 18, marginTop: 18 }}
          theme={{ colors: { primary: 'blue' } }}
        />
);
}

Home Screen:-
function HomeScreen({ navigation }) {
  const [data, setData] = useState([]);
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(true);

  const fetchData = () => {
    fetch('http://10.0.0.2/')
      .then((res) => res.json())
      .then((results) => {
        setData(results);
        setName(results.name);
        setLoading(false);

      })
      .catch((err) => {
        Alert.alert('something went wrong in HomeScreen_fetchData()');
      });
  };

  useEffect(() => {
    fetchData();
  }, []);

  const renderList = (item) => {
    return (
      <Card
        style={styles.mycard}
        onPress={() => navigation.navigate('Profile', { item })}>
        <View style={styles.cardView}>
          <Image
            style={{ width: 60, height: 60, borderRadius: 50 / 2 }}
            source={{
              uri: item.picture,
            }}
          />
          <View style={{ marginLeft: 10 }}>
            <Text style={styles.text}>{item.name}</Text>
            <Text>{item.position}</Text>
          </View>
        </View>
      </Card>
    );
  };

  return (
      <CustomHeader title="Home" />
      <View style={{ flex: 1 }}>

        <Text>Your name is {name}</Text>

        <FlatList
          data={data}
          renderItem={({ item }) => {
            return renderList(item);
          }}
          keyExtractor={(item) => item._id}
          onRefresh={() => fetchData()}
          refreshing={loading}
        />
      </View>
  );
}

A: Try this way
const sendCred = async (props) => {
    ...........
      .then(async (data) => {
        try {
          // expect "data.user" is an object contain user related data like "name" etc ...
          await AsyncStorage.setItem('user', JSON.stringify(data.user) ); // store user here
          props.navigation.navigate('Home');
        } catch (e) {
          console.log('error', e);
        }
      });
  };

Home Screen:-
function HomeScreen({ navigation }) {
  .........
  const [user, setUser] = useState({}); // new add

  const getUser = async () => {
    try {
          const data = await AsyncStorage.getItem('user'); // get user here
          setUser(JSON.parse(data) );
        } catch (e) {
          console.log('error', e);
        }
  };

  useEffect(() => {
    getUser();
  }, []);

  return (
      <View style={{ flex: 1 }}>

        <Text>Welcome {user && user.name ? user.name : ""}</Text> // expect user object has "name" property

        .....
      </View>
  );
}

A: This will work only if you have a jwt token
Once you did that (we assume that you had stored the user in the token):
.then(async (data) => {
    try {
      await AsyncStorage.setItem('token', data.token);
      props.navigation.navigate('Home');

You can create a file that will return the current user (e.g. Service/auth.service.js), we use jwt-decode (you need to import from nmpjs) that will decode the token :
/**
* Return current user
*/
const getCurrentUser = () => {
    const token = localStorage.getItem("token");
    return jwtDecode(token);
};

export default {getCurrentUser}

You can then import it into your Home component like this :
import AuthService from "hereThePath/Services/auth.service"

const user = AuthService.getCurrentUser();
console.log(`this is the user name ${user.name}`);


text:
Q: Iterate over DataGrid How can I iterate over a WPF DataGrid "as seen by the user" (e.g. the user might have sorted it or the user might have rearranged columns).
When I iterate using ItemsSource
foreach (System.Data.DataRowView dr in ResultDataGrid.ItemsSource)
{ .. }

then I am iterating over the original, unsorted DataGrid. Thank you for any help!

A: Ensure your underlying collection reflects the visual collection.
So instead of relying on the DataGrid itself to do the sorting, for instance, sort the underlying ObservableCollection so that when you iterate through it, you are iterating in visual order.


text:
Q: Trying to change the value of a global variable, variable is undefined error in React I am new in react, and wanted to make a shopping website. I created a global array named cart, and I can read the data in it. However, when I tried to update the data in the cart array, I encountered with the error "ReferenceError: cart is not defined"
const [cartProducts, setCartProducts] = useState(cart);

const handleCartButton = () => {
    if(!cartProducts.includes({item})) // itemi içerse de buraya giriyor.
    {
        const newList = cartProducts.concat( [{item}] );
        setCartProducts(newList);
    }
    cart = cartProducts; // this is the error line
}
useEffect(()=>{
    console.log(item.name + cartProducts);
    console.log(cart);
},[cartProducts])

and this is the cart array,
export let cart = [];

I do not know how to update a global variable.

A: For global variables you should use context
// AppContext.js

import React, { useContext } from "react"

const AppContext = React.createContext()

export const AppProvider = ({
    children
}) => {
    const [cart, setCart] = useState([])

    const value = { cart, setCart }

    return <IconContext.Provider value={value}>{children}</IconContext.Provider>
}

export function useAppContext() {
    return useContext(AppContext)
}

And then use it like this (from your example):
// make sure to import useAppContext
const { cart, setCart } = useAppContext()

const handleCartButton = () => {
    if(!cart.includes({item})) {
        const newList = cart.concat( [{item}] );
        setCart(newList);
    }
}

useEffect(()=>{
    console.log(item.name + cart);
    console.log(cart);
},[cart])

And then make sure to wrap your component in AppProvider:
import React from "react"
import {AppProvider} from "./AppContext.js"

const ParentComponent = () => {
    return <AppProvider>
        <YourComponent/>
    </AppProvider>
}

You can wrap your whole application with AppProvider:
// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {AppProvider} from "./AppContext.js"

const root = ReactDOM.createRoot(
  document.getElementById('root')
);
root.render(
  <React.StrictMode>
      <AppProvider>
        <App />
      </AppProvider>
  </React.StrictMode>
);


text:
Q: How do I compile abinit on a Cray XC30? I am trying to compile the abinit code (http://www.abinit.org/) on a Cray XC30 machine (http://www.archer.ac.uk). Does anyone have a step-by-step procedure for doing this?

A: This is pretty straightforward. Instructions can be found at:
http://www.archer.ac.uk/documentation/software/abinit/compiling_7_phase2.php
and can be summarised as:

*

*Switch to the Intel programming environment (GCC works too but produces slower code)
module swap PrgEnv-cray PrgEnv-intel

*Load the FFTW and NetCDF modules
module load fftw
module load cray-netcdf

*Write a custom configuration file for autotools
prefix="/path/to/your/install/directory"

enable_mpi=yes
enable_mpi_io="yes"
enable_gw_dpc="yes"

enable_64bit_flags="yes"
enable_optim="aggressive"

CC=cc
CXX=CC

FC=ftn
FCFLAGS_EXTRA=""

with_linalg_flavor="mkl"
with_linalg_incs="-I$MKLROOT/include/intel64/lp64"
with_linalg_libs="-L$MKLROOT/lib/intel64 -lmkl_lapack95_lp64 -lmkl_blas95_lp64 -lpthread -lm"

with_fft_flavor=fftw3
with_fft_incs="-I$FFTW_INC"
with_fft_libs="-L$FFTW_DIR -lfftw3 -lfftw3f"

with_trio_flavor="netcdf"

*configure, make, make install


text:
Q: Stylize Codeigniter Helper Forms with Boostrap I've made a search form on my website using the Codeigniter form helper, but as I'm using Bootstrap for the entire website I want to stylize the form (input, and button) using it.
This is the code for the search function:
<?php echo form_open('search/cauta');
      echo form_input('element');
      echo form_submit('search_submit', 'Search');
      echo form_close();
?>

How can I make it look like a standard Bootstrap search? I'm passing 'element' to my search/cauta function in my Controller.
Thanks

A: Solved
form_input(array('name'=>'element', 'class'='yourClassName'));
you can pass other parameters the same way


text:
Q: #1451 - Cannot delete or update a parent row: a foreign key constraint fails My code SQL is :
enter code here

CREATE TABLE IF NOT EXISTS `participer` (
  `statut_Invitation` tinyint(1) NOT NULL,
  `NumVersion` int(11) NOT NULL,
  `InviteCode` varchar(255) NOT NULL,
  `IdQuest` int(11) NOT NULL,
  PRIMARY KEY (`NumVersion`,`InviteCode`,`IdQuest`),
  KEY `FK_Participer_NumVersion` (`NumVersion`),
  KEY `FK_Participer_IdQuest` (`IdQuest`),
  KEY `FK_Participer_InviteCode` (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `participer` (`statut_Invitation`, `NumVersion`, `InviteCode`, `IdQuest`) VALUES
(0, 2, '2548', 1),
(0, 2, '8742', 1);

CREATE TABLE IF NOT EXISTS `questionnaire` (
  `IdQuest` int(11) NOT NULL AUTO_INCREMENT,
  `Nom` varchar(256) DEFAULT NULL,
  `DateCreation` date DEFAULT NULL
  PRIMARY KEY (`IdQuest`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO `questionnaire` (`IdQuest`, `Nom`, `DateCreation`, `ID`) VALUES
(1, 'Parions Sport', '2015-03-23'),
(2, 'GPS', '2015-03-23');

CREATE TABLE IF NOT EXISTS `utilisateurs` (
  `InviteCode` varchar(255) NOT NULL,
  `Email` varchar(25) NOT NULL,
  `DateNaissance` date DEFAULT NULL,
  `Ville` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `utilisateurs` (`InviteCode`, `Email`, `DateNaissance`, `Ville`) VALUES
('1235314', 'bocchi@gmail.com', NULL, NULL),
('2548', 'bocchiTEST@gmail.com', NULL, NULL),
('337752493652424404824466004444846460026', 'dylan@gmail.com', NULL, NULL),
('53131172170670664482420846024208824402', 'dylan2@gmail.com', NULL, NULL),
('5446544', 'lool', NULL, NULL),
('8742', 'max@gmail.com', NULL, NULL);

-- --------------------------------------------------------

CREATE TABLE IF NOT EXISTS `versionquestionnaire` (
  `NumVersion` int(11) NOT NULL,
  `DateExpiration` date DEFAULT NULL,
  `SommeNote` float DEFAULT NULL,
  `NbReponses` int(11) DEFAULT NULL,
  `IdQuest` int(11) NOT NULL,
  PRIMARY KEY (`NumVersion`,`IdQuest`),
  KEY `FK_VersionQuestionnaire_IdQuest` (`IdQuest`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `versionquestionnaire` (`NumVersion`, `DateExpiration`, `SommeNote`, `NbReponses`, `IdQuest`) VALUES
(1, '2015-03-26', 120, 2, 1),
(1, '2015-03-30', 100, 1, 2),
(2, '2015-03-26', 210, 3, 1),
(2, '2015-03-30', 300, 4, 2);

ALTER TABLE `participer`
  ADD CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`),
  ADD CONSTRAINT `FK_Participer_InviteCode` FOREIGN KEY (`InviteCode`) REFERENCES `utilisateurs` (`InviteCode`),
  ADD CONSTRAINT `FK_Participer_NumVersion` FOREIGN KEY (`NumVersion`) REFERENCES `versionquestionnaire` (`NumVersion`);

ALTER TABLE `versionquestionnaire`
  ADD CONSTRAINT `FK_VersionQuestionnaire_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `questionnaire` (`IdQuest`);

When i want to delete the version 1 of the questionnaire 1 :
DELETE FROM `versionquestionnaire` WHERE `versionquestionnaire`.`NumVersion` = 1 AND `versionquestionnaire`.`IdQuest` = 1;

I have a error :
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`testbug`.`participer`, CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`)) ;

I don't understand because in the table participer, there isn't the couple with NumVersion = 1 and IdQuest = 1, there are 2 couples with NumVersion = 1 and IdQuest = 1. So my request may be run.

A: In short, you can't delete records from versionquestionnaire because some records in participer table reference records in participer.
Your request clearly violates IdQuest constraint: you're trying to delete a record with IdQuest = 1, while BOTH participants that still reference that ID.


text:
Q: THREE.js: Errormessage "THREE.OBJLoader is not a constructor" I am just learning the use of three.js. It seems very okay, but now I have a problem, which I can't solve.
I want to load an OBJ-file, which I created in blender before. To do that, I am trying to use the THREE.OBJloader.
I copied the code from http://mamboleoo.be/learnThree/, but I get the errormessage "THREE.OBJLoader is not a constructor" in line 32.
Everything else works fine: Adding a scene, adding a material, adding a cube, etc.
To make it easy, this is the code:
var renderer, scene, camera, banana;
var ww = window.innerWidth,
wh = window.innerHeight;

function init(){

renderer = new THREE.WebGLRenderer({canvas : document.getElementById('scene')});
renderer.setSize(ww,wh);

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera(50,ww/wh, 0.1, 10000 );
camera.position.set(0,0,500);
scene.add(camera);

//Add a light in the scene
directionalLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
directionalLight.position.set( 0, 0, 350 );
directionalLight.lookAt(new THREE.Vector3(0,0,0));
scene.add( directionalLight );

//Load the obj file
loadOBJ();
}

var loadOBJ = function(){

//Manager from ThreeJs to track a loader and its status
var manager = new THREE.LoadingManager();
//Loader for Obj from Three.js
var loader = new THREE.OBJLoader( manager );
//Launch loading of the obj file, addBananaInScene is the callback when it's ready
loader.load( 'http://mamboleoo.be/learnThree/demos/banana.obj', addBananaInScene);

};

var addBananaInScene = function(object){
banana = object;
//Move the banana in the scene
banana.rotation.x = Math.PI/2;
banana.position.y = -200;
banana.position.z = 50;
//Go through all children of the loaded object and search for a Mesh
object.traverse( function ( child ) {
    //This allow us to check if the children is an instance of the Mesh constructor
    if(child instanceof THREE.Mesh){
        child.material.color = new THREE.Color(0X00FF00);
        //Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
        child.geometry.computeVertexNormals();
    }
});
//Add the 3D object in the scene
scene.add(banana);
render();
};

var render = function () {
requestAnimationFrame(render);

//Turn the banana
banana.rotation.z += .01;

renderer.render(scene, camera);
};

init();

I hope, someone has an idea, where this might come from.
Regards, Christian

A: When you are copying from Codepen examples, always go to pen and check under the 'Settings' to see any other files which are used in the project.
In your case, the author is using OBJLoader.js and that's where OBJLoader constructor is coming from and you don't have a reference to that. Hence, you're getting the error. Include the reference and it should be working.

A: import OBJLoader
- import { OBJLoader } from './jsm/loaders/OBJLoader.js';

A: Great answer.
One thought though ... In that .js file, there is NO reference to the version, and these change like on a roller-coaster with functions being deprecated on a daily basis (.e.g. projector was ok till i think v71 or so ?)
There are many issues with backward compatibility of three.js project and a lack of an organized repository for .js files

A: you can use ObjectLoader.js
var objLoader = new THREE.ObjectLoader();

note: OBJLoader not working


text:
Q: Android EditText, soft keyboard show/hide event? Is it possible to catch the event that Soft Keyboard was shown or hidden for EditText?

A: I solved this issue by using onGlobalLayoutListener :
 final View activityRootView = findViewById(R.id.top_root);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();

                if (heightDiff > 100) {
                    // keyboard is up
                } else {
                    // keyboard is down
                }
            }
        });

Here activityRootView is your Activity's root view.

A: Hi I'd used following workaround:
As far as my content view is a subclass of LinearLayout (could be any other view or view group), I'd overridden onMeasure method lilke following:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
    final int actualHeight = getHeight();

    if (actualHeight > proposedheight){
        // Keyboard is shown
    } else {
        // Keyboard is hidden
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

This workaround helped me to hide some controls when keyboard is showing and bring back otherwise.
Hope this would be useful.

A: In my case I wanted to hide a bottom bar when softkeyboard was shown. I considered best to just hide the bar when layout had less than a percent size of normal layout size. So I used this solution that works fine considering that soft keyboard usually takes 20% or more screen height. Just change the percent constant by any value you may think is ok. It needs attribute android:windowSoftInputMode="adjustResize" in manifest and layout must be the root to work.
Extend from any layout you may want instead of RelativeLayout.
public class SoftKeyboardLsnedRelativeLayout extends RelativeLayout {
    private boolean isKeyboardShown = false;
    private List<SoftKeyboardLsner> lsners=new ArrayList<SoftKeyboardLsner>();
    private float layoutMaxH = 0f; // max measured height is considered layout normal size
    private static final float DETECT_ON_SIZE_PERCENT = 0.8f;

    public SoftKeyboardLsnedRelativeLayout(Context context) {
        super(context);
    }

    public SoftKeyboardLsnedRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("NewApi")
    public SoftKeyboardLsnedRelativeLayout(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int newH = MeasureSpec.getSize(heightMeasureSpec);
        if (newH > layoutMaxH) {
            layoutMaxH = newH;
        }
        if (layoutMaxH != 0f) {
            final float sizePercent = newH / layoutMaxH;
            if (!isKeyboardShown && sizePercent <= DETECT_ON_SIZE_PERCENT) {
                isKeyboardShown = true;
                for (final SoftKeyboardLsner lsner : lsners) {
                    lsner.onSoftKeyboardShow();
                }
            } else if (isKeyboardShown && sizePercent > DETECT_ON_SIZE_PERCENT) {
                isKeyboardShown = false;
                for (final SoftKeyboardLsner lsner : lsners) {
                    lsner.onSoftKeyboardHide();
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void addSoftKeyboardLsner(SoftKeyboardLsner lsner) {
        lsners.add(lsner);
    }

    public void removeSoftKeyboardLsner(SoftKeyboardLsner lsner) {
        lsners.remove(lsner);
    }

    // Callback
    public interface SoftKeyboardLsner {
        public void onSoftKeyboardShow();
        public void onSoftKeyboardHide();
    }
}

Example:
layout/my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<yourclasspackage.SoftKeyboardLsnedRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    ...
</yourclasspackage.SoftKeyboardLsnedRelativeLayout>

MyActivity.java
public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);
        SoftKeyboardLsnedRelativeLayout layout = (SoftKeyboardLsnedRelativeLayout) findViewById(R.id.myLayout);
        layout.addSoftKeyboardLsner(new SoftKeyboardLsner() {
            @Override
            public void onSoftKeyboardShow() {
                Log.d("SoftKeyboard", "Soft keyboard shown");
            }

            @Override
            public void onSoftKeyboardHide() {
                Log.d("SoftKeyboard", "Soft keyboard hidden");
            }
        });
    }
}

A: There actually isn't such an event to catch.  The IME is simply showing and hiding its window; the feedback you get from this is the window manager causing your own window's content to resize if you have put it in resize mode.

A: try these methods: showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver). You can override onReceiveResult(int resultCode, Bundle resultData) method of ResultReceiver class to handle show/hide event.

A: Many of Android developer like to alter the layout based on whether the virtual keyboard is shown or not.so for solution you can see Android: Detect softkeyboard open.and it is working for me and i think it is so usefull as well.

A: You can capture this by overwriting the onConfigurationChanged method of your activity:
@Override
public void onConfigurationChanged(Configuration newConfig) {
   super.onConfigurationChanged(newConfig);

   if(newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
      ((SherlockFragmentActivity)getActivity()).getSupportActionBar().hide();
   }
   else if(newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES){
      ((SherlockFragmentActivity)getActivity()).getSupportActionBar().show();
   }
}


text:
Q: Focus first focusable element below a Focus widget I am trying to focus the first focusable element below a Focus widget. Consider the following artifical example. It contains a BarWidget with some TextField.
The FooWidget wraps it into a Focus widget with the given focusNode. After one second, I'd like to focus the first element of BarWidget. Please not that I don't want to pass a FocusNode down into BarWidget.
import 'package:flutter/material.dart';

void main() {
  runApp(Foo());
}

class Foo extends StatefulWidget {
  @override
  State createState() => FooState();
}

class FooState extends State<Foo> {
  final focusNode = FocusNode();

  void initState() {
    super.initState();
    Future.delayed(
      const Duration(seconds: 1),
      focusNode.requestFocus,
    );
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          body: Focus(
            focusNode: focusNode,
            child: BarWidget(),
          ),
        ),
      );
}

class BarWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Column(
        children: [
          Text("Foo"),
          TextField(),
          Text("Bar"),
        ],
      );
}

A: It is in theory possible by using FocusTraversalPolicy.sortDescendants. However, that method is declared as @protected. See: https://github.com/flutter/flutter/issues/70534
Full example:
import 'package:flutter/material.dart';

void main() {
  runApp(Foo());
}

class Foo extends StatefulWidget {
  @override
  State createState() => FooState();
}

class FooState extends State<Foo> {
  final focusNode = FocusNode(canRequestFocus: false);

  void initState() {
    super.initState();
    void f() {
      final policy = FocusTraversalGroup.of(focusNode.context);
      // ignore: invalid_use_of_protected_member
      final node = policy.sortDescendants(focusNode.traversalDescendants, null).first;
      node.requestFocus();
    }
    Future.delayed(
      const Duration(seconds: 1),
      f,
    );
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          body: Focus(
            focusNode: focusNode,
            child: BarWidget(),
          ),
        ),
      );
}

class BarWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Column(
        children: [
          Text("Foo"),
          TextField(),
          Text("Bar"),
        ],
      );
}


text:
Q: prove the divergence How to show that the following series is divergent?
$$\sum_{n=1}^\infty \frac{4^n (n!)^2}{(2n)!}.$$
Stirling's approximation easily implies that the series is equivalent to $\sum \sqrt{n},$ hence diverges.
Can we solve it without using this result?
Thanks

A: Note that the central binomial coefficient $\binom{2n}{n}$ is the largest one in the expansion of $(1+1)^{2n}$. Hence
$$\frac{(2n)!}{(n!)^2}=\binom{2n}{n}\leq  (1+1)^{2n}=4^n\implies \frac{4^n(n!)^2}{(2n)!}\geq 1.$$

A: Yes. Recall that $$
 \frac{(2n)!}{n!^2} = \binom{2n}{n}
$$
from which
$$
\frac{(2n)!}{n!^2} \cdot \frac{1}{4^n} = \binom{2n}{n} \frac{1}{2^{2n}} = \mathbb{P}\{ X = n\} \leq 1
$$
where $X \sim\operatorname{Bin}(2n,1/2)$. This implies
$$
\frac{1}{\mathbb{P}\{ X = n\}} \geq 1
$$
leading to the divergence.

A: By Raabe's test
$$n\left(\frac{a_n}{a_{n+1}}-1\right)=n\left(\frac{4^n (n!)^2}{(2n)!}\frac{(2n+2)!}{4^{n+1} ((n+1)!)^2}-1\right)=n\left(\frac{(2n+2)(2n+1)}{4(n+1)^2}-1\right)=n\frac{4n^2+6n+2-4n^2-8n-4}{4n^2+8n+4}=\frac{-2n^2-2n}{4n^2+8n+4}\to -\frac12<1$$
thus the series diverges.

A: Hint: $(a+b)! \leq 2^{a+b} a!b!$, so $(2n)! = (n+n)! \leq 2^{n+n}n!n! = 4^n (n!)^2$.
The first inequality follows from the binomial theorem:
$$ 2^{a+b} = (1+1)^{a+b} = \sum_{k=0}^{a+b} \binom{a+b}{k} = \sum_{k=0}^{a+b} \frac{(a+b)!}{(a+b-k)!k!} \geq \frac{(a+b)!}{a!b!}, $$
where the bound in the final step follows by choosing $k=b$.


text:
Q: Implementing integration points for custom logic What is the traditional approach or best practices for integrating custom logic into a web application?  More specifically...  I am currently working on a web application targeted at paperless manufacturing.  The application architecture is as follows:
-Heavy jQuery-less JavaScript front-end using YUI
-Back-end exposed via REST API using Spring Core, Spring MVC, Spring Security
-Integration with external systems (mostly ERPs) via Spring Integration, ActiveMQ
-Currently runs exclusively on Tomcat 7, but ideally needs to be App server independent
Given the nature of manufacturing and the lack of standardization (especially small/middle market companies) almost all of our potential clients need some sort of custom logic to make our application better fit their existing processes.
What I envision looks something like custom classes that would be compiled separately and could then be dynamically loaded into the classpath, located, and called by code from the core product.  This would allow us to have a single core product which would serve as a base which we would then add "customization modules" to fulfill the specific needs of customers which are too specific to be applied to the core product.
Does that make any sense?  Is there a standard approach to achieving this?  What sort of provisions does java have for loading code outside of a war file at runtime?  Any help would be much appreciated!

A: I figured I'd answer this for the sake of anyone who runs across this.  Basically, you want to look at the plugin pattern.  If you search on that you should be able to find numerous variations of the pattern in your language of choice.


text:
Q: Device.OS in Xaml in Xamarin.Forms How to write (Device.OS == TargetPlatform.Android) in xaml,
In My class file i created like this in c#, but i don't know how to write this in xaml,
  if (Device.OS == TargetPlatform.Android)
  {
        var stack = new StackLayout()
        {
            HorizontalOptions = LayoutOptions.Center,
        };
         var label = new Label()
        {
            Content = "This design is for Android"
        };
        stack.Children.Add(label);

    };

    if (Device.OS == TargetPlatform.iOS)
    {
        var grid = new Grid()
        {
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };
        var label = new Label()
        {
            Content = "This design is for IOS"
        };
        grid.Children.Add(label);
    }

Please help me how to write this two different design in android and IOS in xaml.

A: As far as I know, this is not possible in XAML, at least not like this. Two options come to mind:
Create two pages in XAML, one for Android and one for iOS and push the right page depending on the platform, basically with the if from your code.
Or, implement something like this in one page:
<StackLayout>
    <StackLayout.IsVisible>
        <OnPlatform x:TypeArguments="x:Boolean">
            <OnPlatform.iOS>false</OnPlatform.iOS>
            <OnPlatform.Android>true</OnPlatform.Android>
         </OnPlatform>
    </StackLayout.IsVisible>
</Stacklayout>

And for the grid the other way around. Note: the latter might negatively impact your layout cycle
PS. Device.OS is deprecated, you should use Device.RuntimePlatform now.


text:
Q: read csv from pandas issues (delimiters or separators not working) My raw data in csv format is as below
text,location,user_follower_count,user_verified
shameful  a poor man from bihar is killed  j amp k administration under central rule did not even arrange for his body to be flown,NA,NA,NA
being right about anything can be its own reward  but you migh    more for aquarius,NA,NA,NA
they don t want herd immunity  they want a herd mentality,NA,NA,NA

I am trying to read the above file as follows.
raw_data = pd.read_csv(raw_tweet_data,sep=",", header='infer')

But everything gets deleted jammed under column (text).  location,user_follower_count,user_verified columns are "Nan".
I tried both "delimiters" and "sep". Both don't work. Why is it so?

A: try to mention the columns when reading along with other parameters like pd.read_csv(columns=[...]) once I faced this type of problem by mentioning the column names it was solved.

A: Problem was because of "NA" string in columns like location, user_follower_count and user_verified
Pandas is reading "NA" string as Nan. Once I changed the string "NA" to "not available", issue got resolved. Bit tricky. Thanks.


text:
Q: Local Service account canot write to filesystem I have created a simple Windows service, following these youtube videos:
https://www.youtube.com/watch?v=cp2aFNtcZfk.
This works, so long as I don't try to do any logging. If I call my logging function:
    public static void LogMsg(LogMsgTypes msgType, string msg)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory;

        string logFileName = string.Format("{0}Recalculator{1:yyyyMMdd}.log",path, DateTime.Now);
        var file = System.IO.File.AppendText(logFileName);

        file.WriteLine(string.Format("{0} {1,-9} : {2}", DateTime.Now.ToString(), msgType, msg));

        file.Close();
    }

then the service crashes and I get an Unauthorized Access Exception error in the Windows Event Log. I know I should be logging to the Event Log anyway, but I gather I will have to create the source manually first and I would really like to be able to write to a file if possible. On the youtube tutorial I am following, the guy gets no errors at all.

A: I think the correct answer is probably that I should do it 'right' by creating a source in the Windows Event Log and then writing to there instead of to a custom log file.
For now, I have just installed the service to run under Local System.


text:
Q: How can I display the familly name first in the addressbook on Ubuntu Touch? I just want to display it in the format
Famillyname, Firstname
Doe, John

A: Not sure if that's possible at the moment
There is a bug about sorting
https://bugs.launchpad.net/address-book-app/+bug/1215373
It might be worth opening another one with your request
https://bugs.launchpad.net/ubuntu/+source/address-book-app/+filebug


text:
Q: Saber el valor de una celda y modificar sus estilos según su valor Tomando la siguiente tabla como ejemplo
columna 1 columna 2 columna 3
    10        8         9
     8        9         8
    10       10         8

Necesito que las celdas que contengan valor de 8 esten de color rojo
Como aquí

.valor{
  color:red;
}

       columna 1
       columna 2
       columna 3
       columna 4
       columna 5
       columna 6
       columna 7
       columna 8
       columna 9
       columna 10

       10
       10
       8
       8
       9
       10
       8
       8
       10
       10

       10
       10
       8
       10
       9
       10
       8
       8
       10
       10

       10
       10
       8
       9
       9
       10
       8
       8
       10
       10

       10
       9
       8
       10
       9
       10
       8
       8
       10
       10

       10
       10
       8
       8
       9
       8
       8
       8
       10
       8

En el ejemplo anterior a las celdas con valor 8 le agrego la clase valor y con css le agrego el color rojo, pero necesito hacerlo con java script o jQuery.
columnas = $('.valor').text();

for(var i =0; i < columnas.length; i++){
    if(columnas[i] == 8){
        columnas[i].css('color','red');
    }
}

Utilizando jQuery a una variable llamada columnas le paso todas las celdas y su valor mediante el selector de clase 'valor' esto me funciona trato de recorrer con un for y para cada posición pregunto si el valor es igual con 8, hasta aquí no tengo problema al parecer funciona correctamente, la situación es cuando quiero añadirle los estilos a la celda en la posición n me arroja el siguiente error:
Uncaught TypeError: columnas[i].text is not a function
por lo que solicito su ayuda, gracias.

A: Tienes que seleccionar primero los td con clase valor, después lo recorres con un for y para obtener su contenido puedes utilizar innerHTML, después validas si el contenido es 8, le agregas el color con style.color="red", no hay necesidad de usar jQuery, con JavaScript puro funciona.

let td = document.getElementsByClassName('valor');

for(let i = 0; i < td.length; i++){

    //console.log(td[i].innerHTML);

      //console.log(td[i]);

   if(td[i].innerHTML == '8'){

        td[i].style.color = 'red';

    }

}
/*.valor{
  color:red;
}*/

       columna 1
       columna 2
       columna 3
       columna 4
       columna 5
       columna 6
       columna 7
       columna 8
       columna 9
       columna 10

       10
       10
       8
       8
       9
       10
       8
       8
       10
       10

       10
       10
       8
       10
       9
       10
       8
       8
       10
       10

       10
       10
       8
       9
       9
       10
       8
       8
       10
       10

       10
       9
       8
       10
       9
       10
       8
       8
       10
       10

       10
       10
       8
       8
       9
       8
       8
       8
       10
       8

A: el problema es que al hacer columnas = $('.valor').text(); estas obteniendo un arreglo de string con los valores de los td lo que tienes que hacer es obtener como tal el objeto y no el texto columnas = $('.valor') y hacer las adecuaciones dentro del for.
columnas = $('.valor');

for (var i = 0; i < columnas.length; i++) {
  if (columnas[i].innerHTML == '8') {
   columnas[i].style.color = 'red';
  }
}

o igual puedes hacer que se recorra todas los  de la tabla para que agregue la condición.
$("#tabla tbody tr td").each(function (element) {
   if ($(this).text() == 8) {
       $(this).css('color', 'red');
   }
});

Saludos.

A: Tengo el mismo problema pero la diferencia es que necesito una funcion para cambiar el color de fondo de la td className "celda" de acuerdo al dato de estadotk, cuando el dato sea Pendiente el color de fondo debe ser rojo, me podrian ayudar por favor...
ListadoTickets.map((ticket) => (

                                    {ticket.fecha}
                                    {ticket.asunto}

                                    {ticket.solicitud}
                                    {ticket.agente}
                                     {ticket.estadotk }

                                    {ticket.cierre}
                                    {ticket.fechaCierre}

                            ))


text:
Q: How to resize Text field in IE9? I'm able to resize Text Field in Chrome & other browsers. However, I'm not able to make the same work in IE9, even after installing the Chrome frame for IE. I use for Ex:
style="resize:horizontal;"
Ex:

Can someone suggest me how to make it work in IE browsers?
Thanks.
*EDIT*
Ok, So after a lot of tweaking around, I finally made it to work for IE9 !! Yay :)
First things first : You need to install the Chrome Frame on IE9.
Then you add some tags for it to render on IE.
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

Here's the complete code :
<!DOCTYPE >

<html xmlns="http://www.w3.org/1999/xhtml">
<!-- <meta http-equiv="X-UA-Compatible" content="chrome=IE9">
<!-- X-UA-Compatible: chrome=1-->

<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

<head>
    <title>Text Feilds</title>

   <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>

 </head>
<body>
<input type="text" id="txt1" style= "resize: horizontal"; />
<input type="text" id="txt2" style= "resize: both"; />

</body>
</html>

A: If you have a look at http://www.w3schools.com/cssref/css3_pr_resize.asp you will see that this feature is not supported in IE at all.
If you want to support this feature in all browsers you will have to create your own resize function in javascript (our use any framework if there is one).

A: You can't, in any simple way. According to http://caniuse.com/#feat=css-resize there is no support in IE 9, and IE 10 status is unknown.

A: That's HTML5 markup and older versions of IE do not support HTML5 or HTML5 ready. IE 9 only supports it in parts


text:
Q: Is that $\pi_*\pi^*=1$ for a projective bundle $\mathbb P(\mathscr E)\xrightarrow{\pi}S$, I'm reading Thomason's proof of projective bundle formula in algebraic K-theory, and have trouble understanding the proof. Here is the set up.
Let $ S$ be a qcqs scheme, and $X=\mathbb P(\mathscr E)$ the projective bundle over $S$ with structure morphism $\pi:X\rightarrow S$. A fact used in the proof is $\pi_*\pi^*=1$. How does this follows?


text:
Q: MS Project - Macro not working on XML custom tab I'm creating a custom tab in MS Project using VBA and XML. On the ProjectGlobal I have the following:
Inside ThisProject(Global.MPT)
Private Sub Project_Activate(ByVal pj As MSProject.Project)

ribbonXml = "<mso:customUI xmlns:x1=""http://schemas.microsoft.com/office/2009/07/customui/macro"" xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">"
ribbonXml = ribbonXml + "<mso:ribbon>"
ribbonXml = ribbonXml + "<mso:qat/>"
ribbonXml = ribbonXml + "<mso:tabs>"
ribbonXml = ribbonXml + "<mso:tab id=""mso_c1.497B55B8"" label=""Produtos Novos"">"
ribbonXml = ribbonXml + "<mso:group id=""mso_c2.497B55B8"" label=""New Product"" imageMso=""ViewGoForward"" autoScale=""true"">"
ribbonXml = ribbonXml + "<mso:button idQ=""x1:newProjectPN"" label=""New Project (NOK)"" imageMso=""CategoryCollapse"" onAction=""thisproject.newProjectPN"" visible=""true"" />"
ribbonXml = ribbonXml + "</mso:group>"
ribbonXml = ribbonXml + "</mso:tab>"
ribbonXml = ribbonXml + "</mso:tabs>"
ribbonXml = ribbonXml + "</mso:ribbon>"
ribbonXml = ribbonXml + "</mso:customUI>"

ActiveProject.SetCustomUI (ribbonXml)

End Sub

Then I have a module with the following
Sub newProjectPN()

MsgBox "Not working yet. Please be patient :)"

End Sub

It creates the tab with the button as expected, but when I click the button it does nothing. How do I reference the macro in XML strings?

A: I've found the solution. I was using two different namespaces in the XML code. This is what I have now and it works. I've also changed the button id from idQ to id.
Private Sub Project_Activate(ByVal pj As MSProject.Project)

ribbonXml = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">"
ribbonXml = ribbonXml + "<mso:ribbon>"
ribbonXml = ribbonXml + "<mso:qat/>"
ribbonXml = ribbonXml + "<mso:tabs>"
ribbonXml = ribbonXml + "<mso:tab id=""mso_c1.497B55B8"" label=""Produtos Novos"">"
ribbonXml = ribbonXml + "<mso:group id=""mso_c2.497B55B8"" label=""New Product"" imageMso=""ViewGoForward"" autoScale=""true"">"
ribbonXml = ribbonXml + "<mso:button id=""newProjectPN"" label=""New Project (NOK)"" imageMso=""CategoryCollapse"" onAction=""thisproject.newProjectPN"" visible=""true"" />"
ribbonXml = ribbonXml + "</mso:group>"
ribbonXml = ribbonXml + "</mso:tab>"
ribbonXml = ribbonXml + "</mso:tabs>"
ribbonXml = ribbonXml + "</mso:ribbon>"
ribbonXml = ribbonXml + "</mso:customUI>"

ActiveProject.SetCustomUI (ribbonXml)

End Sub