text:
Q: Vue TypeScript Undefined value after passing to function of Vuex module I have async function named save in a my component
async save(): Promise<void> {
if (!this.ValidateForm()) {
  notifyError("", "Please enter all fields correctly");
}
else {
  await userModule.update(userModule.currentUser?.id as number, this.user, this.file);
  notifySuccess("Your profile updated");
}
}

When this line executed :
await userModule.update(userModule.currentUser?.id as number, this.user, this.file);

Value of second and third argument becomes undefined in userModule.update .
In addition i have to say i don't use any arrow function
and i tried console.log(this.user, this.file) everything is ok.
here is my code :
AccountSetting.ts HTML
<template>

Change your information

      <form>

              Username
              <input
                type="text"
                v-model="user.username"
                @change="checkUsername()"
                class="form-control"
                placeholder="Enter new Username"
              />
              {{ validations.username }}

              Profile Pricture

                <input
                  id="customFile"
                  type="file"
                  class="custom-file-input"
                  v-on:change="handleFileUpload($event)"
                  accept="image/*"
                />
                {{
                  lblFilename
                }}

              Firstname
              <input
                type="text"
                v-model="user.firstname"
                @change="checkFirstname()"
                class="form-control"
                placeholder="Enter your Firstname"
              />
              {{ validations.firstname }}

              Lastname
              <input
                type="text"
                v-model="user.lastname"
                @change="checkLastname()"
                class="form-control"
                placeholder="Enter your Lastname"
              />
              {{ validations.lastname }}

              Email
              <input
                type="text"
                v-model="user.email"
                @change="checkEmail()"
                class="form-control"
                placeholder="Enter your Email address"
              />
              {{ validations.email }}

              Phone Number
              <input
                type="text"
                v-model="user.phoneNumber"
                @change="checkPhonenumber()"
                class="form-control"
                placeholder="Enter your Phone number"
              />
              {{
                validations.phoneNumber
              }}

              Birthdate
              <input
                type="date"
                v-model="user.birthdate"
                class="form-control"
                placeholder=""
              />

              Gender

                  Male
                  <input
                    id="inlineRadioMale"
                    type="radio"
                    name="gender"
                    value="1"
                    v-model="user.gender"
                    class="form-check-input"
                    checked
                  />

                  Female
                  <input
                    id="inlineRadioFemale"
                    type="radio"
                    name="gender"
                    value="2"
                    v-model="user.gender"
                    class="form-check-input"
                  />

          <button type="button" class="btn btn-primary" @click="save()">
            Save
          </button>

      </form>

  </template>

AccountSetting.ts script
import { Component, Vue } from "vue-property-decorator";
import { UserUpdate } from "@/models/user/user";
import userModule from "@/store/modules/user";
import validationUtils from "@/common/validationUtils";
import { notifySuccess, notifyError } from
"@/common/notificationUtils";
import GenderType from "@/common/Enums/genderType";
import { isNullOrEmpty } from "@/common/stringUtils";

@Component
export default class AccountSetting extends Vue {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private file: any;
private lblFilename = "Choose file";
private user: UserUpdate = {
username: userModule.currentUser?.username as string,
firstname: userModule.currentUser?.firstname as string,
lastname: userModule.currentUser?.lastname as string,
email: userModule.currentUser?.email as string,
birthdate: userModule.currentUser?.birthdate as string,
phoneNumber: userModule.currentUser?.username as string,
gender: userModule.currentUser?.gender as GenderType,
teamId: userModule.currentUser?.teamId as number,
profilePictureId: userModule.currentUser?.profilePictureId as number,
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
private validations: any = {
username: "",
password: "",
firstname: "",
lastname: "",
email: "",
phoneNumber: "",
};

checkUsername(): void {
if (!validationUtils.isValidUsername(this.user.username)) {
  this.validations.username = "Username is invalid";
}
else if (this.user.username.length == 0) {
  this.validations.username = "Username is invalid";
}
else if (this.user.username.length > 15) {
  this.validations.username = "Username should be less than 15 characters";
}
else {
  this.validations.username = "";
}
}

checkEmail(): void {
if (!validationUtils.isValidEmail(this.user.email)) {
  this.validations.email = "Email is invalid";
} else {
  this.validations.email = "";
 }
 }

checkFirstname(): void {
if (this.user.firstname.length == 0) {
  this.validations.firstname = "Firstname is invalid";
}
else if (this.user.firstname.length > 35) {
  this.validations.firstname = "Firstname should be less than 35 characters";
}
else {
  this.validations.firstname = "";
}
}

checkLastname(): void {
if (this.user.lastname.length == 0) {
  this.validations.lastname = "Lastname is invalid";
}
else if (this.user.firstname.length > 35) {
  this.validations.lastname = "Lastname should be less than 35 characters";
}
else {
  this.validations.lastname = "";
}
}

checkPhonenumber(): void {
if (this.user.phoneNumber.length == 0) {
  this.validations.phoneNumber = "Phone Number is invalid";
}
else {
  this.validations.phoneNumber = "";
}
}

ValidateForm(): boolean {
this.checkUsername();
this.checkFirstname();
this.checkLastname();
this.checkEmail();
this.checkPhonenumber();

if (this.user.username == "" || !isNullOrEmpty(this.validations.userUsername)) {
  return false;
}

if (this.user.firstname == "" || !isNullOrEmpty(this.validations.firstname)) {
  return false;
}

if (this.user.lastname == "" || !isNullOrEmpty(this.validations.lastname)) {
  return false;
}

if (this.user.email == "" || !isNullOrEmpty(this.validations.email)) {
  return false;
}

if (this.user.phoneNumber == "" || !isNullOrEmpty(this.validations.phoneNumber)) {
  return false;
}
return true;

}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
handleFileUpload(event: any): void {
this.file = event.target.files[0];
this.lblFilename = this.file.name;
}

async save(): Promise<void> {
if (!this.ValidateForm()) {
  notifyError("", "Please enter all fields correctly");
}
else {
  await userModule.update(userModule.currentUser?.id as number, this.user, this.file);
  notifySuccess("Your profile updated");
  }
 }

 }

Vuex module
user.ts :
import {
Action,
getModule,
Module,
Mutation,
VuexModule
} from "vuex-module-decorators";
import modulesNames from "@/store/moduleNames";
import store from "@/store/index";
import localStorageUtils from "@/common/localStorageUtils";
import { User, UserCreate, UserUpdate } from
 "@/models/user/user";
import Token from "@/models/authentication/token";
import authenticationService from
 "@/services/authentication/authenticationService";
import userService from "@/services/user/userService";
import Login from "@/models/user/login";
import { isEmptyObject } from "@/common/objectUtils";

@Module({ dynamic: true, namespaced: true, store, name: modulesNames.user })
class UserModule extends VuexModule {

private _currentUser?: User = localStorageUtils.getItem("User");
private _authToken?: Token = localStorageUtils.getItem("Token");

get currentUser(): User | undefined | null {
    return this._currentUser;
}

get authToken(): Token | undefined | null {
    return this._authToken;
}

get isLoggedIn(): boolean {
    return !isEmptyObject(this.currentUser);
}

@Mutation
private SET_CURRENT_USER(currentUser?: User): void {
    if (currentUser) {
        this._currentUser = currentUser;
        localStorageUtils.setItem("User", currentUser);
    } else {
        this._authToken = undefined;
        localStorageUtils.removeItem("User");
    }
}

@Mutation
private SET_AUTH_TOKEN(authToken?: Token): void {
    if (authToken) {
        this._authToken = authToken;
        localStorageUtils.setItem("Token", authToken);
    } else {
        this._authToken = undefined;
        localStorageUtils.removeItem("Token");
    }
}

@Action({ rawError: true })
public async login(login: Login): Promise<void> {
    const response = await authenticationService.login(login);
    this.SET_CURRENT_USER(response);
}

@Action({ rawError: true })
public async register(userCreateOrUpdate: UserCreate): Promise<void> {
    const response = await authenticationService.register(userCreateOrUpdate);
    this.SET_CURRENT_USER(response);
}

@Action({ rawError: true })
public async update(id: number, userUpdate: UserUpdate, file: any): Promise<void> {
    const response = await userService.updateUser(id, userUpdate, file);
    this.SET_CURRENT_USER(response);
}

@Action({ rawError: true })
public async logout(): Promise<void> {
    await authenticationService.logout();
    this.SET_AUTH_TOKEN(undefined);
    this.SET_CURRENT_USER(undefined);
}

}

export default getModule(UserModule);

index.ts
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {},
});

modulesNames.ts :
const modulesNames = {
user: "user",
};

export default modulesNames;

A: I'm new to javascript and typescript and frontend frameworks .
After many attempts for this problem in stackoverflow an also reading the docs
,I found nothing so i decided to do more debugging and i understand
Vuex actions only take one arguments so another arguments values becomes undefined


text:
Q: How to convert select-input content to string on sql query? My html form has 2 select-input field which are sent via HTTP POST as json to my java webserver API and then to my postgresql. Im having a internal error and i believe that is because the select-input json output is like this "field":["value"]
How can i tell java to read the content inside the [ ]?
this is my query
String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
                + " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
This is the http post method on my angular frontend
    postData(params){
     let headers = new Headers();
     headers.append('Content-type','application/json');
     return this.http.post(this.api,params,{
     headers: headers
   }).map(
   (res:Response) => {return res.json();}
   );

And this is the java web server post method
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/neuromotora/")
public Response createNeuromotora(Neuromotora n) throws SQLException, ClassNotFoundException{
    neuromotoraDAO dao = new neuromotoraDAO();

    dao.insert(n);

    return Response
      }

And this is the neuromotora java
  public class Neuromotora {
   private int neuromotoraid;
   private String latencia;
   private String amplitudeDistal;
   private String amplitutdeProx;
   private String nervoNome;
   private String ladoNervo;
   private String ondaF;
   private int pacienteid;
    ...getters and  setters..
     }

Insert method
 public Long insert(Neuromotora oferta) throws SQLException, ClassNotFoundException{
    Long id = null;
    String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
            + " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
    try{
        PreparedStatement stmt = this.con.getConnection().prepareStatement(sqlQuery);
        stmt.setString(1,oferta.getNervoNome());
        stmt.setString(2,oferta.getLatencia());
        stmt.setString(3,oferta.getAmplitudeDistal());
        stmt.setString(4,oferta.getAmplitutdeProx());
        stmt.setString(5, oferta.getVelocidade());
        stmt.setString(8, oferta.getOndaF());
        stmt.setInt(6,oferta.getPacienteid());
        stmt.setString(7,oferta.getLadoNervo());

        ResultSet rs = stmt.executeQuery();
        if(rs.next()){
            id = rs.getLong("neuromotoraid");
        }

        this.con.commit();
        }
    catch(SQLException e){
        this.con.rollback();
        throw e;
        }
        return id;
        }

A: Removing the the multiple="true" on the ion-select and adding size="1" worked for me, the input is no longer a json array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Factoring $x^5 - 5x^4 + 1$ The original problem was stated like this:
Prove that the polynomial $x^5 - 5x^4 + 1$ does not have roots of multiplicity 4.
So, factoring the polynomial would answer the question, but I don't know how to do it.
Using the root test, ${1, -1}$ should be roots, but If I divide by $x-1$ or $x+1$  $\frac {x^5 - 5x^4 + 1}{x-1}$, or $\frac {x^5 - 5x^4 + 1}{x-1}$ I get a remainder, so those are not roots?!

A: As suggested in the comments, try this $$\begin{align}(x-a)(x-b)^4&=(x-a)(x^4-4x^3b+6x^2b^2-4xb^3+b^4)\\&=(x^5-(a+4b)x^4+(4ab+6b^2)x^3-(4b^3+6ab^2)x^2+(b^4+4ab^3)x-ab^4)\end{align}$$
For this to match the expression $x^5-5x^4+1$, we need:
$$\begin{align}&a+4b=5\\&b(4a+6b)=0\\&b^2(4b+6a)=0\\&b^3(b+4a)=0\\&ab^4=-1
\end{align}$$
From the fifth equation, $b\neq 0$. Then from the fourth equation, $b=-4a$. Substitution into the first yields $a-16a=5\implies a=-\frac13\implies b=\frac43$. But substitution into the second equation gives $4a+6b=-\frac43+\frac{24}3\neq0$. Similarly, the third equation fails.
So the expression $x^5-5x^4+1$ cannot be factored into this form.

A: Factoring is not a good idea; factoring a 5th degree polynomial is difficult at best, and usually impossible.
You can show this using derivatives. If $a$ is a repeated root of $p(x)$ with multiplicity 4, then $p(x) = (x-a)^{4}(x-b)$.  If you look at the first three derivatives, you can see that $p(a)$, $p^{\prime}(a)$, $p^{\prime\prime}(a)$, and $p^{(3)}(a)$ all should evaluate to $0$.  If you look at your polynomial, you can see that this is not the case (the roots are easy to find for all of the derivatives).

A: I am surprised nobody offered this approach yet: If a polynomial $f \in \mathbb Q[X]$ has a root $a \in \mathbb C$ of multiplicity $4$, then we have $m^4 |f$ in $\mathbb Q[X]$, where $m \in \mathbb Q[X]$ is the minimal polynomial of $a$. Then of course $\deg f=5$ yields $\deg m=1$, i.e. $a \in \mathbb Q$. Thus any root of multiplicity $4$ is actually a rational root, which (as the OP already figured out) would be either $1$ or $-1$ and you can just check that they are not (of course just by plugging in and not by doing the division). Thus the polynomial has no root of multiplicity $4$.

A: The derivative  of $P(x)=x^5-5x^4+1$ is $P'(x)=5x^3(x-4).$ Now $P'(x)>0$ for $x>4$ and also $P'(x)>0$ for $x<0.$  And $P'(x) <0$ for $x\in  (0,4).$
So $P$ is strictly increasing on  $(-\infty,0],$ strictly decreasing on $[0,4],$ and strictly increasing on $[4,\infty)$.
Therefore, from that, and from  $P(-1)<0<P(0)$ and $P(4)<0<P(5),$ we conclude that there are exactly 3 real solutions to $P(x)=0,$ one in $(-1,0),$ one in $(0,4),$ and one in $(4,5).$ The 2 other solutions to $P(x)=0$ must be  complex, of the form $a\pm bi,$ with real $a, b$ with $b\ne 0.$

A: Since $P(x)'=5x^3(x-4)$, the possibities are only two.
$P(x)=(x+a)(x-4)^4$ or $(x+b)x^4$
But these never become OP's.

A: extended gcd in $\mathbb Q[x].$ the original polynomial and its derivative are coprime; there are no multiple roots, not even double.
$$  \left(   x^{5}  - 5 x^{4}  + 1 \right)  $$
$$  \left(   x^{4}  - 4 x^{3}  \right)  $$
$$  \left(   x^{5}  - 5 x^{4}  + 1 \right)  =  \left(   x^{4}  - 4 x^{3}  \right)  \cdot \color{magenta}{ \left(   x  - 1 \right)}  +  \left(   - 4 x^{3}  + 1 \right)  $$
 $$  \left(   x^{4}  - 4 x^{3}  \right)  =  \left(   - 4 x^{3}  + 1 \right)  \cdot  \color{magenta}{ \left(   \frac{  -  x  + 4 }{ 4 }  \right)}  +  \left(   \frac{  x  - 4 }{ 4 }  \right)  $$
 $$  \left(   - 4 x^{3}  + 1 \right)  =  \left(   \frac{  x  - 4 }{ 4 }  \right)  \cdot  \color{magenta}{ \left(   - 16 x^{2}  - 64 x  - 256 \right)}  +  \left( -255  \right)  $$
 $$  \left(   \frac{  x  - 4 }{ 4 }  \right)  =  \left( -255  \right)  \cdot  \color{magenta}{ \left(   \frac{  -  x  + 4 }{ 1020 }  \right)}  +  \left( 0 \right)  $$
 $$ \frac{ 0}{1} $$
 $$ \frac{ 1}{0} $$
 $$  \color{magenta}{ \left(   x  - 1 \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   x  - 1 \right) }{ \left( 1  \right) } $$
 $$   \color{magenta}{\left(   \frac{  -  x  + 4 }{ 4 }  \right)}   \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{  -  x^{2}  + 5 x  }{ 4 }  \right) }{ \left(   \frac{  -  x  + 4 }{ 4 }  \right) } $$
 $$   \color{magenta}{\left(   - 16 x^{2}  - 64 x  - 256 \right)}   \Longrightarrow  \Longrightarrow  \frac{  \left(  4 x^{4}  - 4 x^{3}  - 16 x^{2}  - 319 x  - 1 \right) }{ \left(  4 x^{3}  - 255 \right) } $$
 $$  \color{magenta}{ \left(   \frac{  -  x  + 4 }{ 1020 }  \right)}   \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{  -  x^{5}  + 5 x^{4}  - 1 }{ 255 }  \right) }{ \left(   \frac{  -  x^{4}  + 4 x^{3}  }{ 255 }  \right) } $$
 $$  \left(   x^{5}  - 5 x^{4}  + 1 \right)  \left(   \frac{ 4 x^{3}  - 255 }{ 255 }  \right)  -  \left(   x^{4}  - 4 x^{3}  \right)  \left(   \frac{ 4 x^{4}  - 4 x^{3}  - 16 x^{2}  - 319 x  - 1 }{ 255 }  \right)  =  \left( -1  \right)  $$

A: Let $f(x) = x^5 + 5x^4 + 1.$
Rather than perform division of polynomials, a simple way to test possible rational roots is just to plug them into the equation. For $x=-1$ and $x=1$ this gives us
\begin{align}
f(-1) &= (-1)^5-5(-1)^4 + 1 = -5, \\
f(1)  &= (1)^5-5(1)^4 + 1 = -3.
\end{align}
But of course $f(0) = 1.$ So there is one root between $-1$ and $0$ and another between $0$ and $1.$ There must also be a root greater than $1$ since  we know $f(x)$ eventually grows without bound.
That's three distinct roots. If any of these had multiplicity $4,$
then $f(x)$ would have a total of at least six roots (including multiple roots).
But $f(x)$ is only fifth degree and can have at most five roots.
Therefore $f(x)$ has no roots of multiplicity $4.$

A: The "easy" part of the fundamental theorem of algebra says that a polynomial of degree $n$ has at most $n$ roots, counting multiplicities.  (The "hard" part says it has exactly $n$ roots, but we only need the "at most" part here.). Therefore, if $x^5-5x^4+1$ had a root of multiplicity $4$, it would have at most $2$ distinct roots, namely the the one of multiplicity $4$ and at most one other.  But the polynomial, which is of odd degree, is positive at $x=0$ and negative at $x=1$, so it has at least three distinct real roots (one less than $0$, one between $0$ and $1$, and one greater than $1$).  Thus it cannot have a root of multiplicity $4$.
Remark: This approach only rules out roots of multiplicity $4$ or $5$; it does not rule out the possibility of multiplicy $2$ or $3$.  But it avoids doing any explicit algebra beyond evaluating the polynomial in question at two points.
Additional remark:  This answer is essentially the same as David K's.  For some reason I didn't see his answer when I initially posted.

A: Note that for $n\geqslant 1$, a polynomial $f$ has a root of multiplicity $(n+1)$ if and only if $f$ shares a root with $f^{(n)}$.
Consider $f = x^5 - 5x^4 + 1, n=3$.
Then $f''' = 60x^2-60x=60x(x-1)$.
The only roots of $f'''$ are $0,1$, which are not roots of $f$.
Thus, $f$ and $f'''$ share no roots, and hence $f$ has no roots of multiplicity $4$.


text:
Q: Drawing weighted circles on an svg path I have a set of nodes with weight and a title.
How can I render these data as circles with following conditions using D3 js:

*

*circles should place on a predefined path (for example a tree in SVG format)

*circles should not interfere with each other

*each circle should have radius in relation with its weight

*having a reference predefined central point in the predefined path(condition 1), the distance of each circle to this reference point is also determined by its weight.the most weighted node should be the nearest to the reference point.

*circles should be limited in a frame (width and height)

Is it necessary to use D3 or it can be simply done using an algorithm on html5 canvas?
Thanks in advance


text:
Q: How these transactions cause deadlock? I've 2 types of transactions:
Type 1 includes the following Sqls:
UPDATE userdb_ingest_report SET start_time='%s', end_time='%s', is_csv_ingest=%d, success=%d, failed=%d WHERE clientid='%s' AND filename='%s' AND network_id=%d AND data_provider_id=%d;\n
    or
INSERT INTO userdb_ingest_report(clientid, filename, network_id, data_provider_id, start_time, end_time, is_csv_ingest, success, failed) VALUES ('%s', '%s', %d, %d, '%s', '%s', %d, %d, %d);\n"
    and
DELETE FROM userdb_ingest_report WHERE clientid<>'%s' AND filename='%s' AND network_id=%d AND data_provider_id=%d;\n

Type 2 includes the following Sqls:
UPDATE userdb_ingest_report SET start_time=LEAST(%s, start_time), end_time=GREATEST(%s, end_time), is_csv_ingest=%d, success=success+%d, failed=failed+%d WHERE clientid='%s' AND filename='%s' AND network_id='%d' AND data_provider_id='%d'"
    or
INSERT INTO userdb_ingest_report(clientid, filename, network_id, data_provider_id, start_time, end_time, is_csv_ingest, success, failed) VALUES ('%s', '%s', %d, %d, '%s', '%s', %d, %d, %d);\n

There may be 1 instance of type1 and 1-6 instances of type2 running concurrently. Sometimes I'll get the deadlock failure:
Update table userdb_ingest_report error. Sql:UPDATE userdb_ingest_report SET start_time=LEAST(20170622134845, start_time), end_time=GREATEST(20170622134846, end_time), is_csv_ingest=1, success=success+184, failed=failed+0 WHERE clientid='clienta' AND filename='file1' AND network_id='48804' AND data_provider_id='386123', Error:Error 1213: Deadlock found when trying to get lock; try restarting transaction
or
Insert table userdb_ingest_report error. Sql:INSERT INTO userdb_ingest_report(clientid, filename, network_id, data_provider_id, start_time, end_time, is_csv_ingest, success, failed) VALUES ('clientb', 'fileb', 385316, 385316, '20170622140908', '20170622140922', 1, 372521, 0); , Error:Error 1213: Deadlock found when trying to get lock; try restarting transaction

and this is the schema of this table:
CREATE TABLE `userdb_ingest_report` (
  `filename` varchar(255) NOT NULL,
  `network_id` bigint(20) NOT NULL,
  `data_provider_id` bigint(20) NOT NULL,
  `start_time` datetime NOT NULL,
  `end_time` datetime NOT NULL,
  `is_csv_ingest` smallint(1) NOT NULL,
  `success` bigint(20) DEFAULT '0',
  `failed` bigint(20) DEFAULT '0',
  `clientid` char(30) DEFAULT '',
  KEY `network_data_provider_clientid_idx` (`network_id`,`data_provider_id`,`clientid`,`filename`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

When I use show innodb status in mysql, I got the following messages about the last deadlock information:
------------------------
LATEST DETECTED DEADLOCK
------------------------
170622 21:15:22
*** (1) TRANSACTION:
TRANSACTION 3F427F4B, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 30 lock struct(s), heap size 6960, 41 row lock(s), undo log entries 14
MySQL thread id 43053224, OS thread handle 0x2b8f80ffe940, query id 1158507552 10.1.10.42 backend_new update
INSERT INTO userdb_ingest_report(clientid, filename, network_id, data_provider_id, start_time, end_time, is_csv_ingest, success, failed) VALUES ('auingest03.fwmrm.net_1', '/mnt/sftponly/381963/files/audience/ingest/pending/visitor_attr_381963_20170622145737.csv.gz', 0, 381963, '20170622211520', '20170622211522', 1, 18203, 0)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 1026 page no 711706 n bits 176 index `network_data_provider_clientid_idx` of table `fwmrm_stats`.`userdb_ingest_report` trx id 3F427F4B lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 16 PHYSICAL RECORD: n_fields 5; compact format; info bits 0
 0: len 8; hex 8000000000000000; asc         ;;
 1: len 8; hex 800000000005d457; asc        W;;
 2: len 30; hex 202020202020202020202020202020202020202020202020202020202020; asc                               ;;
 3: len 30; hex 2f6d6e742f736674706f6e6c792f3338323033392f66696c65732f617564; asc /mnt/sftponly/382039/files/aud; (total 92 bytes);
 4: len 6; hex 00000c420d62; asc    B b;;

*** (2) TRANSACTION:
TRANSACTION 3F427F4C, ACTIVE 0 sec inserting, thread declared inside InnoDB 500
mysql tables in use 1, locked 1
28 lock struct(s), heap size 6960, 38 row lock(s), undo log entries 13
MySQL thread id 43053207, OS thread handle 0x2b8f80bee940, query id 1158507553 10.1.10.41 backend_new update
INSERT INTO userdb_ingest_report(clientid, filename, network_id, data_provider_id, start_time, end_time, is_csv_ingest, success, failed) VALUES ('auingest02.fwmrm.net_1', '/mnt/sftponly/381963/files/audience/ingest/pending/visitor_attr_381963_20170622145737.csv.gz', 0, 381963, '20170622211520', '20170622211522', 1, 36103, 0)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 1026 page no 711706 n bits 176 index `network_data_provider_clientid_idx` of table `fwmrm_stats`.`userdb_ingest_report` trx id 3F427F4C lock_mode X locks gap before rec
Record lock, heap no 16 PHYSICAL RECORD: n_fields 5; compact format; info bits 0
 0: len 8; hex 8000000000000000; asc         ;;
 1: len 8; hex 800000000005d457; asc        W;;
 2: len 30; hex 202020202020202020202020202020202020202020202020202020202020; asc                               ;;
 3: len 30; hex 2f6d6e742f736674706f6e6c792f3338323033392f66696c65732f617564; asc /mnt/sftponly/382039/files/aud; (total 92 bytes);
 4: len 6; hex 00000c420d62; asc    B b;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 1026 page no 711706 n bits 176 index `network_data_provider_clientid_idx` of table `fwmrm_stats`.`userdb_ingest_report` trx id 3F427F4C lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 16 PHYSICAL RECORD: n_fields 5; compact format; info bits 0
 0: len 8; hex 8000000000000000; asc         ;;
 1: len 8; hex 800000000005d457; asc        W;;
 2: len 30; hex 202020202020202020202020202020202020202020202020202020202020; asc                               ;;
 3: len 30; hex 2f6d6e742f736674706f6e6c792f3338323033392f66696c65732f617564; asc /mnt/sftponly/382039/files/aud; (total 92 bytes);
 4: len 6; hex 00000c420d62; asc    B b;;

so how would this happen, and how can I solve this deadlock?


text:
Q: How Content Controls are indexed in repeating Section Content Control? I have document with two paragraph: in the first one one Plain text CC and in the second one repeating section CC with one Plain Text CC inside.
I am trying to move all the info from CC's in repeating section to appear in first paragraph CC. So far I have come to this code:
 Sub first_paragraph()

    Dim x As Integer
    Dim xNames As String
    Dim xEntry As String

    xNames = ""

    With ActiveDocument.SelectContentControlsByTag("VP_pav")

        For x = 1 To .Count
            With .Item(x)
                If .Tag = "VP_pav" Then
                    xEntry = ActiveDocument.SelectContentControlsByTag("VP_pav").Item(x).Range.Text
                        ' "if" for removing comma before first entry
                         If xNames = "" Then
                            xNames = xEntry + xNames
                            Else
                            xNames = xEntry + ", " + xNames
                            End If
                    End If
                End With
            Next x
        End With

    ActiveDocument.SelectContentControlsByTag("pirm_pas").Item(1).Range.Text = xNames

End Sub

Problem that CC generated in repeating section CC (then adding new section) seems to get random item number (I thought that first CC with tag "example" would get item number 1, second CC with the same tag get item number 2 and etc., but it seems it is not the case).
Because newly generated CC gets random item numbers, values in first paragraph CC are out of order.
Is it possible to make newly generated CC to get sequential numbers? How they get item numbers if they are not sequential? Should take some different approach?
I am adding picture to illustrate my situation:

P.S. I'm deletting my recently posted question about correct variables order in this situation since I determined that it is (probably) not the problem.

A: With the code shown, nothing is telling Word to read the content controls in any kind of order. In this case, a better approach would be to loop the content controls in the Repeaing Section content control.
The following example assumes the RepSec has been assigned to the Title of the repeating section content control:
 Sub first_paragraph()
    Dim xNames As String, xEntry as String
    Dim ccRepSec as Word.ContentControl
    Dim cc as Word.ContentControl

    xNames = ""

    Set ccRepSec = ActiveDocument.SelectContentControlsByTitle("RepSec").Item(1)
    For Each cc in ccRepSec.Range.ContentControls
         If .Tag = "VP_pav" Then
              xEntry = cc.Range.Text
              If xNames = "" Then
                 xNames = xEntry & xNames
              Else
                 xNames = xEntry & ", " & xNames
              End If
         End If
    Next cc

    ActiveDocument.SelectContentControlsByTag("pirm_pas").Item(1).Range.Text = xNames
End Sub


text:
Q: Conditional binding in column of datagrid I have a DataGrid which itemsSource is an ObservableCollection<MyType>. This type has this properties:
long ID;
long IDCategory;
long? IDState01;
long? IDEstate02;
long? IDEste03;

I have 3 categories, if it is category 1, IDState01 is not null and the others states are null. If category is 2, the IDState02 is not null and the others are null and son on.
I have a state column in my DataGrid, which value depends on the category. So I would like to binding to the correct property depending on the category, so if the category is 1, it would bind property state01, if the category is 3 it would bind property state02 and so on.
I think that my DataGrid would be something like that:
<DataGrid HorizontalAlignment="Stretch" Margin="5,5,5,5" VerticalAlignment="Stretch">
    <DataGrid.Columns>
        <DataGridTextColumn Header="State">
            <!--Something here, perhaps a datatrigger.-->
        </DateGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

Thanks.
EDIT: I would like to do it in XAML if it is possible, instead of using a converter.

A: introduce a property which will get/set the correct state based on category:
public long? State
{
    get
    {
        if (IDCategory == 1) return IDState01;
        if (IDCategory == 2) return IDState02;
        return null;
    }
    set
    {
        if (IDCategory == 1) IDState01 = value;
        else if (IDCategory == 2) IDState02 = value;
    }
}

in DataGird bind column to a new property:
<DataGridTextColumn Header="State" Binding="{Binding State}"/>

A:
I would like to do it in XAML if it is possible ...

You could use a DataGridTemplateColumn:
<DataGridTemplateColumn Header="State">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IDCategory}" Value="1">
                                <Setter Property="Text" Value="{Binding IDState01}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IDCategory}" Value="2">
                                <Setter Property="Text" Value="{Binding IDEstate02}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IDCategory}" Value="3">
                                <Setter Property="Text" Value="{Binding IDEste03}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox>
                <TextBox.Style>
                    <Style TargetType="TextBox">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IDCategory}" Value="1">
                                <Setter Property="Text" Value="{Binding IDState01}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IDCategory}" Value="2">
                                <Setter Property="Text" Value="{Binding IDEstate02}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IDCategory}" Value="3">
                                <Setter Property="Text" Value="{Binding IDEste03}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
            </TextBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

A: I think you will need own DataTemplate for each category and DataTemplateSelector to assign DataTemplates based on category type.


text:
Q: How to get api key from steamcommunity.com? I am working now, my site will  connection with  steamcommunity.com. I have completed the install steamcommunity. I have account also. But I am not get a API key. But one thing all tutorials will say follow this link and get API key. But my account in this link always show
Access Denied
You will be granted access to Steam Web API keys when you have games in your      Steam account.

Visit Steam Support for more information

I have followed this link
How can I get API key and open id from this site?

A: I had the same issue when I was trying to use the invisnik/laravel-steam-auth Laravel package to implement a steam auth system for my project.
By the time my steam account had ZERO purchases :D
First, I though it will be enough to buy just "any" item from their store, so obviously I've purchased a $1.99 game but nothing happened!
Then I saw somewhere that "maybe" a TOTAL of $5 spending will activate the API Key for my account. I gave it a try and bought two more games ($2.99 + $0.49).
Now my total spending have exceeded $5 ( $1.99 + $2.99 + $0.49 = $5.47) and the API Key got activated instantly !!

A: As mytuny stated, you need to have spent more than $5 on your account to obtain an Api key.
There are a few features that are disabled until you have spent $5 on Steam.
You can see the restrictions here.
https://support.steampowered.com/kb_article.php?ref=3330-iagk-7663


text:
Q: error TS2307: Cannot find module 'rxjs/Operators' Azure DevOps Angular 8
Please have a look at this image.
I'm trying to setup Azure DevOps for .Net core project with Angular, but while in the publish step it throws an error "error TS2307: Cannot find module 'rxjs/Operators'" even though it works locally with successful publish, once the pipeline job runs it gives this error. Using the latest version of rxjs with Angular 8.

A:
error TS2307: Cannot find module 'rxjs/Operators' Azure DevOps Angular 8

This is a common error, we can find the solution in a simple web by searching the key words "error TS2307: Cannot find module 'rxjs/Operators".
The solution for this error is that the O in Operators in the import statement should be in small case operators.
Generally, by default, Mac/windows file system are case insensitive.
Hence, the following line in a Typescsript file,
import { switchMap } from 'rxjs/Operators/switchMap';

would not throw any error if you build the Angular project with command ng build --prod on Mac/windows OS.
But if you run the same project on Linux, it is likely to throw that error.
You could check this thread for some more details.


text:
Q: Move an input into a form using Javascript I am trying to move an element inside a form and then change the display to block. I am getting the display to change but can't seem to move it, this is the code I am using
<form action="testsubmit.php">

    <input type="submit" value="submit">
</form>

<input type="text" name="test" id="input1">

<button onclick="test()">Click me</button>

A: the insertion  has to be done in the other way round
document.getElementById('placehere').appendChild(
     document.getElementById('input1')
);

The DOM insertion via appendChild() is in fact <parentNode>.appendChild(<node>)
Then, to show the element javascript is not necessary. just hide the input by default via CSS, and show it when it is inside the form element
#input1 { display: none }
#placehere #input1 { display: block }

A: Have you tried:
     document.getElementById('placehere').appendChild(document.getElementById('input1'));

A: Try this code
<form action="testsubmit.php">

    <input type="submit" value="submit">
</form>

<input type="text" name="test" id="input_text">

<button onclick="test()">Click me</button>


text:
Q: Unit testing realistic Android classes. Test environment, the lifecycle, and responses There seems to be no end to the number of posts discussing how to unit test completely unrealistic things.
An abundance of tutorials, videos etc outline what unit tests are and how you do them. There do not however seem to be many (if any) resources which outline how to test something real.
After all.. in reality the 'units' that we are testing are generally significantly more complex than a method taking inputs and giving an output.
I am working with Android at the moment and was investigating how to unit test my application.
My application is essentially made up of views and server requests. You click button x and it changes the view displayed. You click button y and it loads data from the server and populates a list.
Below is some source code. I have essentially pieced together an example setup which demonstrates the things that are confusing (to me). The things that I find conceptually difficult to unit test.
public class ChainActivity extends FragmentActivity {

private PRFragmentTabHost mTabHost;

public GetChainResponse.Data responseData;

Integer chainId; //ref to chain we are getting - passed in

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Get the chain id we are getting
    Bundle extras = getIntent().getExtras();
    chainId = extras.getInt("chainId");

    setContentView(R.layout.activity_base);

    //Set up the tabs
    mTabHost = (PRFragmentTabHost) findViewById(android.R.id.tabhost);

    mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("Details").setIndicator("Details", null), ChainDetailsFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("Pictures").setIndicator("Pictures", null), PicturesFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("Cats").setIndicator("Cats", null), CatsFragment.class, null);

}

@Override
public void onStart() {
    super.onStart();

    //Initiate the data load
    loadChainData();
}

//Method loads the chain data
public void loadChainData(){

    PRAPIInterface apiService = ApiService.getInstance();

    Integer limit = 4;

    apiService.getChain(chainId, limit, new Callback<GetChainResponse>() {

        @Override
        public void success(GetChainResponse pr, Response response) {

            lastData = System.nanoTime();

            //Save the response data
            responseData = pr.data;

            //Get the current tab and pass the loaded data to it
            String currentTabTag = mTabHost.getCurrentTabTag();
            DataLoadedInterface currentTab = (DataLoadedInterface) getSupportFragmentManager().findFragmentByTag(currentTabTag);
            currentTab.dataLoaded(responseData, false);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            // Log error here since request failed
            Log.w("Failed", "Failed" + retrofitError.getUrl());
            Log.w("Failed", "Failed" + retrofitError.getBody());
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Fragment fragment = getSupportFragmentManager().findFragmentByTag(mTabHost.getCurrentTabTag());

    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

}
So.. I am aware of Roboeletric, Robotium etc and other libraries that are available for testing on Android. I am however looking for conceptual advice.
Android provides ActivityUnitTestCase
I can subclass this and setup a test for my activity.
Part 1
In principle I could test my onCreate by verifying that mTabHost is not null BUT I don't want to make it publicly available, nor do I want to have a getter to its value.
I figured that I could test the existence of my fragments but i can in fact not. Because the activity runs in 'isolation' it seemingly does not actually create the fragments for the tabs.
Part 2
Next is onStart. This calls another method. It has no return value. I cant test a response.
It is however important that i test that onStart we load our initial data..
Within loadChainData I could set a Boolean indicating that I am loading data and verify this but a coworker could just set this Boolean to true by default and my test would pass.
Furthermore I don't want to test loadChainData 'again'.. I will be testing this method anyway. One idea that springs to mind is stubbing out loadChainData and verifying that it is called and leaving it at that. This however seems to be difficult to do with Android (anyone..?) and does not really fit with the sentiment that testing should be fun.
Part 3
loadChainData loads some data from the server using retrofit. Because in reality this method executes asynchronously there is again no response from this method. I have found an appropriate way of returning mock data by swapping out the retrofit client but doing this swapping is not apparently simple.
At the moment I use a singleton for my ApiService. I want to essentially replace what is built the first time this singleton is called. There are potential complex solutions for this like using a Dependency injection library (like Dagger) but given what I want to achieve I feel that there should be a much simpler way of doing this.
My initial thoughts are that if the application could be instantiated with say a test flag. The singleton would return the test client. Alternatively it would default to the real client. This in my mind smells a little.. could someone explain what the smell is, and how one could appropriately resolve it?
Even if the above was considered a fair suggestion there seems to be no easy way to actually do it with ActivityUnitTestCase.
Part 4
Finally is onActivityResult.
Again, there is no response.
This time the method in question interacts with other units elsewhere. Units that act differently within the constraints of ActivityUnitTestCase anyway.
I could wrap my manipulation of the support fragment manager, mock my wrapper, return a mocked fragment, verify that its onActivityResult method is called.. but again this seems incredibly tough to do. Furthermore this adds complexity to my code to allow something to be testable. I have no interest in increasing complexity just to test..
So..
Does anyone with real experience unit testing on mobile have any insight on how to appropriately tests a class such as this one. As you can see it is not really a case of  'put 2 in, does 4 come out' :)
A lot of resources mention how testing is underdone. This is why :) Any advice would be greatly appreciated.
T

A: onCreate
I would test in two ways, one using some form of AndroidTestCase this would allow the testing of extras you send in the Bundle.
( I would add error handling to throw an error if the extra is not present )
( I would change loadChainData() to take chainId as a paramater )
To test your tabs are instantiated correct I would use espresso for an Acceptance test to validate your views are present.
onStart
There is no Dependency Inversion here and so you cannot test the service methods are called. You would want to test getChain is called. What happens when you create that service, could you do it in the constructor?
 ( I would move away from the Activity here and encapsulate all behaviour from onStart in some other class [perhaps MVC could help] that way you aren't constrained by the lifecycle.
 ( I would also add another layer of callback's on top of Volley in to the Activity, that way you can test your listeners return the correct success or failure, but you don't have to worry about the tabs [the activity ui]).
If you really wanted to test asynchronisity (which I wouldn't advise) you can use Espresso and that can help you manage the test to still get callbacks see custom resource idoling.
onActivityResult
I believe using Robolectric you could pass it a Mockito mock fragment manager in order to return you a stub fragment and validate the behviour of the  the fragment tab host, then you would call onActivityResult yourself: whether testing this actually gives you any benefit is another question.
Overall testing lifecycle methods is like testing anything else, for it to be testable you need to abstract away any ideas of threading, you need to be in control of your dependencies and I find the closer you adhere to SOLID the easier testing is. In the wake of these stumbling blocks, this is why Robolectric, InstrumentationTests and Espresso where created.
In summary sorry, there is no straight forward answer here, you have to ask yourself - do I get any benefit from testing these things, am I testing my code or am I testing the framework, what is the cost benefit of testing this Activity does it actually encumber future changes rather than gain me confidence.


text:
Q: Delete a project from VS code How do I delete a project in Visual Studio Code?
I've clicked everywhere looking for a solution. I have cleared the recently opened, restarted VS Code but the project doesn't go anywhere. I researched online but there is a void. It seems projects stay there forever!
Any help would be great. Thanks.

A: If you want to delete the project, you can not delete it from inside the VS Code. you should go to the folder that project is inside that, you can do that with right click on the name of project in toolbar VS Code and select the Reveal the explorer and go directly to the root of the project.
then you can delete the project.
I hope it helps you.

A: You would need to use the command pallete and search for
Workspaces: Remove Folder from Workspace...

A: 'File' >> 'Close Folder' removes the project from the explorer sidebar without actually deleting from the disk.

A: You can use 'Close Workspace' from command pallete, this will close the workspace from VS Code keeping all the files on the disk.
Close project in VSCode


text:
Q: edit two parts of text document python Similar to my recent question asked:
I have a text file contain some data using this piece of code
def Add_score():
    with open("users.txt") as myFile:
        for num, line in enumerate(myFile, 1):
            if name in line:
                line_found = num
                break

It finds the line that has a specific name. The line would look like this.
Name: whatever Username: whatever password: whatever score: 25 goes: 3
I need to be able to add number to score as well as goes
Change 3 to 4 and change 25 to 26

A: Here you are:
line = 'Name: Username: password: whatever score: 25 goes: 3'
print(line)
lineSplitted = line.split()
print(lineSplitted)
updatedLine = " ".join(lineSplitted[0:5] + [str(int(lineSplitted[5])+1)] + [lineSplitted[6]] + [str(int(lineSplitted[7])+1)])
print(updatedLine)

prints:
Name: Username: password: whatever score: 25 goes: 3
['Name:', 'Username:', 'password:', 'whatever', 'score:', '25', 'goes:', '3']
Name: Username: password: whatever score: 26 goes: 4


text:
Q: Pass a parameter to existing onClick JS function Very basic question, but how can I add/populate a parameter to the onClick function of an HTML element?
Some function

//PSEUDO CODE
var someFunctionParam = document.getElementById('testLink');
someFunctionParam.addParameter(someParam);

Obviously "addParameter" isn't a valid method in Javascript, can anyone guide on how to do so?

A: The best way in my opinion is to rewrite you JS to something like this:
Some function

function aNewFunction() {
  // Invoke your existing function here;
  someFunction();

  //PSEUDO CODE
  var someFunctionParam = document.getElementById('testLink');
  someFunctionParam.addParameter(someParam);
}

A: Best way I would think of is
$(function () {
    var parameter='Joe Root';
    var functionName = $('#testLink').attr("onclick");
    $('#testLink').attr("onclick",
    functionName.replace('()', "('" + parameter + "')"));
    alert($('#testLink').attr("onclick"));
});

function someFunction(name) {
    alert("Hi " + name);
}

As, you can see, this works http://jsfiddle.net/hXpSN/1/


text:
Q: How to check if validation fails while saving data in sharepoint spservice I am using following code to save items in sharepoint.
 $().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "Share Point List",
valuepairs: [["Title", fnameVal], ["LastName", lnameVal], ["Gender0", genderVal], ["DateOfBirth", birthDateVal], ["Email0", emailVal], ["City", cityVal], ["Country", countryVal]],
completefunc: function (xData, Status) {
alert("Data Saved! and Please check your List");
}
});

It works perfectly when data is saved but when it don't save for some validation I still get the alert message. How can I check if validation failed and for which fields validation failed?

A: Your answer is in this SPServices forum post: http://spservices.codeplex.com/discussions/393036
I believe Marc has an issue open to add the methods I posted in that thread to SPServices in some future release.


text:
Q: Python | Reading JSON files and applying simple algorithm on each iteratively into a dataframe we have a large json file that takes too long to be read with pd.read_json.
What we want to do initially is :
# Load the file
df_view = pd.read_json('/path/to/file', lines=True)

# Create a new feature using the above dataframe
df_nb_view = df_view[['userid','itemid']]
df_nb_view = df_nb_view.groupby('userid').count()
df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)

So I've divided the dataset into subsets of it in one folder, and would like to read iteratively into it so as to do the work above on each subset, and concatenating the result at each step.
Hope this is clear enough.
I started out with this so as to read each file into one final df, but not sure how to create the new features in the process.
files = []
for file in os.listdir("/path/to/folder"):
    if file.endswith(".json"):
        files.append(os.path.join("/path/to/folder", file))

for file in files:
    with codecs.open(file,'r','utf-8') as f:
        df_view = json.load(f, encoding='utf-b')

Thanks a lot in advance.

A: If I understand correctly, you want to read and process in file chunks.
If so, create a final result dataframe and append to it in each iteration
final_df = pd.DataFrame()

for filename in files:
    df_view = pd.read_json(filename, lines=True)
    df_nb_view = df_view[['userid','itemid']]
    df_nb_view = df_nb_view.groupby('userid').count()
    df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)

    final_df.append(df_nb_view)


text: Q: Limits of $f$ in this formula By integration by parts: $$\int u dv=uv-\int vdu$$ Now I used this to create a clever little formula: $$\int f(x)dx=-\sum^\infty_{k=1} \frac{(-x)^k}{k!}f^{(k-1)}(x)$$ I did this by setting $u=f(x)$ and $v=1$: $$\int f(x)dx=xf(x)-\int xf'(x)dx$$Then we set $u=f'(x)$ and $v=x$: $$\int f(x)dx=xf(x)-\int xf'(x)dx=xf(x)-\frac{x^2}{2}f'(x)+\int\frac{x^2}{2}f''(x)dx$$And so on. Now I decided to test this formula. It worked for $f(x)=x$ but not $f(x)=x^{-1}$. What are the limitations for $f$? I found two: It's derivative must be continuous and the sum above must converge $\forall x\in\mathbb{R}$. Are there any others?


text:
Q: Android Camera2 API - lack of privileges on resume I'm developing the app using Camera2 API. My problem looks like that:
 when I hit the device's sleep button while the camera fragment is working and after that I wake up the device, the application restarts
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime: FATAL EXCEPTION: main
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime: Process: com.snapsportz.nexus5camera.app, PID: 5081
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime: java.lang.RuntimeException: Unable to pause activity {com.snapsportz.nexus5camera.app/com.snapsportz.handheldcamera.app.CameraActivity}: java.lang.SecurityException: Lacking privileges to access camera service
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3381)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3340)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4047)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.-wrap15(ActivityThread.java)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:  Caused by: java.lang.SecurityException: Lacking privileges to access camera service
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.hardware.camera2.utils.CameraBinderDecorator.throwOnError(CameraBinderDecorator.java:108)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.hardware.camera2.utils.CameraBinderDecorator$CameraBinderDecoratorListener.onAfterInvocation(CameraBinderDecorator.java:73)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.hardware.camera2.utils.Decorator.invoke(Decorator.java:81)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at java.lang.reflect.Proxy.invoke(Proxy.java:393)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at $Proxy1.cancelRequest(Unknown Source)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.hardware.camera2.impl.CameraDeviceImpl.stopRepeating(CameraDeviceImpl.java:899)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.hardware.camera2.impl.CameraCaptureSessionImpl.close(CameraCaptureSessionImpl.java:373)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.snapsportz.handheldcamera.app.Camera2BasicFragment.closeCamera(Camera2BasicFragment.java:899)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.snapsportz.handheldcamera.app.Camera2BasicFragment.onPause(Camera2BasicFragment.java:771)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.Fragment.performPause(Fragment.java:2379)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1130)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.FragmentManagerImpl.dispatchPause(FragmentManager.java:1967)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.FragmentController.dispatchPause(FragmentController.java:185)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.Activity.performPause(Activity.java:6346)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1311)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3367)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3340)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4047)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.-wrap15(ActivityThread.java)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
12-10 10:59:10.423 5081-5081/com.snapsportz.nexus5camera.app E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I believe that it's not a lack of camera permission in manifest file because it is included in it and the app works fine unless I try to wake it up.
I'll be really glad for any hint.

A: If you used the Google Camera2Basic Sample App - issue #42 seems to describe the problem. The solution is to review your use of onResume method in your Fragment - and call closeCamera() before you call openCamera() in the onResume().  Seems to fix the problem in my testing of Camera2Basic.

A: Usually, It's because you didn't stop the camera device.
I solved this in onPause/onResume activity override methods:
@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "onResume");
    ...
    openCamera();
    ...
}
@Override
protected void onPause() {
    Log.e(TAG, "onPause");
    closeCamera();
    super.onPause();
}

This worked for me.
Regards.-


text:
Q: Change preset settings in OS X print dialog (Canon iR-ADV 2030i) I'm using OS X 10.9. I need to change some of the advanced printer settings in the presets dialog (the printer is Canon ImageRunner Advance 2030i). In this case I'd like to change the 'print style' setting under 'finishing' but I have no clue what to do to make the actual change happen. I tried clicking in combination with various keys but the setting still seems to be displayed as read-only (see screenshot). What should I do?

A: I have no idea how to do this via the UI but you can go to ~/Library/Preferences and look for com.apple.print.custompresets.forprinter.*.plist (where * stands for your printer name). The file only exists if you created a custom preset.
You can open the plist with Xcode and edit all printer settings.


text:
Q: How to extract information and transform true to 1? I got this code :
foreach($data['matches'] as $matches){
$win += $matches['participants'][0]['stats']['winner'];
if ($win == true){
$winner+= '1';
}
}

This code extract information from an API, and what I want is how much the value "true" is in the API, soo I've tried to convert "true" to 1, but still not working well.
In the api there are 8 "true" but when I've tried to print $winner I got just 2.

What to do please to correct the code ?

A: Just make  $win = $matches['participants'][0]['stats']['winner']; and then if $win is equal to true increment $winner.
$winner = 0;

foreach($data['matches'] as $matches){
$win = $matches['participants'][0]['stats']['winner'];
if ($win == true) {
$winner++;
}
}


text:
Q: DELETE and INSERT - is this simple query statement sufficient to preserve atomicity? I intend to update a table by going for a DELETE then INSERT on postgres in a single query. Obviously I want the DELETE to only take place if the INSERT is successful, i.e. preserve atomicity.
Is writing the query as below, sufficient for this?
DELETE FROM table_one WHERE some_id = 1;
INSERT INTO table_one(col1, col2, col3) VALUES (val1, val2, val3), (val4, val5, val6), ...

Thank you very much.
EDIT:
After reading around, I believe I am supposed to use transactions. Is this correct?
BEGIN;
DELETE FROM table_one WHERE some_id = 1;
INSERT INTO table_one(col1, col2, col3) VALUES (val1, val2, val3), (val4, val5, val6), ...
COMMIT;

So if DELETE fails, then the entire transaction fails?

A: Yes you can use transactions.
And yes if one of transaction statements fails all of it will rollback. Meaning : Nothing will happen or everything will be done.

Your code :

BEGIN;
DELETE FROM table_one WHERE some_id = 1;
INSERT INTO table_one(col1, col2, col3) VALUES (val1, val2, val3), (val4, val5, val6), ...
COMMIT;

See following link for more information about transactions: Transactions in PostgreSql


text:
Q: Padding between 2 columns with affect padding elsewhere I have made a row with 2 columns. Between there 2 columns there is a padding on 30px. I need that to be 10px. See a live example on bootply.com here.
In the core bootstrap, the class "col-sm-4" has a padding-left and padding-right set to 15px, so therefore 30px. The problem for me now, is that I need to keep the 15 px on the left and right side of the columns.
How can I make the padding smaller between the 2 columns, without it is affecting the padding on the left and right side?

A: You can overwrite the padding-right for the col-sm-4 to 7.5px and the padding-left for the col-sm-8 to 7.5px.
Here is a codepen example.
However, you want to be careful as overwriting Bootstrap classes on a large website may affect other pages/sections. If you can, you want to add some extra classes to your divs(something like col-sm-4 and small-right-padding and col-sm-8 and small-left-padding).
so you can have these rules:
.small-padding-left {
    padding-left:7.5px;
  }

  .small-padding-right {
    padding-right:7.5px;
  }


text:
Q: What is memory pressure, and how do I relieve it? I have had my machine for more than a year now, and I'm looking at Memory Pressure in the Activity Monitor.
What is this memory pressure and How do I "relieve" this memory pressure from my system?
I've done reboots, and it shows clear for a while, but eventually builds back up.

A: Memory Pressure is a better indicator of the health of the virtual memory system than the traditional UNIX measure of free, inactive and active pages.
For a brush up on the previous measure, have a read at:

*

*Isn't Inactive memory a waste of resources?
Now, the caching of files is drawn as a good thing (green memory pressure) and you will only see the pressure raise in the main window of Activity Monitor when you have a large proportion of wired memory or the system starts swapping RAM to storage and evicting too many cache pages.
The image from your window looks perfectly fine - so I wouldn't worry about reducing the pressure. If you want to reduce the pressure, you can do so by quitting apps and then letting the system manage that memory. If your Mac can accommodate more RAM, adding RAM would reduce the pressure for the same line up of programs running and using memory.

A: Here's what Apple says the graph means:
https://support.apple.com/en-us/HT201464

*

*Memory Pressure: The Memory Pressure graph helps illustrate the
  availability of memory resources. The graph moves from right to left
  and updates at the intervals set in View > Update Frequency. The
  current state of memory resources is indicated by the color at the
  right side of the graph:

*

*Green: Memory resources are available.

*Yellow: Memory resources are still available but are being tasked by
  memory-management processes, such as compression.

*Red: Memory resources are depleted, and macOS is using your startup
  drive for memory. To make more RAM available, you can quit one or
  more apps or install more RAM. This is the most important indicator
  that your Mac may need more RAM.


text:
Q: Jmeter JDBC Connection Configuration Parametrization of Database URL for accessing SQL Database Anyone knows how to parametrize Database URL under JDBC Connection Configuration.

Database URL: jdbc:sqlserver://ovh-sql1:1433;DatabaseName=user_1
  JDBC Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver

I want to parametrize DatabaseName=user_1
Normal parametrization is not working here. Please suggest.

A: You can use variable for database name and configure it.
Here is the example:
Database URL: jdbc:mysql://${mysql_hostname}:${mysql_port}/${mysql_database}
JDBC Driver Class: com.mysql.jdbc.Driver
Username: ${mysql_username}
Password: ${mysql_username}


text:
Q: Is there a .NET default AND common values reference I already know there's Default Values Table as well as it's relatives.
However, it'd be nice to have a printable chart which shows:

*

*default values table

*Min/Max for built-in numerics (including TimeSpan and DateTime)

*Other useful math numbers (e.g. PI = 3.14159265358979323846)

*Maybe some 2^N = ...

Does such a thing exist?

A: it exists for C++ see here .
In the math class of .NET as you ask there are two: E and PI, see here.

A: xlsx (source)
pdf (for printing)


text:
Q: Field of a structure changing randomly and i cant find the issue #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#define MAX_LINE  80

int historyLength=10;
int currentNumberOfHistoryElements=0;
int currentCommandNumber=1;
int notDone=1;
size_t n=MAX_LINE;

struct pastCommand
{

    char *command;
    char *commandslist[10];
    int commandlistLength;
};

void addNewHistory(struct pastCommand *newHistory,struct pastCommand *historyList[])
{
    char *look = newHistory->command;
    printf("HEREsad %s\n",look );
    if(currentNumberOfHistoryElements<historyLength)
    {
        for(int i=0; i<historyLength; i++)
        {
            if(historyList[i]==NULL)
            {
                historyList[i]=newHistory;
                currentNumberOfHistoryElements++;
                break;
            }
        }
    }
    else
    {
        for(int i=0; i<historyLength-1; i++)
        {
            historyList[i+1]=historyList[i];
        }

        historyList[0]=newHistory;
    }
}

void printHelp()
{
    printf("List of Commands:\n Verbose[on|off]: shows info as commands called \n help: what you are looking at right now\n history: the past 10 commands you have entered\n quit: quit the program\n");
}

void printHistoryElement(struct pastCommand *currentHistory, int number)
{
    if(currentHistory==NULL)
    {

    }
    else
    {
        int myLength=currentHistory->commandlistLength;
        char *myCommand=currentHistory->command;
        printf("LOOKIE %s\n",myCommand);

        printf("Commands #%d: %s\n",number, myCommand);
        for(int i=0; i<myLength; i++)
        {

            printf("arg[%d] :%s\n",i,currentHistory->commandslist[i]);
        }
        printf("\n");
    }
}

void printHistory(struct pastCommand *allHistories[],int length)
{
    for(int i=0; i<length; i++)
    {
        printHistoryElement(allHistories[i],i);
    }
}

void freeHistoryList(struct pastCommand *allHistories[])
{
    for(int i=0; i< historyLength; i++)
    {
        if(allHistories[i]!=NULL)
        {
            free(allHistories[i]);
        }
    }
}

void runProgram()
{
    struct pastCommand *allCommands[historyLength];
    for(int i=0; i<10; i++)
    {
        allCommands[i]=NULL;
    }
    char* buf = (char*) malloc(sizeof(char) * MAX_LINE);

    while(notDone)
    {
        printf("mish[%d]> ",currentCommandNumber);

        int result=getline(&buf, &n, stdin);
        if(result==-1)
        {
            printf("\n");
            exit(EXIT_FAILURE);
        }
        else
        {
            strtok(buf,"\n");
            if(strcmp(buf,"help")==0)
            {
                printHelp();
                struct pastCommand *current=malloc(sizeof(struct pastCommand));
                current->command=malloc(sizeof(buf));

                current->command=buf;
                printf("%s\n",current->command );
                current->commandlistLength=0;
                addNewHistory(current,allCommands);
                printf("HIT IT\n");
            }
            else if(strcmp(buf,"quit")==0)
            {
                free(buf);
                freeHistoryList(allCommands);
                exit(EXIT_SUCCESS);
            }
            else if(strcmp(buf,"history")==0)
            {
                printHistory(allCommands,currentNumberOfHistoryElements);
            }
        }

        currentCommandNumber++;
    }
}

int mish_command_name(int argc, char *argv[])
{
    return 0;
}

int main(int argc, char *argv[])
{
    runProgram();
    return 0;
}

Overall the issue is I'm keeping a history of commands that are to be run. When I type help, it works fine and I see help is added to the history list with the command name help. However, when I type history to show it, the command name which is being printed changes to history which is really weird.
I tried to debug as you can see from the code and I have no idea how the field variable for the structure is changing from help to history. If I type help like 5 times, then type history, all the command names have the name history.
Some insight would be incredibly helpful.

A: There is a problem with:
current->command=buf;

buf is the buffer allocated by getline, however that function will re-use its buffer each time (and maybe even free it if it needed to reallocate), so it is not a good idea to have your commands point to that buffer. You should malloc new space for each command.
It looks like you tried that with:
current->command=malloc(sizeof(buf));

however (as well as mallocing the wrong number of bytes) you never actually use that malloc'd space, you just pointed current->command at buf immediately after.
Try replacing both lines with:
current->command = strdup(buf);


text:
Q: code causing a 1004 error and im not sure why So i have this string of code that should let me auto highlight rows and columns of active cells... The catch is it is popping a 1004 error and I'm not sure why. Possibly in the syntax?
It flags the ".colorindex=20"
Im running excel 2010
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static rr
Static cc

If cc <> "" Then
    With Columns(cc).Interior
        .ColorIndex = xlNone
    End With
    With Rows(rr).Interior
        .ColorIndex = xlNone
    End With
End If

r = Selection.Row
c = Selection.Column
rr = r
cc = c

With Columns(c).Interior
    .ColorIndex = 20
    .Pattern = xlSolid
End With
With Rows(r).Interior
    .ColorIndex = 20
    .Pattern = xlSolid
End With
End Sub

A: you have to add :
Dim r, c

the code:
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static rr
Static cc
Dim r, c

If cc <> "" Then
    With Columns(cc).Interior
        .ColorIndex = xlNone
    End With
    With Rows(rr).Interior
        .ColorIndex = xlNone
    End With
End If

r = Selection.Row
c = Selection.Column
rr = r
cc = c

With Columns(c).Interior
    .ColorIndex = 20
    .Pattern = xlSolid
End With
With Rows(r).Interior
    .ColorIndex = 20
    .Pattern = xlSolid
End With
End Sub

A: Solved... had to edit the colors in this format. and then she ran... my only catch to it is it is now reformatting the colors I already have on the sheet.
Is there a work around to that from the original code to where it highlight but doesnt reformat?
With Columns(c).Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 10937227
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
With Rows(r).Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 10937227
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
End Sub


text:
Q: $D_{2n}$ Acting on the set consisting of Opposite Pairs of Vertices of a regular n-gon I have been asked to show that $D_{2n}$ acts on the set consisting of pairs of opposite vertices of a regular $n$-gon, where $n$ is taken to be a positive even integer.
The first thing that came to my mind was to represent $r$ and $s$ in cycle notation, i.e., to show that $D_{2n}$ is isomorphic to a certain subgroup of $S_n$, and then I can show that permutations acting the two element sets of opposite vertices is a group action of $D_{2n}$ on them. More specifically, if $\sigma$ is a permutation and $\{v_1,v_2\}$ is a set consisting of opposite vertices, then I would show $\sigma\cdot \{v_1,v_2\} := \{\sigma(v_1), \sigma(v_2) \}$ is a group action.
So, $r \mapsto (1~2~...~n)$ and $s \mapsto (2~n)(3~(n-1))~...?$.
There are a few things I am having difficulty with: (1) will this argument succeed; (2) how do I make the arguments more rigorous; (3) how do I determine exactly what $s$ gets mapped to; and (4), given an arbitrary vertex, what will its opposite vertex look like (in other words, what does the set $\{v_1,v_2\}$ look like)?
Note, more questions may come.

A: Define the set consisting of pairs of opposite vertices of a regular n-gon as $A$. By the
definition of group action, we need to show any $h, g \in D_{2n}$,$ a \in A, g · a \in A, 1 · a = a,$
$h · (g · a) = (gh) · a.$
Since $1$ doesn't make any change to the n-gon, thus $1 · a = a,$ for any $a \in A$.
And any element of $A$ is a combination of $s, r,$ thus in order to show $g · a \in A,$ we just need to show $s · a \in A, r · a \in A.$ We may define the vertices clockwise as $0, 1, 2, ..., n − 1$
Let the $\frac{n}{2}$ pairs of opposite vertices defined to be $a_i:= \{i, i + n/2\}, 0 ≤ i < n/2$.
If we define $r(j) = j − 1\mod n$ with $0 ≤ j ≤ n − 1$, then we get $r(i) = i − 1,$ if $i ≥ 1 $and $r(0) = n − 1$.Then to any pair $(i, i + n/2)$ with $0 < i < n/2, r(i) = i − 1, r(i + n/2) =i − 1 + n/2, $i.e. $r(i, i + n/2) = (i − 1, i − 1 + n/2) = a_{i−1} \in A$
Thus we can conclude that $r(a_i) = a_{i−1} \mod \frac{n}{2}$
And we define the reflection is about the line connecting vertices $0, 3,$
thus $s(j) = −j \mod n,$ thus to any $a_i, s(i) = −i \mod n = n − i, s(i + n/2) = n/2 − i,$thus $s(a_i) = (n/2 − i, n − i) = a−i \mod n/2$. Thus we have proved s · $a \in A$, $r · a \in A$ for any $a \in A$, therefore $g · a \in A$, for any $g \in D_{2n}, a \in A.$
Since any $g \in D_{2n}$ is in the form of $r^is^j$
, we just need to show $(r^as^b) · ((r^xs^y) · ai) =((r^as^b)(r^xs^y)) · a_i$
. Indeed, by computation, we can get
$((r^as^b)(r^xs^y)).a_i=(r^{a+(-1)^bx}s^{b+y}).a_i= a_{-1^{y+b}i + (-1)^{b+1} x-a \mod n/2}=r^as^b.a_{-1^yi-x \mod n/2}$ .Thus it is an action
since $r^xs^y.a_i= a_{-1^yi-x \mod n/2}$
Thus if $r^xs^y.a_i=a_i$ then$ x= n/2 ,0.y=0 $,
if $y = 1$ then $x$ depend on $i $, thus if $ r^xs^y.a_i=a_i $ for any$ i$ ,then$ y=0 , x= n/2, 0$.so kernel is $\{r^0=1, r^{n/2}\}$


text:
Q: what is the alternative of javaScriptWindowObjectCleared() on new qt 5.10 ?javaScriptWindowObjectCleared is not recognized on qt 5.10 Please help I want to port webkit to WebEngine but I have some problems with that, I have a signal javaScriptWindowObjectCleared() which is not recognized by new qt 5.10. What can help me in this case?
connect( this->page(), SIGNAL( javaScriptWindowObjectCleared() ), SLOT( OnPopulateJavaScriptObjec() ) );

A: The following code sinppet may help you.
    QWebEngineScript toBeInjectedjs;
    toBeInjectedjs.setName("qwebchannel.js");
    toBeInjectedjs.setInjectionPoint(QWebEngineScript::DocumentCreation); //important
    toBeInjectedjs.setRunsOnSubFrames(false);
    toBeInjectedjs.setWorldId(QWebEngineScript::MainWorld);
    toBeInjectedjs.setSourceCode(jsStr);  //jsStr is what your want to inject to page;
    scripts().insert(toBeInjectedjs); //scripts is a member function of QWebEnginePage.


text:
Q: How to read time in HH:MM:SS format in Java? I am trying to read time in HH:MM:SS format. I tried this but it resulted in java.util.InputMismatchException
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
sc.next();
int m = sc.nextInt();
sc.next();
int s = sc.nextInt();
System.out.println(h+":"+m+":"+s);

A: You're using the default token delimiter, which is whitespace. So nextInt() tries to parse the whole date string and fails. Just add the colon as a delimiter, and skip the extraneous next() calls:
Scanner sc = new Scanner(System.in);
sc.useDelimiter(":|\\s+");
int h = sc.nextInt();
int m = sc.nextInt();
int s = sc.nextInt();
System.out.println(h+":"+m+":"+s);

A: I would prefer to use Java's standard LocalTime class for this:
    DateTimeFormatter parseFormat = DateTimeFormatter.ofPattern("H:mm:ss");
    Scanner sc = new Scanner(System.in);
    String timeString = sc.nextLine();
    LocalTime time = LocalTime.parse(timeString, parseFormat);
    System.out.println(time);

No need to reinvent the wheel.
If I enter 9:05:30, the output is 09:05:30. If you prefer the output without the leading 0, just format it back to a string with the same DateTimeFormatter:
    System.out.println(time.format(parseFormat));

If you need your variables h, m and s, get their values from the LocalTime object:
    int h = time.getHour();
    int m = time.getMinute();
    int s = time.getSecond();

LocalTime.parse() will throw a DateTimeParseException if the entered string is not a valid clock time. You may want to catch this and act accordingly (for example, print an error message and ask the user to try again).

A: You need to use sc.nextLine to treat the whole thing as a string. After that you search for the ':' with indexOf, and then get your separeted numbers. You can't use nextInt because java will expect integers separeted by spaces not together with ':'


text:
Q: How to use C++ /WinRT HttpRequestMessage with Custom POST Body and HttpFormUrlEncodedContent (UWP App) In Windows 10, 1803 it is possible to call the WinRT from standard conforming C++. The C++ /CX language extensions are not required anymore.
I already know how to send a post Request to a Server using the HttpRequestMessage Class:
#pragma comment(lib, "windowsapp")

#include "pch.h"
#include "winrt/Windows.Web.Http.Filters.h"
#include "winrt/Windows.Web.Http.Headers.h"
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <string_view>

using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Web::Http;
using namespace Windows::Web::Http::Filters;
using namespace Windows::Web::Http::Headers;
using namespace Windows::Foundation::Collections;
using namespace std::literals;
using namespace std;

IAsyncAction HttpClientExample(Uri uri)
{
    HttpBaseProtocolFilter filter;
    HttpClient httpClient(filter);
    HttpRequestMessage loginRequest(HttpMethod::Post(), uri);

    try
    {

        auto response{ co_await httpClient.SendRequestAsync(loginRequest) };
        HttpCookieCollection cookieCollection =     filter.CookieManager().GetCookies(uri);
        wcout << cookieCollection.Size() << L" cookies found." << endl;

        for (HttpCookie cookie : cookieCollection) {
            wcout << L"Name: " << cookie.Name().c_str() << endl;
            wcout << L"Domain: " << cookie.Domain().c_str() << endl;
            wcout << L"Path: " << cookie.Path().c_str() << endl;
            wcout << L"Value: " << cookie.Value().c_str() << endl;
        }
    }
    catch (winrt::hresult_error const& ex)
    {
        // Details in ex.message() and ex.to_abi().
    }
}

int main() {

    init_apartment();

    Uri uri{ L"http://www.google.com/"sv };

    HttpClientExample(uri);

    Sleep(10000);
}

How do i set a Custom Header using HttpFormUrlEncodedContent and how do i set custom content in the POST Body?
Thank you for your help!


text:
Q: can we run node js child process with code instead of file or command? I have a situation, in which I want to run some code (some call to API), in child process. So, can we run code in a child process instead of file or command ? -- old
Now I have used this code:
process = require('child_process');
                var ls = process.spawnSync('node','lookUp.js ' + serialNumber);
                ls.stdout.on('data', function(data) {
                 console.log('stdout: ' + data);
                });

And received this erroe :

child_process.js:1254
  for (i = 0; i < options.stdio.length; i++) {
                               ^
TypeError: Cannot read property 'length' of undefined
    at Object.spawnSync (child_process.js:1254:32)
    at /home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/service2.js:252:22
    at Object.whilst (/home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/node_modules/async/dist/async.js:4578:9)
    at Request._callback (/home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/service2.js:211:10)
    at Request.self.callback (/home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/node_modules/request/request.js:200:22)
    at Request.EventEmitter.emit (events.js:110:17)
    at Request.<anonymous> (/home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/node_modules/request/request.js:1067:10)
    at Request.EventEmitter.emit (events.js:129:20)
    at IncomingMessage.<anonymous> (/home/eweba1-pc-22/htdocs/geoAdmin/myAdminTester/zohocrm-myadmin-module-to-get-devices/node_modules/request/request.js:988:12)
    at IncomingMessage.EventEmitter.emit (events.js:129:20)


text:
Q: which code is more efficient? calling twice a macro or just assigning macro to a variable and use it twice? From the below "C" code snippets which one is more efficient (1 or 2) and Why? Please shed some light on this. Thanks in advance!
//I am doing some operation with this macro.
 #define ERRMAP( sts ) ((A_AB( sts ) < FIRST_ERR) ? \
                         sts : \
                         ((A_AB( sts ) > A_AB( LAST_ERR )) ? \
                         sts : \
                         sts_to_errno_m[A_AB( sts ) - FIRST_ERR]))

    //Code snippet 1
       int some_fun (int sts) {

               int i = ERRMAP( sts );
               printf(" sts = %d", i);
               return i;
        }

    //Code snippet 2
        int some_fun (int sts) {

               printf(" sts = %d", ERRMAP( sts ));
               return (ERRMAP( sts ));
        }

A: Please don't worry about "most efficient" without having first done some sort of measurement that it matters.  Also "efficient" can mean many different things.  Efficient in terms of execution time?  Code size?  Memory usage?  "Efficient" is not a synonym for "fastest".
Rather than worrying about which is fastest, think about which way is clearest.  The most expensive time is programmer time.

A: Don't do this:
int some_fun (int sts) {
    printf(" sts = %d", ERRMAP( sts ));
    return (ERRMAP( sts ));
}

Someday if ERRMAP is modified to have a side-effect you'll get different results between what's printed and returned.
Also doing the calculation once is a good idea. This is best whether ERRMAP is a function or a macro: int i = ERRMAP( sts );

A: Presumably A_ABS is also a function like macro! The basic trick is to work it out in your head into pseudo machine code - lets say that A_ABS has a similar complexity and doesn't call any more things - then I would put each of them at about 20 op codes making a total of 40 - using them and assigning to a value then using that value twice would be 42 - while "calling" twice would be 80 so you work it out.
BTW - you should only even think about doing this sort of macro, (i.e. function like), if you have tried using a function and your profiler has said it is one of the main reasons that your code is either too big or too slow.  The reasons:

*

*Errors in macros are hard for the compiler to report the location of - you have 5 lines of up to 80 characters but any compiler errors will just be reported where you "call" the code.

*You are defeating type checking which is one of the major benefits of C/C++

*Debugging other than as machine code is impossible as you can not
step through a macro.

*It is a maintenance nightmare.

*Compiler optimisers will often not do well on it.

*Code checkers can not work well on macros

*MISRA and other compilence checkers will fail your code.

*It is usually unnecessary!


text:
Q: Parsing string arguments in tcl I am passing parameters to a function StcPortConfig as below:
 STC::StcPortConfig m:$port_b fc:1 pause_frame_rate:30 pause_val:"FFFF" mode:"gen";

In StcPortconfig function I need to parse different parameter values which I am doing as follows:
 proc ::STC::StcPortConfig {args} {

  foreach arg $args {
    regexp {([A-Za-z0-9_-]+):([a-z0-9,-_ ]*)} $arg match cmd value

 if {$cmd == "pause_frame_rate"} {
    set pause_frame_rate $value
    set pause_frame 1
  }
 if {$cmd == "mode"} {
    set mode $value
    puts "\nport is configured as $mode\n"
  }
}

I am able to read the value of pause_frame_rate (set to 30). But there is a problem in parsing string when I am reading "mode". The print statement is giving "port is configured as  ".
When I am reading the args, its printing like below:
      args are m:1 fc:1 pause_frame_rate:30 pause_val:\"FFFF\" mode:\"gen\"
I am missing something while trying to parse the parameters which are string and not integers/numerals.

A: You can use string trim to remove the quotes. An alternative implementation:
proc ::STC::StcPortConfig {args} {
    foreach arg $args {
        regexp {([\w-]+):(.*)} $arg -> cmd value
        set value [string trim $value {"}]   ; # remove double quotes
        switch -exact -- $cmd {
            pause_frame_rate {
                set pause_frame_rate $value
                set pause_frame 1
            }
            mode {
                set mode $value
                puts "\nport is configured as $mode\n"
            }
        }
    }
}

A: Instead of doing mode:"gen", I changed it to mode:gen and it works.


text:
Q: Can i do sonar scan on the Gerrit patch? As part of my precheckin workflow in Gerrit I want to configure sonarqube to perform scan on the submitted patch, I am using sonar-gerrit plugin in my Jenkins  and configured gerrit-trigger to run this analysis job. This job is configured with preview mode and runs analysis but the the analysis happens on the repository which doesn't include the submitted patchset.  How can i ensure to run the analysis on the patchset?

A: Use the "$GERRIT_REFSPEC" variable to configure your job like the following:


text:
Q: Suppress hints in the Delphi command-line compilers (dcc32.exe etc.) How do I suppress hints when using the Delphi command-line compilers? (I.e. dcc32.exe, dcc64.exe, dcclinux64.exe etc.)
I know that {$HINTS OFF} can be used in the source code to turn hints off, but its scope is local and affects only the code in the unit where is placed. I would want a global option that affects the whole compilation.
I also know that when compiling in the IDE, one can turn hints off globally in Project Options > Building > Delphi Compiler > Hints and Warnings > Output hints (True/False). I would need the same option in the command-line compilers.
Warnings can be suppressed using the -W-[WARNING] option, but is there anything similar for hints?

A: Running DCC32.EXE shows:

Hints are controlled using -H option

Show Hints (use -H+ or no option at all, as it is the default behavior):
D:\Tmp\TestHint>"C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\DCC32.EXE" -H+ "D:\Tmp\TestHint\Project1.dpr"
Embarcadero Delphi for Win32 compiler version 33.0
Copyright (c) 1983,2018 Embarcadero Technologies, Inc.
Project1.dpr(11) Hint: H2164 Variable 'Unused' is declared but never used in 'Project1'
Project1.dpr(20)
21 lines, 0.08 seconds, 118868 bytes code, 28648 bytes data.

Hide hints (use -H-):
D:\Tmp\TestHint>"C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\DCC32.EXE" -H- "D:\Tmp\TestHint\Project1.dpr"
Embarcadero Delphi for Win32 compiler version 33.0
Copyright (c) 1983,2018 Embarcadero Technologies, Inc.
Project1.dpr(20)
21 lines, 0.09 seconds, 118868 bytes code, 28648 bytes data.


text:
Q: How do I get the text that present under the matched string in tcl I have a string value in tcl as
set out " ABC CDE EFG
          123     456"

I want to get the text that is present below text "EFG".
As right now it is "456", but it can be anything so I need a way though which I can grep for "EFG" and get the text below it.

A: This answer takes some inspiration from Johannes Kuhn's answer, but I use regexp to get the word indices from the "keys" line.
# this is as close as I can get to a here-doc in Tcl
set out [string trim {
ABC DEF GHI
123     456
}]

# map the words in the first line to the values in the 2nd line
lassign [split $out \n] keys values
foreach range [regexp -all -inline -indices {\S+} $keys] {
    set data([string range $keys {*}$range]) [string range $values {*}$range]
}
parray data

outputs
data(ABC) = 123
data(DEF) =
data(GHI) = 456

A: I Suggest splitting the string into the keys and values with
lassign [split $out \n] keys values

and then look for the string position in the keys and get the same range in the values
set start [string first "EFG" $keys]
set value [string range $values $start [expr {${start}+[string length "EFG"]-1}]]

wraping it in a proc and we get
proc getValue {input lookFor} {
    lassign [split $input \n] keys values
    set start [string first $lookfor $keys]
    set value [string range $values $start \
        [expr {${start}+[string length $lookfor]-1}]]
}

invoke it like that:
getValue $out "EFG"

Edit: how is the 2nd line aligned? With a tabulator (\t), spaces?

A: In this case what you actually have is two lines with groups of 3 alphanumeric characters separated by spaces with a large amount of leading whitespace prefixing the second line ("\x20ABC\x20CDE\x20EFG\n[string repeat \x20 10]123[string repeat \x20 5]456" will reproduce what you posted). In your example [string range end-2 end] would give you what you need. I'd suggest reading the file line by line and each time you see the EFG, on the next line extract the part you need (maybe using string range) and emit it.
For example (untested):
set state 0
set f [open $inputfile r]
while {[gets $f line] != -1} {
    if {$state} {
        puts [string range $line end-2 end]
        set state 0
    } else {
        if {[string match "*EFG" $line]} { set state 1 }
    }
}
close $f


text:
Q: Calculus Question involving Error function The slope field for $F^{'}(x) = e^{-x^{2}}$ is shown here with a particular solution $F(0)=0$ superimposed. Using calculator, find
$$ \lim_{x \rightarrow \infty} F(x)$$ to $3$ decimal places.
Answer choices were
(A) $0.886$
(B) $0.987$
(C) $1.000$
(D) $1.414$
(E) $\infty$
The book says that answer is A, but I want to understand this.

A: It is well known that
$$\int_{0}^{\infty} e^{-x^2} \text{ dx} = \frac{\sqrt{\pi}}{2} = 0.8862269\dots$$
For instance see here: http://en.wikipedia.org/wiki/Gaussian_integral
or
Proving $\int_{0}^{\infty} \mathrm{e}^{-x^2} dx = \dfrac{\sqrt \pi}{2}$
So that explains why the answer is A.
Were you looking for some other explanation?

A: I am also curious what calculator is here for. We just need a crude idea of what $\int_0^\infty e^{-x^2}\,dx$ is. Note that $\int_a^{\infty}e^{-x^2}\,dx\le e^{-a^2}\int_0^\infty e^{-2at}\,dt=e^{-a^2}/(2a)$ and that $e^{-4}/4< 0.01$, so we really need only
$$
\int_0^2e^{-x^2}\,dx\approx \frac 13(1+4e^{-1}+e^{-4})\approx (1+\frac 4{2.7}+\frac 1{7.29})/3\approx \frac 13+\frac 12+\frac 1{22}=0.83333\dots+0.04545\dots\approx 0.878\dots
$$
Of course, Simpson is a slight underestimate here but for the multiple choice, it is perfectly suitable.
Of course, if you happen to know the exact value $\sqrt\pi/2$, the life gets completely trivial.


text:
Q: Fetching data from table and display in Bootstrap modal to edit I am trying to use Bootstrap modal for updating my data in database. But I'm getting an error
on my script in passing the data from my table to my modal. I use edit icon to triggered my modal to pop up but data from my table is not displaying.
this is my table:

this is the error I get whenever I try to fetch the data from my table and display to my modal to edit:

                School Year
                Status
                Action

            <?php
            if(mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_array($result)) {
            ?>

                <?php echo $row['school_year']; ?>

                    <?php

                     if($row['status'] == 1)
                    {
                    echo "<button class='btn btn-success' style='width:6rem !important; font-size:13px'>Active</button>";
                    }
                    else{
                    echo "<button class='btn btn-primary' style='width:6rem !important; font-size:13px'>Inactive</button>";
                    }
                    ?>

                    <a style="color:darkred" data-href="../Actions/school_year_delete.php?id=<?php echo $row['id']?>" ;
                        data-toggle="modal" data-target="#confirm-delete">

            <?php}} ?>

Edit School Year

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

            <form action="school_year.php" method="POST">

                        School year
                        <input type="text" name="year" id="year" class="form-control">
                        Status

                        <select type="number" name="status" id="status" class="form-control">
                            <option value="" selected disabled>--Select if default</option>
                            <option value=" 1 ">Active</option>
                            <option value="2">Inactive</option>
                        </select>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add" value="name" class="btn btn-primary">Update</button>

            </form>

THIS IS MY Script
$('.editbtn').on('click', function() {
    $('#editmodal').modal('show');

    $tr = $(this).closest('tr');
    var data = $tr.children("td").map(function() {
        return $($this).text();
    }).get();

    console.log(data);
    $('#school_year').val(data[0]);
    $('#status').val(data[1]);

});

A: since I don't have enough reputation to comment on your question, You give wrong id in bootstrap-modal :
 School year
                    <input type="text" name="year" id="school_year" class="form-control">
                    Status


text:
Q: PHP memory limit is not changing in nginx. Changed /etc/php/7.2/fpm/php.ini and /etc/php/7.2/cli/php.ini I am having ubuntu server installed nginx and php.
When we try to change the memory limit in php ini in the below path, it is not affecting php info.
I changed both ini files here is the path  /etc/php/7.2/fpm/php.ini and /etc/php/7.2/cli/php.ini
Please see the attached screenshots
php info page screenshot

Please help me where to change php settings, so that it will reflect in my server.

A: Check the php-fpm pool configuration file (in my case /etc/opt/remi/php74/php-fpm.d/www.conf) for any directive forcing php parameters, for example php_admin_value[memory_limit].
In my case php.ini memory_limit parameter was ignored and instead of this was used the memory_limit defined into the php-fpm pool.