问:
How to detect changes in MSSQL table in java?
Is there a way to detect changes in MSSQL table in Java. If new record insert into specific table want to detect in Java. Searched in Goolge can't get any solution most of results are like schedule the Job or runnable thread to detect the changes.
Is any specific way to detect the changes in Java. Suggest the Best way to detect the changes.

答:
Do you have a single client application or a distributed program with multiple users in multiple places?

I think the trigger, as mentioned by everson, is the go for. Create a trigger in your MSSQL System which sets a boolean-value in a new table (presumably with 1 column with 1 entry) to true. Each time you fetch for changes you will need to reset this value to false


来源: stackexchange

问:
UseEffect not fired when redux props change caused by async api call with redux-thunk
I have a functional login page connected with redux, I'm firing an async event onSubmit that will trigger the emailLogin action, I am using useEffect to detect the change of the isLoading prop to see whether login finished or not. If login success, the redux store should have the user object, if failed, the user should remain null.

The question is, I know that the login is success, which should triggered the change of isLoading, the parameter that decide whether the useEffect, however, the useEffect is not fired. Also, the console.log('done'); after the line await emailLogin(authData); is never fired. Ssomething is wrong.

```<code>import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import { emailLogin } from '../actions/index';

function Login({ user, isLoading, emailLogin }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const history = useHistory();

  useEffect(() => {
    console.log('useEffect fired', user, isLoading); //<-----This does not fire after login success
    if (user) {
      history.push('/protected_home');
    }
  }, [isLoading]);

  const submitEmailLoginForm = async (e) => {
    e.preventDefault();
    const authData = { email, password };
    await emailLogin(authData);
    console.log('done'); // <------- This is never fired
  };

  return (
    <div>
      <h2>Login</h2>
      <Link to="/">back</Link>
      <form onSubmit={submitEmailLoginForm}>
        <label>
          email:
          <input
            type="text"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </label>
        <label>
          password:
          <input
            type="text"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

const mapStateToProps = (state) => ({
  user: state.user,
  isLoading: state.isLoading
});

const mapDispatch = {
  emailLogin: emailLogin
};

export default connect(mapStateToProps, mapDispatch)(Login);
</code>```

My action file:

```<code>import axios from 'axios';

export const authActions = {
  EMAIL_LOGIN_START: '@@EMAIL_LOGIN_START',
  EMAIL_LOGIN_SUCCESS: '@@EMAIL_LOGIN_SUCCESS'
};

export const emailLogin = ({ email, password }) => async (dispatch) => {
  dispatch({ type: authActions.EMAIL_LOGIN_START });
  try {
    const response = await axios.post('http://localhost:5001/api/auth', {
      email: email,
      password: password
    });
    dispatch({
      type: authActions.EMAIL_LOGIN_SUCCESS,
      payload: {
        user: { ...response.data }
      }
    });
  } catch (error) {
    console.log('Should dispatch api error', error.response);
  }
};
</code>```

My Reducer:

```<code>import { authActions } from '../actions/index';

const initialState = {
  user: null,
  isLoading: false
};

const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case authActions.EMAIL_LOGIN_START:
      return { ...state, isLoading: true };
    case authActions.EMAIL_LOGIN_SUCCESS:
      console.log('Reducer check => Login is success'); //<-----this line is printed
      return { ...state, user: action.payload.user, isLoading: false };
    default:
      return state;
  }
};

export default userReducer;
</code>```

In the reducer, I see that the success action is actually triggered by checking the console.log(). Also in the redux dev tool, I can actually see that the login is success and the isLoading prop has changed :

答:
This solve my problem</p>

```<code>const mapStateToProps = (state) => ({
  user: state.userReducer.user,
  isLoading: state.userReducer.isLoading
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a functional login page connected with redux, I'm firing an async event onSubmit that will trigger the emailLogin action, I am using useEffect to detect the change of the isLoading prop to see whether login finished or not. If login success, the redux store should have the user object, if failed, the user should remain null.

The question is, I know that the login is success, which should triggered the change of isLoading, the parameter that decide whether the useEffect, however, the useEffect is not fired. Also, the console.log('done'); after the line await emailLogin(authData); is never fired. Ssomething is wrong.

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import { emailLogin } from '../actions/index';

function Login({ user, isLoading, emailLogin }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const history = useHistory();

  useEffect(() => {
    console.log('useEffect fired', user, isLoading); //<-----This does not fire after login success
    if (user) {
      history.push('/protected_home');
    }
  }, [isLoading]);

  const submitEmailLoginForm = async (e) => {
    e.preventDefault();
    const authData = { email, password };
    await emailLogin(authData);
    console.log('done'); // <------- This is never fired
  };

  return (

Login

      <Link to="/">back</Link>
      <form onSubmit={submitEmailLoginForm}>

          email:
          <input
            type="text"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />

          password:
          <input
            type="text"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />

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

  );
}

const mapStateToProps = (state) => ({
  user: state.user,
  isLoading: state.isLoading
});

const mapDispatch = {
  emailLogin: emailLogin
};

export default connect(mapStateToProps, mapDispatch)(Login);

My action file:

import axios from 'axios';

export const authActions = {
  EMAIL_LOGIN_START: '@@EMAIL_LOGIN_START',
  EMAIL_LOGIN_SUCCESS: '@@EMAIL_LOGIN_SUCCESS'
};

export const emailLogin = ({ email, password }) => async (dispatch) => {
  dispatch({ type: authActions.EMAIL_LOGIN_START });
  try {
    const response = await axios.post('http://localhost:5001/api/auth', {
      email: email,
      password: password
    });
    dispatch({
      type: authActions.EMAIL_LOGIN_SUCCESS,
      payload: {
        user: { ...response.data }
      }
    });
  } catch (error) {
    console.log('Should dispatch api error', error.response);
  }
};

My Reducer:

import { authActions } from '../actions/index';

const initialState = {
  user: null,
  isLoading: false
};

const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case authActions.EMAIL_LOGIN_START:
      return { ...state, isLoading: true };
    case authActions.EMAIL_LOGIN_SUCCESS:
      console.log('Reducer check => Login is success'); //<-----this line is printed
      return { ...state, user: action.payload.user, isLoading: false };
    default:
      return state;
  }
};

export default userReducer;

In the reducer, I see that the success action is actually triggered by checking the console.log(). Also in the redux dev tool, I can actually see that the login is success and the isLoading prop has changed :

Body:
This solve my problem

const mapStateToProps = (state) => ({
  user: state.userReducer.user,
  isLoading: state.userReducer.isLoading
});


问:
R Repeat Rows Data Table
```<code>library(data.table)
dataHAVE=data.frame("student"=c(1,2,3),
                    "score" = c(10,11,12),
                "count"=c(4,1,2))

dataWANT=data.frame("student"=c(1,1,1,1,2,3,3),
                    "score"=c(10,10,10,10,11,12,12),
                    "count"=c(4,4,4,4,1,2,2))

setDT(dataHAVE)dataHAVE[rep(1:.N,count)][,Indx:=1:.N,by=student]
</code>```

I have data 'dataHAVE' and seek to produce 'dataWANT' that basically copies each 'student' 'count' number of times as shown in 'dataWANT'. I try doing this as shown above in data.table as this is the solution I seek but get error

Error: unexpected symbol in "setDT(dat)dat"

and I cannot resolve thank you so much.

答:
Try:

```<code>setDT(dataHAVE)[rep(1:.N,count)]
</code>```

Output:

```<code>   student score count
1:       1    10     4
2:       1    10     4
3:       1    10     4
4:       1    10     4
5:       2    11     1
6:       3    12     2
7:       3    12     2
</code>```

As explained you could also replace 1:.N and do setDT(dataHAVE)[dataHAVE[, rep(.I, count)]].

Just FYI, there's also a nice function in tidyr that does similar thing:

```<code>tidyr::uncount(dataHAVE, count, .remove = FALSE)
</code>```

Title: R Repeat Rows Data Table

Body:
library(data.table)
dataHAVE=data.frame("student"=c(1,2,3),
                    "score" = c(10,11,12),
                "count"=c(4,1,2))

dataWANT=data.frame("student"=c(1,1,1,1,2,3,3),
                    "score"=c(10,10,10,10,11,12,12),
                    "count"=c(4,4,4,4,1,2,2))

setDT(dataHAVE)dataHAVE[rep(1:.N,count)][,Indx:=1:.N,by=student]

I have data 'dataHAVE' and seek to produce 'dataWANT' that basically copies each 'student' 'count' number of times as shown in 'dataWANT'. I try doing this as shown above in data.table as this is the solution I seek but get error

Error: unexpected symbol in "setDT(dat)dat"

and I cannot resolve thank you so much.

Body:
Try:

setDT(dataHAVE)[rep(1:.N,count)]

Output:

   student score count
1:       1    10     4
2:       1    10     4
3:       1    10     4
4:       1    10     4
5:       2    11     1
6:       3    12     2
7:       3    12     2

As explained you could also replace 1:.N and do setDT(dataHAVE)[dataHAVE[, rep(.I, count)]].

Just FYI, there's also a nice function in tidyr that does similar thing:

tidyr::uncount(dataHAVE, count, .remove = FALSE)


问:
Firebase Cloud Functions deploy error
I'm trying to deploy my project from firebase CLI but there is an issue with my functions. This is strange because I had no issues with it four weeks ago. I haven't changed any of my firebase cloud function settings. When I try to run
  firebase deploy  or
  firebase deploy --only functions .

I get this same error:
  There was an issue deploying your functions. Verify that your project has a Google App Engine instance setup at https://console.cloud.google.com/appengine and try again. If this issue persists, please contact support.

Error: HTTP Error: 500, Internal error encountered.

My cloud functions worked fine before without having to set up a Google App Engine and I can't seem to find anything mentioning the need for a Google App Engine in the Docs.

答:
For me it was an issue with the cloud resource location.

So just add firestore to your project and choose a location (i.e. europe-west).

Explanation:

After firebase init I got an error:

Error: Cloud resource location is not set for this project but the
  operation you are attempting to perform in Cloud Firestore requires
  it. Please see this documentation for more details:
  https://firebase.google.com/docs/projects/locations

So go to https://console.firebase.google.com/project, choose your project, and click on database and add firestore (or real time database if you prefer). That will also allow your functions to be uploaded.

ContentLicense: CC BY-SA 3.0

Title: Firebase Cloud Functions deploy error


问:
Vector of class object with private constructor and destructor?
Defining the classes A with private constructor and destructor (it should be so!) and B as a friend class, how can I creat a vector of A objects in B and fill it with the function addA(). I got the error "error C2248: "A::~A": No access to private members whose declaration was made in the A class".</p>

```<code>class A
{
private:
    A();
    A(const std::string& name, const float& num);
    ~A();
public:
    friend class B;
private:
    std::string name_;
    float num_;
};

A::A()
{
    name_ = "NoName";
    num_ = 0.0;
}
A::A(const std::string& name, const float& num)
{
    name_ = name;
    num_ = num;
}
A::~A()
{
}

class B
{
public:
    B();
    ~B();
    void addA(const std::string name, const float num);
private:
    vector<A> vecA;
};

B::B()
{
}
B::~B()
{
}
void B::addA(const std::string name, const float num)
{
    A a(name, num);
    vecA.push_back(a);
}

int main()
{
    B b;
    b.addA("Name", 1.0);

    return 0;
}
</code>```

答:
how can I create a vector of A objects in B [...] ?

You can't do that. While B is a friend of A, std::vector is not a friend of A, which means that it cannot access private members of A, e.g., constructor, which is required for a vector to work.

However, if you are okay with a little indirection, little potential performance hit and a change in your signature, you can replace the not-working std::vector with a workig std::vector<std::unique_ptr>.

It's important to note that plain std::unique_ptr will not work here. It has a similar problem to std::vector - it cannot access private destructor of A. One way to work around it is to outsource the job of constructing and destructing of As entirely to B - via explicit construction and destruction, that is:

new A(name, num)

static void deleter_a(A* a) { delete a; }

in B's scope.

Now we can do:

```<code>std::vector<std::unique_ptr<A, std::function<void(A*)>>> vecA;
</code>```

instead of: std::vector or std::vector<std::unique_ptr>. This is important - neither std::unique_ptr nor std::vector construct or destruct your As. B is entirely responsible for constructing (new A(name, num)) and destructing (static void deleter_a(A* a) { delete a; }) As.

Full B class:

```<code>class B {
public:
    B() {};  // or = default
    ~B() {}; // or = default
    void addA(const std::string name, const float num);

private:
    static void deleter_a(A* a) { delete a; }
    using deleter_a_t = void(A*);
    std::vector<std::unique_ptr<A, std::function<deleter_a_t>>> vecA;
};

void B::addA(const std::string name, const float num) {
    vecA.push_back(std::unique_ptr<A, std::function<deleter_a_t>>{
            new A(name, num), std::function<deleter_a_t>{deleter_a}
    });
}
</code>```

Body:
Defining the classes A with private constructor and destructor (it should be so!) and B as a friend class, how can I creat a vector of A objects in B and fill it with the function addA(). I got the error "error C2248: "A::~A": No access to private members whose declaration was made in the A class".

class A
{
private:
    A();
    A(const std::string& name, const float& num);
    ~A();
public:
    friend class B;
private:
    std::string name_;
    float num_;
};

A::A()
{
    name_ = "NoName";
    num_ = 0.0;
}
A::A(const std::string& name, const float& num)
{
    name_ = name;
    num_ = num;
}
A::~A()
{
}

class B
{
public:
    B();
    ~B();
    void addA(const std::string name, const float num);
private:
    vector vecA;
};

B::B()
{
}
B::~B()
{
}
void B::addA(const std::string name, const float num)
{
    A a(name, num);
    vecA.push_back(a);
}

int main()
{
    B b;
    b.addA("Name", 1.0);

    return 0;
}

Body:
how can I create a vector of A objects in B [...] ?

You can't do that. While B is a friend of A, std::vector is not a friend of A, which means that it cannot access private members of A, e.g., constructor, which is required for a vector to work.

However, if you are okay with a little indirection, little potential performance hit and a change in your signature, you can replace the not-working std::vector<A> with a workig std::vector<std::unique_ptr<A, deleter>>.

It's important to note that plain std::unique_ptr will not work here. It has a similar problem to std::vector - it cannot access private destructor of A. One way to work around it is to outsource the job of constructing and destructing of As entirely to B - via explicit construction and destruction, that is:

new A(name, num)

static void deleter_a(A* a) { delete a; }

in B's scope.

Now we can do:

std::vector<std::unique_ptr<A, std::function<void(A*)>>> vecA;

instead of: std::vector<A> or std::vector<std::unique_ptr<A>>. This is important - neither std::unique_ptr nor std::vector construct or destruct your As. B is entirely responsible for constructing (new A(name, num)) and destructing (static void deleter_a(A* a) { delete a; }) As.

Full B class:

class B {
public:
    B() {};  // or = default
    ~B() {}; // or = default
    void addA(const std::string name, const float num);

private:
    static void deleter_a(A* a) { delete a; }
    using deleter_a_t = void(A*);
    std::vector<std::unique_ptr<A, std::function<deleter_a_t>>> vecA;
};

void B::addA(const std::string name, const float num) {
    vecA.push_back(std::unique_ptr<A, std::function<deleter_a_t>>{
            new A(name, num), std::function<deleter_a_t>{deleter_a}
    });
}


问:
Convert to Date Time Format "2020-02-11T17:26:31-05:00"
Hi I am not able to understand what time format we need to use  in order to parse this date2020-02-11T17:26:31-05:00  I have tried using Date formatter and simple date format but its not working

Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date

Below is snippet of code i have tried but its throwing exception

```<code>DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);
</code>```

答:
This is a datetime String that contains an offset of minus five hours. You don't even have to use a DateTimeFormatter directly, because parsing this to an OffsetDateTime will do:

```<code>public static void main(String[] args) {
    String dateString = "2020-02-11T17:26:31-05:00";
    OffsetDateTime odt = OffsetDateTime.parse(dateString);

    System.out.println(odt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
</code>```

Output:

2020-02-11T17:26:31
```

Not that this uses a DateTimeFormatter without an offset for the output.

Body:
Hi I am not able to understand what time format we need to use  in order to parse this date2020-02-11T17:26:31-05:00  I have tried using Date formatter and simple date format but its not working

Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date

Below is snippet of code i have tried but its throwing exception

DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);

Body:
This is a datetime String that contains an offset of minus five hours. You don't even have to use a DateTimeFormatter directly, because parsing this to an OffsetDateTime will do:

public static void main(String[] args) {
    String dateString = "2020-02-11T17:26:31-05:00";
    OffsetDateTime odt = OffsetDateTime.parse(dateString);

    System.out.println(odt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}

Output:

2020-02-11T17:26:31

Not that this uses a DateTimeFormatter without an offset for the output.


问:
AWK: dynamically change FS or RS
I cannot seem to get the trick to interchange the FS/RS variables dynamically, so that I get the following results from the input:

Input_file

```<code>header 1
header 2
{
something should not be removed
}

50

(
auto1
{
    type        good;
    remove      not useful;
}

 auto2
{
    type        good;
    keep        useful;
}

 auto3
{
    type        moderate;
    remove      not useful;
}
)
</code>```

Output_file

```<code>header 1
header 2
{
something that should not be removed
}

50

(
auto1//good
{
    type        good;//good
}

auto2//good
{
    type        good;//good
    keep        useful;
}

auto3//moderate
{
    type        moderate;//moderate
}
)
</code>```

The key things are:

There's no change is happening when the code-block {...} is not preceded by a autoX (X can be 1,2,3 etc.).

The changes should happen when autoX is followed by a codeblock {...}.

the value inside the codeblock & autoX is modified with the addition of \\good or //moderate, which needs to be read from the {...} itself.

the whole line should be removed from {...}, if it contains the phrase remove.

HINT: It might be something that can use regex and the idea explained here, with this particular example.

For now, I only have been able to meet the last requirement, with the following code:

```<code>awk ' {$1=="{"; FS=="}";} {$1!="}"; gsub("remove",""); print NR"\t\t"$0}' Input_file
</code>```

Thanks in advance, for your skill & time, to tackle this problem with awk.

答:
You can use two newlines as record separator and process each record which may contain one

```<code>autoX
{
  ...
  ...
}
</code>```

block.

```<code>awk '
BEGIN{
  RS="\n\n"                          # set record separator RS to two newlines
  a["good"]; a["moderate"]           # create array a with indices "good" and "moderate"
}
{
  sub(/\n[ \t]+remove[^;]+;/, "")    # remove line containing "remove xxx;"
  for (i in a){                      # loop array indices "good" and "moderate"
    if (index($0, i)){               # if value exists in record
      sub(i";", i";//"i)             # add "//good" to "good;" or "//moderate" to "moderate;"
      match($0, /(auto[0-9]+)/)      # get pos. RSTART and length RLENGTH of "autoX"
      if (RSTART){                   # RSTART > 0 ?
                                     # set prefix including "autox", "//value" and suffix
        $0=substr($0, 1, RSTART+RLENGTH-1) "//"i substr($0, RSTART+RLENGTH)
      }
      break                          # stop looping (we already replaced "autoX")
    }
  }
  printf "%s", (FNR==1 ? "" : RS)$0  # print modified line prefixed by RS if not the first line
}
' Input_file
</code>```

Title: AWK: dynamically change FS or RS

Body:
I cannot seem to get the trick to interchange the FS/RS variables dynamically, so that I get the following results from the input:

Input_file

header 1
header 2
{
something should not be removed
}

50

(
auto1
{
    type        good;
    remove      not useful;
}

 auto2
{
    type        good;
    keep        useful;
}

 auto3
{
    type        moderate;
    remove      not useful;
}
)

Output_file

header 1
header 2
{
something that should not be removed
}

50

(
auto1//good
{
    type        good;//good
}

auto2//good
{
    type        good;//good
    keep        useful;
}

auto3//moderate
{
    type        moderate;//moderate
}
)

The key things are:

There's no change is happening when the code-block {...} is not preceded by a autoX (X can be 1,2,3 etc.).

The changes should happen when autoX is followed by a codeblock {...}.

the value inside the codeblock & autoX is modified with the addition of \\good or //moderate, which needs to be read from the {...} itself.

the whole line should be removed from {...}, if it contains the phrase remove.

HINT: It might be something that can use regex and the idea explained here, with this particular example.

For now, I only have been able to meet the last requirement, with the following code:

awk ' {$1=="{"; FS=="}";} {$1!="}"; gsub("remove",""); print NR"\t\t"$0}' Input_file

Thanks in advance, for your skill & time, to tackle this problem with awk.

Body:
You can use two newlines as record separator and process each record which may contain one

autoX
{
  ...
  ...
}

block.

awk '
BEGIN{
  RS="\n\n"                          # set record separator RS to two newlines
  a["good"]; a["moderate"]           # create array a with indices "good" and "moderate"
}
{
  sub(/\n[ \t]+remove[^;]+;/, "")    # remove line containing "remove xxx;"
  for (i in a){                      # loop array indices "good" and "moderate"
    if (index($0, i)){               # if value exists in record
      sub(i";", i";//"i)             # add "//good" to "good;" or "//moderate" to "moderate;"
      match($0, /(auto[0-9]+)/)      # get pos. RSTART and length RLENGTH of "autoX"
      if (RSTART){                   # RSTART > 0 ?
                                     # set prefix including "autox", "//value" and suffix
        $0=substr($0, 1, RSTART+RLENGTH-1) "//"i substr($0, RSTART+RLENGTH)
      }
      break                          # stop looping (we already replaced "autoX")
    }
  }
  printf "%s", (FNR==1 ? "" : RS)$0  # print modified line prefixed by RS if not the first line
}
' Input_file


问:
Form with multiple file inputs
I have an application with a dynamic form that uploads simultaneously to different people.

Each person has a different input file and can add more 2 inputs dynamic.

```<code><div id="InputsWrapper_1">
<div><input type="file" name="arquivoDep_1_[]" id="1" value="" multiple><a href="#" class="removeclass"></a></div>
</div>

<div id="AddMoreFileId_1">
<a href="#" id="AddMoreFileBox_1" class="btn btn-info adiciona">Add field</a><br><br>
</div>
<div id="lineBreak"></div>

 <div id="InputsWrapper_2">
<div><input type="file" name="arquivoDep_2_[]" id="2" value="" multiple><a href="#" class="removeclass"></a></div>
</div>

<div id="AddMoreFileId_2">
<a href="#" id="AddMoreFileBox_2" class="btn btn-info adiciona">Add field</a><br><br>
</div>
</code>```

When I submit this form, I´ve this response

```<code><input id="1" type="file" name="arquivoDep_1_[]" value="" multiple="">
<input type="file" name="arquivoDep_1_[]">

<input id="2" type="file" name="arquivoDep_2_[]" value="" multiple="">
<input type="file" name="arquivoDep_2_[]">
</code>```

That´s ok. Two files for two persons.

How can I append this files.. someting like

```<code>$.each($("input[type=file]"), function(i, obj)
{
    $.each(obj.files,function(j, file)
    {
        form_data.append('arquivoDep_x_[]', file, file.name);
    })
});
</code>```

答:
First we are in 2020, check if you really need jQuery : http://youmightnotneedjquery.com/

Then you can use a multipart-form data like this :

```<code><script type="text/javascript">
  const formElement = document.querySelector('form');

  formElement.addEventListener('submit', e => {
    e.preventDefault();

    const request = new XMLHttpRequest();

    const formData = new FormData();

    const formElements = formElement.elements;

    const data = {};

    for (let i = 0; i < formElements.length; i++) {
      const currentElement = formElements[i];
      if (!['submit', 'file'].includes(currentElement.type)) {
        data[currentElement.name] = currentElement.value;
      } else if (currentElement.type === 'file') {
        if (currentElement.files.length === 1) {
          const file = currentElement.files[0];
          formData.append(`files.${currentElement.name}`, file, file.name);
        } else {
          for (let i = 0; i < currentElement.files.length; i++) {
            const file = currentElement.files[i];

            formData.append(`files.${currentElement.name}`, file, file.name);
          }
        }
      }
    }

    formData.append('data', JSON.stringify(data));

    request.open('POST', 'https://example.com');

    request.send(formData);
  });
</script>
</code>```

Source : Upload | Strapi Documentation

Title: Form with multiple file inputs

Body:
I have an application with a dynamic form that uploads simultaneously to different people.

Each person has a different input file and can add more 2 inputs dynamic.

<input type="file" name="arquivoDep_1_[]" id="1" value="" multiple>

Add field

<input type="file" name="arquivoDep_2_[]" id="2" value="" multiple>

Add field

When I submit this form, I´ve this response

<input id="1" type="file" name="arquivoDep_1_[]" value="" multiple="">
<input type="file" name="arquivoDep_1_[]">

<input id="2" type="file" name="arquivoDep_2_[]" value="" multiple="">
<input type="file" name="arquivoDep_2_[]">

That´s ok. Two files for two persons.

How can I append this files.. someting like

$.each($("input[type=file]"), function(i, obj)
{
    $.each(obj.files,function(j, file)
    {
        form_data.append('arquivoDep_x_[]', file, file.name);
    })
});

Body:
First we are in 2020, check if you really need jQuery : http://youmightnotneedjquery.com/

Then you can use a multipart-form data like this :

<script type="text/javascript">
  const formElement = document.querySelector('form');

  formElement.addEventListener('submit', e => {
    e.preventDefault();

    const request = new XMLHttpRequest();

    const formData = new FormData();

    const formElements = formElement.elements;

    const data = {};

    for (let i = 0; i < formElements.length; i++) {
      const currentElement = formElements[i];
      if (!['submit', 'file'].includes(currentElement.type)) {
        data[currentElement.name] = currentElement.value;
      } else if (currentElement.type === 'file') {
        if (currentElement.files.length === 1) {
          const file = currentElement.files[0];
          formData.append(`files.${currentElement.name}`, file, file.name);
        } else {
          for (let i = 0; i < currentElement.files.length; i++) {
            const file = currentElement.files[i];

            formData.append(`files.${currentElement.name}`, file, file.name);
          }
        }
      }
    }

    formData.append('data', JSON.stringify(data));

    request.open('POST', 'https://example.com');

    request.send(formData);
  });
</script>

Source : Upload | Strapi Documentation


问:
Datatable YADCF server side filter type
I am using yadcf column filters to a server side DataTables.js request.

```<code> yadcf.init(table, [
       {
                    column_number: 0,
                    filter_type: "text",
                    filter_default_label: "Search",
                    filter_reset_button_text: false
        },
        {
                    column_number: 1,
                    filter_type: "select",
                    filter_reset_button_text: false
        },
     ]
</code>```

Request give me

columns[X][search][value]

columns[X][search][name] like this but I want to get column yadcf column attribute filter_type .

This data help to search for contains search or equals search

How is it get? or change scripts.

Version 0.9.3

答:
I send mail to Daniel Reznick (yadcf writer)

Daniel Reznick answers :

I think you could achieve it by using some datatables "pre XHR" event / hook in which you can modify the XHR request before its being sent to server, but IMO since this is being initialized only once (when you write your JS code) I guess you can do it "hard coded" on server

My Code like this

```<code>var table = $("#datalist")
            .on('preXhr.dt', function (e, settings, data) {
                var yadcf = [];
                $('.yadcf-filter').each(function (data) {
                    input = $(this)
                    var col = {
                        "type": input.attr('type'),
                        "filter_match_mode": input.attr('filter_match_mode'),
                        "column_number": input.attr('id').replace('yadcf-filter--datalist-', '')
                    }
                    yadcf.push(col);
                });
                data.yadcf = yadcf;
            })
          .DataTable({
            "ajax": {
                "url": "/url",
                "type": "POST",
                "datatype": "json"
            },

yadcf.init(table, [

            { column_number: 1, filter_type: "text", filter_default_label: "Contains Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode:"contains"},
            { column_number: 2, filter_type: "text", filter_default_label: "Exact Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode: "exact" },
            { column_number: 3, filter_type: "text", filter_default_label: "Starts With Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode: "startsWith" },
</code>```

]

Title: Datatable YADCF server side filter type

Body:
I am using yadcf column filters to a server side DataTables.js request.

 yadcf.init(table, [
       {
                    column_number: 0,
                    filter_type: "text",
                    filter_default_label: "Search",
                    filter_reset_button_text: false
        },
        {
                    column_number: 1,
                    filter_type: "select",
                    filter_reset_button_text: false
        },
     ]

Request give me

columns[X][search][value]

columns[X][search][name] like this but I want to get column yadcf column attribute filter_type .

This data help to search for contains search or equals search

How is it get? or change scripts.

Version 0.9.3

Body:
I send mail to Daniel Reznick (yadcf writer)

Daniel Reznick answers :

I think you could achieve it by using some datatables "pre XHR" event / hook in which you can modify the XHR request before its being sent to server, but IMO since this is being initialized only once (when you write your JS code) I guess you can do it "hard coded" on server

My Code like this

var table = $("#datalist")
            .on('preXhr.dt', function (e, settings, data) {
                var yadcf = [];
                $('.yadcf-filter').each(function (data) {
                    input = $(this)
                    var col = {
                        "type": input.attr('type'),
                        "filter_match_mode": input.attr('filter_match_mode'),
                        "column_number": input.attr('id').replace('yadcf-filter--datalist-', '')
                    }
                    yadcf.push(col);
                });
                data.yadcf = yadcf;
            })
          .DataTable({
            "ajax": {
                "url": "/url",
                "type": "POST",
                "datatype": "json"
            },

yadcf.init(table, [

            { column_number: 1, filter_type: "text", filter_default_label: "Contains Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode:"contains"},
            { column_number: 2, filter_type: "text", filter_default_label: "Exact Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode: "exact" },
            { column_number: 3, filter_type: "text", filter_default_label: "Starts With Search", filter_reset_button_text: false, filter_delay: 500, filter_match_mode: "startsWith" },

]


问:
Can you filter an xml document to a subset of nodes using XPath in C#?
I'm trying to filter an Xml document so into a subset of itself using XPath.

I have used XPath get an XmlNodeList, but I need to transform this into an XML document.

Is there a way to either transform an XMLNodeList into an XmlDocument or to produce an XmlDocument by filtering another XmlDocument directly?

答:
With XmlDocument, you will need to import those nodes into a second document;</p>

```<code>    XmlDocument doc = new XmlDocument();
    XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("root"));
    XmlNodeList list = // your query
    foreach (XmlElement child in list)
    {
        root.AppendChild(doc.ImportNode(child, true));
    }
</code>```

OwnerDisplayName: Omar Kooheji

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Omar Kooheji

Body:
With XmlDocument, you will need to import those nodes into a second document;

    XmlDocument doc = new XmlDocument();
    XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("root"));
    XmlNodeList list = // your query
    foreach (XmlElement child in list)
    {
        root.AppendChild(doc.ImportNode(child, true));
    }

OwnerDisplayName: Marc Gravell


问:
EF code first attach and create proxy
Let's say I have an entity Foo.

```<code>public class Foo
{
  public int Id {get;set;}
  public virtual ICollection<Bar> Bars {get;set;}
}
</code>```

When I get this entity from the db then I actually get a proxy and everything works as it should be.

But, can I attach Foo to DbContext and create the proxy manually so Bars would not return null after attaching it, but an actual collection of bars?

Meaning

```<code>var foo = new Foo { Id = 1 };
Context.Set<Foo>().Attach(foo);
foo = CreateProxyOf(foo);
var countOfBars = foo.Bars.Count();
</code>```

Is there something like CreateProxyOf?

答:
When you get all Foos or a single Foo you can tell EF to get bars at the same time. For example:

```<code>var foos = db.Foos.Include("Bars");

var foo = db.Foos.Include("Bars").Single(f => f.Id == 1);
</code>```

More details on MSDN here

http://msdn.microsoft.com/en-us/library/bb896272.aspx

Title: EF code first attach and create proxy

Body:
Let's say I have an entity Foo.

public class Foo
{
  public int Id {get;set;}
  public virtual ICollection<Bar> Bars {get;set;}
}

When I get this entity from the db then I actually get a proxy and everything works as it should be.

But, can I attach Foo to DbContext and create the proxy manually so Bars would not return null after attaching it, but an actual collection of bars?

Meaning

var foo = new Foo { Id = 1 };
Context.Set<Foo>().Attach(foo);
foo = CreateProxyOf(foo);
var countOfBars = foo.Bars.Count();

Is there something like CreateProxyOf?

Body:
When you get all Foos or a single Foo you can tell EF to get bars at the same time. For example:

var foos = db.Foos.Include("Bars");

var foo = db.Foos.Include("Bars").Single(f => f.Id == 1);

More details on MSDN here

http://msdn.microsoft.com/en-us/library/bb896272.aspx


问:
Achieve 3D model using 2D horizontal polygons sorted by z-axis
Please advise me.

I want to construct a 3D model in C++ using 2D horizontal polygons (actually a set of 2D points which form a closed contour) sorted by z-axis (Using frameworks like OpenGL).

How could I do that ?

Thanks.

答:
You can take a look at the DOOM engine from id Software, in which they used a very similar principle to display 3D scenes. Also, take a look at the Game Engine Black Book: DOOM

Briefly, the 2D polygons are converted into a BSP tree to create a set of convex nodes, which are then used for rendering. There are other resources for similar techniques, such as the Build engine which uses portal rendering.

Note that this technique you are trying to use has some limitations.


问:
how to assign variable in json in restrequest c#
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json. </p>

```<code>var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
</code>```

答:
You can use string.Format()</p>

```<code>request.AddParameter("application/json", string.Format("{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"{0}\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",messageVar)
</code>```

Body:
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json.

var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Body:
You can use string.Format()

request.AddParameter("application/json", string.Format("{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"{0}\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",messageVar)


问:
How to do active active HA node setup in Postgresql
New to postgres and we need to setup active-active HA for postgresql cluster.
Posgresql documentation has active passive natively supported. Has anyone implemented HA using any tools?

DB is expected to execute huge read write transactions per sec and should be scalable.

Thanks.

答:
have a look over https://github.com/zalando/patroni
as one option. There are more, depends on your specific requirements. </p>


问:
Spring webflux Netty: How to expose proto as json endpoints without duplication of code?
Use-case:

Developers/I, want to only implement a Protobuf implementation (binary protocol). However, I need a way to add config, so, the same implementation is exposed as rest/json api as well -- without code duplication.

I have proto endpoints exposed. I also want consumers to post json equivalent of those proto objects and return/receive json equivalent of the results with type info (Pojo?). The type info helps with OpenAPI / Swagger documentation too!

What are the most elegant/simple ways to achieve that without code duplication?

Any example github code that achieves that would be helpful.

Note: This is for webflux & netty - no tomcat.

ProtobufJsonFormatHttpMessageConverter  - works for tomcat, does not work for netty. A working example code would be great.

答:
Since version 4.1 spring provides org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter for reading and writing protos as Json.

However, If you are using Spring 5.x and Protobuf 3.x there is org.springframework.http.converter.protobuf.ProtobufJsonFormatHttpMessageConverter for more explicit conversion of Json.

This documentation should help you:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverter.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverter.html


问:
Cannot find module "@sendgrid/mail"
I'm using the Sendgrid mail package (https://www.npmjs.com/package/@sendgrid/mail) to send a test email using the Twilio Serveless functions. I have configured the module, specifying the correct version and module in the configure dashboard here. https://www.twilio.com/console/functions/configure but when I deploy my function and run it using the twilio cli, i get the error message,

"message":"Cannot find module '@sendgrid/mail'"

I find this weird since deploying the function manually under the Manage tab, https://www.twilio.com/console/functions/manage tab works like a gem. I'm I missing something?

Or does the serverless API doesn't currently support this? (the same package configurations work when I manually deploying the function)

答:
```<code>const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with Twilio SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
//ES6
sgMail
  .send(msg)
  .then(() => {}, console.error);
//ES8
(async () => {
  try {
    await sgMail.send(msg);
  } catch (err) {
    console.error(err.toString());
  }
})();
</code>```

Title: Cannot find module "@sendgrid/mail"


问:
How do I test a single file using Jest?
I am able to test multiple files using Jest, but I cannot figure out how to test a single file.

I have:

Run npm install jest-cli --save-dev

Updated package.json: `{ ... "scripts": { "test": "jest" } ... }

Written a number of tests.

Running npm test works as expected (currently it runs 14 tests).

How do I test a single file, e.g. test app/foo/__tests__/bar.spec.js?

I have tried running npm test app/foo/__tests__/bar.spec.js (from the project root), but I get the following error:

npm ERR! Error: ENOENT, open '/node_modules/app/foo/tests/bar.spec.js/package.json'

答:
We are using nrwl-nx with Angular. In this case we can use this command:

```<code>npm test <ng-project> -- --testFile "file-name-part"
</code>```

Notes:

npm test will run the test script specified in package.json:
"test": "ng test"

--: tells npm to pass the following parameters to the test script (instead of consuming them)

Thus the rest of the cmd will be passed to ng test

<ng-project> is the name of a project in angular.json

when you omit this parameter, the "defaultProject" (specified in angular.json) will be used (so you must specify it, when the test is not in your default project)

Next we must check which builder is used:

In angular.json navigate to "project" - "<ng-project>" - "architect" - "test"

and check the "builder", which in our case is: "@nrwl/jest:jest"

Now that we know the builder, we need to find the available cmd-line parameters

On the command line, run npm test <ng-project> -- --help to see all available options

Or check the online documentation

One of the options is --testFile which is used here

Title: How do I test a single file using Jest?

Body:
We are using nrwl-nx with Angular. In this case we can use this command:

npm test <ng-project> -- --testFile "file-name-part"

Notes:

npm test will run the test script specified in package.json:
"test": "ng test"

--: tells npm to pass the following parameters to the test script (instead of consuming them)

Thus the rest of the cmd will be passed to ng test

<ng-project> is the name of a project in angular.json

when you omit this parameter, the "defaultProject" (specified in angular.json) will be used (so you must specify it, when the test is not in your default project)

Next we must check which builder is used:

In angular.json navigate to "project" - "<ng-project>" - "architect" - "test"

and check the "builder", which in our case is: "@nrwl/jest:jest"

Now that we know the builder, we need to find the available cmd-line parameters

On the command line, run npm test <ng-project> -- --help to see all available options

Or check the online documentation

One of the options is --testFile which is used here


问:
Service with name "Zend\Authentication\AuthenticationService" could not be created. Reason: Session validation failed
I've developed a system using zend framework 3 and is working fine in my notebook, but when I try to run on a CentOS server it failed creating a session container.

Session error image

Session error image 2

I already compilated selinux modules, so it's OK

Somebody knows how to fix it?

Notebook configuration

Linux Mint 18.2

Apache

Server version: Apache/2.4.18 (Ubuntu)

Server built:   2018-06-07T19:43:03

Php

PHP 7.2.10-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Oct  1 2018 11:45:50) ( NTS )

Copyright (c) 1997-2018 The PHP Group

Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.10-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

Php info

https://drive.google.com/open?id=1ZnmxugSDbtBvZFEBDj7SudxLNaQkl3WU

Server configuration (CentOS)

Red Hat Enterprise Linux Server 7.5 (Maipo)

Apache

Server version: Apache/2.4.6 (Red Hat Enterprise Linux)

Server built:   May 28 2018 16:19:32

Php info

https://drive.google.com/open?id=1DUrc2tEfxOpkGyT0mGv59jlVWOQhKcA9

EDIT

I've found the problem.
In my global.php I've config my session_manager with the validator RemoteAddr, when I removed it,it worked fine.

Does anyone know why did that happen?

答:
I run into exactly the same problem today. I could trace back the problem to only be browser related. Clearing my cookies solved the issue.

I was logged into the app with no problem.

Then run a deployment and after that the error occurred. I guess some token was regenerated after the deployment and the stored session cookie contained the old one. That seems to trigger this error.

If you run into this problem, first try another browser to see if this applies to you.


问:
C# code works from Console function but does not work in SQL CLR Stored Procedure
PLEASE HELP!!! I have a code to get data from AD. This used to work in SQL2014/Visual Studio2013. Now, we are migrating to SQL2016. I tested the code in a Console App and it worked just fine. It just does not work when I create the same code into a SQL CLR Stored Proc using Visual Studio 2017.

This is the code in the Console App:

```<code>        static void Main(string[] args)
        {
            DirectoryEntry ldapConnection;
            DirectorySearcher search;
            SearchResult result;
            DirectoryEntry ldapconnection = null;
            string szJDEID = "";
            string szErrorMessage = "";
            string szNetworkID = "xyz";

            //--- Create and return new LDAP connection with desired settings
            ldapConnection = new DirectoryEntry("LDAP://DC.company.com:389", "userid", "password");
            ldapConnection.Path = "LDAP://DC=company,DC=com";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;

            //--- create search object which operates on ldap connection object and set search object to only find the user specified
            search = new DirectorySearcher(ldapconnection);
            search.Filter = "(&(samaccountname=" + szNetworkID.Trim() + ")(memberOf=CN=JDEdwards Users,OU=Mail Enabled Manual,OU=Groups,OU=Global,DC=company,DC=com))";

            result = search.FindOne();

            if (result != null)
            {
                //--- create an array of properties that we would like and add them to the search object
                string[] requiredproperties = new string[] { "extensionattribute13" };

                foreach (string property in requiredproperties)
                    search.PropertiesToLoad.Add(property);

                result = search.FindOne();

                if (result != null)
                {
                    foreach (string property in requiredproperties)
                        foreach (object mycollection in result.Properties[property])
                            szJDEID = mycollection.ToString();
                }
            }
            else
            {
                szErrorMessage = "ERROR: This user does not belong to the JDEdwards Users AD Group. Please check with the IT Helpdesk team.";
            }
        }
</code>```

I get the value of szJDEID as stored in Extension Attribute13. When I put the same code in a SQL CLR Stored Proc, the Logic always returns the szErrorMessage value.

What am I missing?

Thanks in advance.

答: Finally. As you had rightly pointed earlier, the bindDn was incorrect. The issue is we moved from one DC to another. I used lip.exe to find out the principal - userid@domain.com. Also, the ldapConnection.Path was not needed anymore as it was incorrect with the new DC. So, finally, it is working. Thanks Clint.</p>

Body:
PLEASE HELP!!! I have a code to get data from AD. This used to work in SQL2014/Visual Studio2013. Now, we are migrating to SQL2016. I tested the code in a Console App and it worked just fine. It just does not work when I create the same code into a SQL CLR Stored Proc using Visual Studio 2017.

This is the code in the Console App:

        static void Main(string[] args)
        {
            DirectoryEntry ldapConnection;
            DirectorySearcher search;
            SearchResult result;
            DirectoryEntry ldapconnection = null;
            string szJDEID = "";
            string szErrorMessage = "";
            string szNetworkID = "xyz";

            //--- Create and return new LDAP connection with desired settings
            ldapConnection = new DirectoryEntry("LDAP://DC.company.com:389", "userid", "password");
            ldapConnection.Path = "LDAP://DC=company,DC=com";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;

            //--- create search object which operates on ldap connection object and set search object to only find the user specified
            search = new DirectorySearcher(ldapconnection);
            search.Filter = "(&(samaccountname=" + szNetworkID.Trim() + ")(memberOf=CN=JDEdwards Users,OU=Mail Enabled Manual,OU=Groups,OU=Global,DC=company,DC=com))";

            result = search.FindOne();

            if (result != null)
            {
                //--- create an array of properties that we would like and add them to the search object
                string[] requiredproperties = new string[] { "extensionattribute13" };

                foreach (string property in requiredproperties)
                    search.PropertiesToLoad.Add(property);

                result = search.FindOne();

                if (result != null)
                {
                    foreach (string property in requiredproperties)
                        foreach (object mycollection in result.Properties[property])
                            szJDEID = mycollection.ToString();
                }
            }
            else
            {
                szErrorMessage = "ERROR: This user does not belong to the JDEdwards Users AD Group. Please check with the IT Helpdesk team.";
            }
        }

I get the value of szJDEID as stored in Extension Attribute13. When I put the same code in a SQL CLR Stored Proc, the Logic always returns the szErrorMessage value.

What am I missing?

Thanks in advance.


问:
Is the table rowspan > 1 stopping its child div height setting to 100% of parent properly?
Having a bit of an issue with dynamically created table cells, possibly to do with rowspan.

td{
    height:40px;
    position:relative;
}
.CoolButton{
    position:absolute;
    background-color: aquamarine;
    top:0;
    bottom:0;
}
.CoolButtonInner{
    background-color: pink;
    height:inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td rowspan="4">

        <div class="CoolButtonInner">Blah Blah</div>

</td></code>```

I'm trying to get the div to stretch out for the HEIGHT of the entire td cell.

This snippet works on this site so without posting the entire codebase, what could be stopping the height from stretching down?

答:
You can give a width of 100% for .CoolButton Class.

td{
    height:40px;
    position:relative;
}
.CoolButton{
    position:absolute;
    background-color: aquamarine;
    top:0;
    bottom:0;
    width: 100%; ###

}
.CoolButtonInner{
    background-color: pink;
    height:inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td rowspan="4">

        <div class="CoolButtonInner">Blah Blah</div>

</td></code>```

Body:
Having a bit of an issue with dynamically created table cells, possibly to do with rowspan.

td{
    height:40px;
    position:relative;
}
.CoolButton{
    position:absolute;
    background-color: aquamarine;
    top:0;
    bottom:0;
}
.CoolButtonInner{
    background-color: pink;
    height:inherit;
}

Blah Blah

I'm trying to get the div to stretch out for the HEIGHT of the entire td cell.

This snippet works on this site so without posting the entire codebase, what could be stopping the height from stretching down?

Body:
You can give a width of 100% for .CoolButton Class.

td{
    height:40px;
    position:relative;
}
.CoolButton{
    position:absolute;
    background-color: aquamarine;
    top:0;
    bottom:0;
    width: 100%; ###

}
.CoolButtonInner{
    background-color: pink;
    height:inherit;
}

<td rowspan="4">
    <a class="CoolButton" href="">
        <div class="CoolButtonInner">Blah Blah</div>
    </a>
</td>


问:
set jenkins user build variable option is not available even after installed build user vars
I have "Build User Vars"(user build vars plugin - V 1.5) plugin installed in Jenkins(Version 1.565) but in the job configuration, "set jenkins user build variable" checkbox option is not available. Could someone please help me in understanding what is wrong with my Jenkins?</p>

答:
If your Jenkins' version is greater than 1.609 and you still can't find it in the configuration, in order to access the plugins' variables simply wrap the code in the Jenkinsfile with "BuildUser" class as so: </p>

```<code> wrap([$class: 'BuildUser']) {
      echo "BUILD_USER=${BUILD_USER}"
      echo "env.BUILD_USER_EMAIL=${env.BUILD_USER_EMAIL}"
  }
</code>```

Body:
If your Jenkins' version is greater than 1.609 and you still can't find it in the configuration, in order to access the plugins' variables simply wrap the code in the Jenkinsfile with "BuildUser" class as so:

 wrap([$class: 'BuildUser']) {
      echo "BUILD_USER=${BUILD_USER}"
      echo "env.BUILD_USER_EMAIL=${env.BUILD_USER_EMAIL}"
  }


问:
How to `Insert` a new folder into a path in MYSQL?
Fiddle link:

http://sqlfiddle.com/#!9/04d439/1

Problem:

I need to update a few records. Specifically the file_path column.

All I need to do is, add a folder called 'Archive' before the file.

For example, a record out of the table:

```<code>\\server\data\folder1\folder2\file.docx
</code>```

How can I update path to the following:

```<code>\\server\data\folder1\folder2\Archive\file.docx
</code>```

Simply adding 'Archive` folder before the file.

This is what I have tried, but too much copy and pasting values.

```<code>update file_path set path = '\\\\server\\data\\folder1\\folder2\\Archive\\file.docx' where id = 1;
</code>```

How can this be achieved, without writing out the path?

答:
```<code>UPDATE file_path
SET path = CONCAT(SUBSTRING_INDEX(path,
                                  '\\',
                                  LENGTH(path) - LENGTH(REPLACE(path, '\\', ''))),
                  '\\Archive\\',
                  SUBSTRING_INDEX(path, '\\', -1));
</code>```

fiddle

Body:
Fiddle link:

http://sqlfiddle.com/#!9/04d439/1

Problem:

I need to update a few records. Specifically the file_path column.

All I need to do is, add a folder called 'Archive' before the file.

For example, a record out of the table:

\\server\data\folder1\folder2\file.docx

How can I update path to the following:

\\server\data\folder1\folder2\Archive\file.docx

Simply adding 'Archive` folder before the file.

This is what I have tried, but too much copy and pasting values.

update file_path set path = '\\\\server\\data\\folder1\\folder2\\Archive\\file.docx' where id = 1;

How can this be achieved, without writing out the path?

Body:
UPDATE file_path
SET path = CONCAT(SUBSTRING_INDEX(path,
                                  '\\',
                                  LENGTH(path) - LENGTH(REPLACE(path, '\\', ''))),
                  '\\Archive\\',
                  SUBSTRING_INDEX(path, '\\', -1));

fiddle


问:
Kotlin Handler class: How to stop a thread - from inside of run() - when a condition is met?
I am currently learning how to develop android applications. For my first app, I wanted to build a simple clicker with a primitive combat sistem.

In my code, I have created a Handler instance and a Runnable object. Inside of this "delayed loop" the enemy attacks the player instance every 3 seconds, dealing damage. Inside the loop I also test when the player's hp is less or equals 0; when the condition is met I want to stop the runnable object.

How do i do this? I tried calling a function stopCombat() which contains Handler.removeCallbacks, but i can't call a function before declaration. I tried putting .removeCallbacks(this) inside run(), but it also doesn't work.

```<code>val mainHandler = Handler(Looper.getMainLooper())

    fun playerDied() {
        ongoingFight = false
        combatLog.append("${myPlayer.name} has been defeated!\n")
        myPlayer.currentHitPoints = myPlayer.maxHitPoints / 2
        myPlayer.gold = 0
        gold.text = "${myPlayer.gold} gold"
    }

    val performTask = object : Runnable {
        override fun run() {
            val enemyHit = enemyAttack(myPlayer, myEnemy)
            // Call a function to stop this thread if the condition is met:
            if (myPlayer.takeDamage(enemyHit)) { //myPlayer.takeDamage returns true if hp <= 0
                playerDied()
                stopCombat() // called before declaration
                mainHandler.removeCallbacks(this) // tried, doesn't work
            }
            playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
            mainHandler.postDelayed(this, 3000)
        }
    }

    fun stopCombat(){
        mainHandler.removeCallbacks(performTask)
    }
</code>```

答:
Set a boolean to determine if you’re going to post the runnable again

```<code>
override fun run() {
    val enemyHit = enemyAttack(myPlayer, myEnemy)
    val died = myPlayer.takeDamage(enemyHit))
    if (died)
        playerDied()
   playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
    if (!died)
        mainHandler.postDelayed(this, 3000)
}
</code>```

Sorry for formatting—on my phone.

Body:
I am currently learning how to develop android applications. For my first app, I wanted to build a simple clicker with a primitive combat sistem.

In my code, I have created a Handler instance and a Runnable object. Inside of this "delayed loop" the enemy attacks the player instance every 3 seconds, dealing damage. Inside the loop I also test when the player's hp is less or equals 0; when the condition is met I want to stop the runnable object.

How do i do this? I tried calling a function stopCombat() which contains Handler.removeCallbacks, but i can't call a function before declaration. I tried putting .removeCallbacks(this) inside run(), but it also doesn't work.

val mainHandler = Handler(Looper.getMainLooper())

    fun playerDied() {
        ongoingFight = false
        combatLog.append("${myPlayer.name} has been defeated!\n")
        myPlayer.currentHitPoints = myPlayer.maxHitPoints / 2
        myPlayer.gold = 0
        gold.text = "${myPlayer.gold} gold"
    }

    val performTask = object : Runnable {
        override fun run() {
            val enemyHit = enemyAttack(myPlayer, myEnemy)
            // Call a function to stop this thread if the condition is met:
            if (myPlayer.takeDamage(enemyHit)) { //myPlayer.takeDamage returns true if hp <= 0
                playerDied()
                stopCombat() // called before declaration
                mainHandler.removeCallbacks(this) // tried, doesn't work
            }
            playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
            mainHandler.postDelayed(this, 3000)
        }
    }

    fun stopCombat(){
        mainHandler.removeCallbacks(performTask)
    }

Body:
Set a boolean to determine if you’re going to post the runnable again

override fun run() {
    val enemyHit = enemyAttack(myPlayer, myEnemy)
    val died = myPlayer.takeDamage(enemyHit))
    if (died)
        playerDied()
   playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
    if (!died)
        mainHandler.postDelayed(this, 3000)
}

Sorry for formatting—on my phone.


问:
Attempting to define a non fixed argument function in C
I'm trying this code just to get the basics of defining a function that takes un unknown number of arguments, becasue that function will call sprintf, in C.

So my code so far looks like this:

```<code>#include <QCoreApplication>
#include <QDebug>
#include <stdio.h>
#include <math.h>

void debugMsg(const char *control_string,...);

char __errorLog[100];

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

    debugMsg("Este es un mensaje de debug con 5 parametros %d %d %d %d %d",1,2,4,56,57);

    return a.exec();
}

void debugMsg(const char *control_string, ...){
    va_list argptr;
    va_start(argptr,control_string);
    sprintf(__errorLog,control_string,argptr);
    va_end(argptr);
    qDebug() << __errorLog;
}
</code>```

NOTE: I'm using this in QtCreator as it is the fastest way that I had to get some very simple, pure C, code working in order to test out stuff I'm learning.

So this was taken form an answer to the very question I posed myself (how to create a function that takes many arguments).

The code kind of works as it produces as a result:

```<code>Este es un mensaje de debug con 5 parametros 1262382712 4 56 57 0
</code>```

I think the va_start function takes my arguments "shifted" for lack of a better word so the very first argument passed to the sprintf function is not a 1 but some memory location (maybe the pointer for the control_string?) and the last is a 0 instead of 57.

So my question is, what am I doing wrong and how can I correct it?

答:
Rather than using sprintf directly, you need to use vsprintf which takes a va_list argument rather than taking values directly. The values you see in your output are some int representation (because %d) of a va_list (I guess it's a pointer), and then random memory (which is undefined behavior).

```<code>vsprintf(__errorLog, control_string, argptr);
</code>```

See http://www.cplusplus.com/reference/cstdio/vsprintf/

Body:
I'm trying this code just to get the basics of defining a function that takes un unknown number of arguments, becasue that function will call sprintf, in C.

So my code so far looks like this:

#include <QCoreApplication>
#include <QDebug>
#include <stdio.h>
#include <math.h>

void debugMsg(const char *control_string,...);

char __errorLog[100];

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

    debugMsg("Este es un mensaje de debug con 5 parametros %d %d %d %d %d",1,2,4,56,57);

    return a.exec();
}

void debugMsg(const char *control_string, ...){
    va_list argptr;
    va_start(argptr,control_string);
    sprintf(__errorLog,control_string,argptr);
    va_end(argptr);
    qDebug() << __errorLog;
}

NOTE: I'm using this in QtCreator as it is the fastest way that I had to get some very simple, pure C, code working in order to test out stuff I'm learning.

So this was taken form an answer to the very question I posed myself (how to create a function that takes many arguments).

The code kind of works as it produces as a result:

Este es un mensaje de debug con 5 parametros 1262382712 4 56 57 0

I think the va_start function takes my arguments "shifted" for lack of a better word so the very first argument passed to the sprintf function is not a 1 but some memory location (maybe the pointer for the control_string?) and the last is a 0 instead of 57.

So my question is, what am I doing wrong and how can I correct it?

Body:
Rather than using sprintf directly, you need to use vsprintf which takes a va_list argument rather than taking values directly. The values you see in your output are some int representation (because %d) of a va_list (I guess it's a pointer), and then random memory (which is undefined behavior).

vsprintf(__errorLog, control_string, argptr);

See http://www.cplusplus.com/reference/cstdio/vsprintf/


问:
When pushing a React app to GitHub pages, is it required that the default remote branch be `gh-pages`?
As a side project, I am developing a simple local React app, using Create React App.  I periodically push my edits online, to GitHub pages, using npm run deploy.  As expected, the GitHub repo for this project now has two branches:

```<code>master
gh-pages
</code>```

In this GitHub repo, the default branch is gh-pages.

Does npm run deploy require that the default branch be gh-pages?  Or can I safely change it to master (screenshot), without it affecting npm run deploy?  Specifically, I would like to change the default branch to master, and still be able to push my local app to GitHub pages.1

The reason I’d like to change the default branch to master is because the master branch is the branch that actually displays the code I wrote, as well as the README file for the GitHub repo.  So I'd like to share a link to this repo with collaborators/potential employers, and have my code/README file displayed by default.

My app on GitHub pages is here:   https://cagross.github.io/react-specials/

The GitHub repo is here:  https://github.com/cagross/react-specials

Thanks.

1 Whether I continue to do that with npm run deploy or some other command.

答:
https://help.github.com/en/github/working-with-github-pages/about-github-pages#publishing-sources-for-github-pages-sites

The default publishing source for user and organization sites is the master branch. If the repository for your user or organization site has a master branch, your site will publish automatically from that branch. You cannot choose a different publishing source for user or organization sites.

The default publishing source for a project site is the gh-pages branch. If the repository for your project site has a gh-pages branch, your site will publish automatically from that branch.

Project sites can also be published from the master branch or a /docs folder on the master branch.

(Emphasize is mine — phd)

Body:
As a side project, I am developing a simple local React app, using Create React App.  I periodically push my edits online, to GitHub pages, using npm run deploy.  As expected, the GitHub repo for this project now has two branches:

master
gh-pages

In this GitHub repo, the default branch is gh-pages.

Does npm run deploy require that the default branch be gh-pages?  Or can I safely change it to master (screenshot), without it affecting npm run deploy?  Specifically, I would like to change the default branch to master, and still be able to push my local app to GitHub pages.1

The reason I’d like to change the default branch to master is because the master branch is the branch that actually displays the code I wrote, as well as the README file for the GitHub repo.  So I'd like to share a link to this repo with collaborators/potential employers, and have my code/README file displayed by default.

My app on GitHub pages is here:   https://cagross.github.io/react-specials/

The GitHub repo is here:  https://github.com/cagross/react-specials

Thanks.

1 Whether I continue to do that with npm run deploy or some other command.


问:
Android: Google Map v2 not showing map for release apk
My google map app works fine on device with debug google map API KEY but when I create signed apk for my app with release google map API KEY, it does not display map.
To generate release mode google API KEY , i am using SHA1 fingerprint with my keystore.
And i am also defining "signing and build types" in my project Settings as explained by developer.android.com(http://developer.android.com/tools/publishing/app-signing.html).

Tried every possible solution(removing apk and than reinstalling it again, restarting the device, cleaning the project ). nothing worked.
Anybody have a good solution to my problem please help.
FYI  Using android studios platform.

答:
Below method worked for me:

Put google maps api key in manifest as hardcoded text mentioned by @Florence Herrou

Android Studio creates inside:

```<code>app\src\debug\res\values\google_maps_api.xml (debug) //add key here
</code>```

Add key inside ->

```<code>app\src\release\res\values\google_maps_api.xml (release) //add key here
</code>```

Body:
Below method worked for me:

Put google maps api key in manifest as hardcoded text mentioned by @Florence Herrou

Android Studio creates inside:

app\src\debug\res\values\google_maps_api.xml (debug) //add key here

Add key inside ->

app\src\release\res\values\google_maps_api.xml (release) //add key here


问:
Excel formula to total cells containing numbers in brackets without the text
I would like to know if there's an Excel formula to input into Cell B2 to total up the number of 'A' hours in Row 1?

Thank you

答:
Try this

```<code>=SUM(IF(LEFT(B1:F1,1)="A",IF(MID(B1:F1,4,2)="0.",4,--MID(B1:F1,4,1)),0))
</code>```

Enter as array formula with CTRL + SHIFT + ENTER

EDIT relating to your comment

```<code>=+SUM(IF(LEFT(B10:F10,1)="A",IF(MID(B10:F10,4,2)="0.",4,--MID(B10:F10,4,SEARCH("h",B10:F10)-4)),0))
</code>```

Body:
Try this

=SUM(IF(LEFT(B1:F1,1)="A",IF(MID(B1:F1,4,2)="0.",4,--MID(B1:F1,4,1)),0))

Enter as array formula with CTRL + SHIFT + ENTER

EDIT relating to your comment

=+SUM(IF(LEFT(B10:F10,1)="A",IF(MID(B10:F10,4,2)="0.",4,--MID(B10:F10,4,SEARCH("h",B10:F10)-4)),0))


问:
Dynamic @RequestParam in @RestController
I have a controller:

```<code>@RestController
@RequestMapping(value = UserRestController.REST_URL, produces =
MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {

static final String REST_URL = "/customers";

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}
</code>```

It succesfully handle such requests,as:

```<code>GET:    /customers/
</code>```

And I want to get users by some parameters.For example, email:

```<code>GET:   /customers?email=someemail@gmail.
</code>```

I tried:

```<code>@GetMapping("/")
public User getByEmail(@RequestParam(value = "email") String email) {
    return super.getByEmail(email);
}
</code>```

and expectedly I receive an exception, as "/" is already mapped on getAll-class.
Is there any ways to solve this problem?

答:
```<code>@GetMapping
public Object get((@RequestParam(value = "email", required = false) String email) {
    if (email != null && !email.isEmpty()) {
     return super.getByEmail(email);
    } else {
      return service.getAll();
    }
}
</code>```

Body:
I have a controller:

@RestController
@RequestMapping(value = UserRestController.REST_URL, produces =
MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {

static final String REST_URL = "/customers";

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}

It succesfully handle such requests,as:

GET:    /customers/

And I want to get users by some parameters.For example, email:

GET:   /customers?email=someemail@gmail.

I tried:

@GetMapping("/")
public User getByEmail(@RequestParam(value = "email") String email) {
    return super.getByEmail(email);
}

and expectedly I receive an exception, as "/" is already mapped on getAll-class.
Is there any ways to solve this problem?


问:
Why I get the error: list index out of range

def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ
```

The error is produced by the last if and I don't understand why

答:
That means len(nums) == 0. Try something like

if nums and nums[0] != 13:

Body:
def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ

The error is produced by the last if and I don't understand why


问:
Rolling difference in Pandas
Does anyone know an efficient function/method such as pandas.rolling_mean, that would calculate the rolling difference of an array

This is my closest solution:

```<code>roll_diff = pd.Series(values).diff(periods=1)
</code>```

However, it only calculates single-step rolling difference. Ideally the step size would be editable (i.e. difference between current time step and n last steps).

I've also written this, but for larger arrays, it is quite slow:

```<code>def roll_diff(values,step):
    diff = []
    for i in np.arange(step, len(values)-1):
        pers_window = np.arange(i-1,i-step-1,-1)
        diff.append(np.abs(values[i] - np.mean(values[pers_window])))
    diff = np.pad(diff, (0, step+1), 'constant')
    return diff
</code>```

答:
If you got KeyError: 0, try with iloc:

```<code>import pandas

x = pandas.DataFrame({
    'x_1': [0, 1, 2, 3, 0, 1, 2, 500, ],},
    index=[0, 1, 2, 3, 4, 5, 6, 7])

x['x_1'].rolling(window=2).apply(lambda x: x.iloc[1] - x.iloc[0])
</code>```

Title: Rolling difference in Pandas

Body:
Does anyone know an efficient function/method such as pandas.rolling_mean, that would calculate the rolling difference of an array

This is my closest solution:

roll_diff = pd.Series(values).diff(periods=1)

However, it only calculates single-step rolling difference. Ideally the step size would be editable (i.e. difference between current time step and n last steps).

I've also written this, but for larger arrays, it is quite slow:

def roll_diff(values,step):
    diff = []
    for i in np.arange(step, len(values)-1):
        pers_window = np.arange(i-1,i-step-1,-1)
        diff.append(np.abs(values[i] - np.mean(values[pers_window])))
    diff = np.pad(diff, (0, step+1), 'constant')
    return diff

Body:
If you got KeyError: 0, try with iloc:

import pandas

x = pandas.DataFrame({
    'x_1': [0, 1, 2, 3, 0, 1, 2, 500, ],},
    index=[0, 1, 2, 3, 4, 5, 6, 7])

x['x_1'].rolling(window=2).apply(lambda x: x.iloc[1] - x.iloc[0])


问:
How to split a dataframe and attach the splitted part in new column?
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

```<code>#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)
</code>```

答:
You can use Reduce and cbind to cbind each row of a data.frame in one row and keep the type of the columns.

```<code>Reduce(function(x,y) cbind(x, df[y,]), 2:nrow(df), df[1,])
#  ID     Date value ID     Date value ID     Date value
#1  1 20200101   4.5  2 20200101     5  3 20200101     7
#Equivalent for the sample dataset: cbind(cbind(df[1,], df[2,]), df[3,])
</code>```

or do.call with split:

```<code>do.call(cbind, split(df, 1:nrow(df)))
#  1.ID   1.Date 1.value 2.ID   2.Date 2.value 3.ID   3.Date 3.value
#1    1 20200101     4.5    2 20200101       5    3 20200101       7
#Equivalent for the sample dataset: cbind(df[1,], df[2,], df[3,])
</code>```

In case you have several rows per ID you can try:

```<code>x <- split(df, df$ID)
y <- max(unlist(lapply(x, nrow)))
do.call(cbind, lapply(x, function(i) i[1:y,]))
</code>```

Body:
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)

Body:
You can use Reduce and cbind to cbind each row of a data.frame in one row and keep the type of the columns.

Reduce(function(x,y) cbind(x, df[y,]), 2:nrow(df), df[1,])
#  ID     Date value ID     Date value ID     Date value
#1  1 20200101   4.5  2 20200101     5  3 20200101     7
#Equivalent for the sample dataset: cbind(cbind(df[1,], df[2,]), df[3,])

or do.call with split:

do.call(cbind, split(df, 1:nrow(df)))
#  1.ID   1.Date 1.value 2.ID   2.Date 2.value 3.ID   3.Date 3.value
#1    1 20200101     4.5    2 20200101       5    3 20200101       7
#Equivalent for the sample dataset: cbind(df[1,], df[2,], df[3,])

In case you have several rows per ID you can try:

x <- split(df, df$ID)
y <- max(unlist(lapply(x, nrow)))
do.call(cbind, lapply(x, function(i) i[1:y,]))


问:
Which database can be used with Xcode and at the same time be populated through a website?
We are trying to create an iPhone application that will automatically receive data from a database. Which is a database that will work with Xcode. Our goal is that users can go to our website and input information. That data will be recorded to a database. Once the user downloads our app, the info should then be retrieved from the database and included in the app. We are wondering what database is suitable. It must be able to receive information from a website AND submit it to an application.</p>

答:
Couchbase's new iOS-Couchbase framework is in beta right now - all the functionality of Apache CouchDB on your favourite developer platform - at https://github.com/couchbaselabs/iOS-Couchbase. the iOS release is new but we're looking for it to go places!

Its awesome sync abilities would allow you to pull down any relevant content from your website via HTTP/JSON, or further formats using shows and lists if needed. Pushing data the other way is just as easy. Sync can be continuous, or on demand, bidirectional or one way.

Take a look at some of the Couch App frameworks (not for iOS but for your website)

http://techzone.couchbase.com/community/articles/couchdb/recipes

http://www.mail-archive.com/user@couchdb.apache.org/msg13928.html lots of comments on this thread

A+
Dave


问:
Why am I getting ‘panic: runtime error: invalid memory address or nil pointer dereference’ accessing Firestore on new computer?
I get a Panic if I attempt to run the tests or runthe app directly via: go run main.go
The code works great on my old Macbook Pro. It panics on my new Macbook Pro.

I believe the error has Something to do with accessing the Firestore datastore but I'm not sure what's going wrong.

I'm running the same code so datastore Keys and everything else should be identical.

Here is the Github repo:
https://github.com/golangnewb/FirestoreTestHttp

Working Computer:
go version go1.11.2 darwin/amd64

Panic Computer:
go version go1.13.5 darwin/amd64

```<code>❯ go test
--- FAIL: TestCities (0.01s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x14d557a]

goroutine 6 [running]:
testing.tRunner.func1(0xc000312200)
    /usr/local/go/src/testing/testing.go:874 +0x3a3
panic(0x15ac100, 0x1b3e740)
    /usr/local/go/src/runtime/panic.go:679 +0x1b2
cloud.google.com/go/firestore.(*Client).path(...)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:107
cloud.google.com/go/firestore.(*Client).Collection(0x0, 0x1677ac0, 0x6, 0x14)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:122 +0x9a
_/Users/XXX/Dropbox/go/src/firestoreTestHttp.addCitiesFirestore(0x5e4c4feb, 0xc000064760)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/city_handlers_test.go:218 +0x13d
_/Users/XXX/Dropbox/go/src/firestoreTestHttp.TestCities(0xc000312200)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/city_handlers_test.go:19 +0x26
testing.tRunner(0xc000312200, 0x16a1c98)
    /usr/local/go/src/testing/testing.go:909 +0xc9
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:960 +0x350
exit status 2
FAIL    _/Users/XXX/Dropbox/go/src/firestoreTestHttp    0.165s
</code>```

Here is the panic if I try to run via:

❯ go run main.go

```<code>
2020/02/18 17:19:39 http: panic serving [::1]:60479: runtime error: invalid memory address or nil pointer dereference
goroutine 9 [running]:
net/http.(*conn).serve.func1(0xc00027c6e0)
    /usr/local/go/src/net/http/server.go:1767 +0x139
panic(0x15a69c0, 0x1b39a50)
    /usr/local/go/src/runtime/panic.go:679 +0x1b2
cloud.google.com/go/firestore.(*Client).path(...)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:107
cloud.google.com/go/firestore.(*Client).Collection(0x0, 0x16728ba, 0x6, 0x14)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:122 +0x9a
main.indexHandler(0x1744360, 0xc000322000, 0xc0002c8200)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/main.go:50 +0xa2
net/http.HandlerFunc.ServeHTTP(0x169da80, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2007 +0x44
net/http.(*ServeMux).ServeHTTP(0xc0002ea100, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2387 +0x1bd
net/http.serverHandler.ServeHTTP(0xc000312000, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2802 +0xa4
net/http.(*conn).serve(0xc00027c6e0, 0x17457a0, 0xc00008cf80)
    /usr/local/go/src/net/http/server.go:1890 +0x875
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2928 +0x384
</code>```

答:
Although I dont feel well in Go I will try a shot. If I am wrong just let me know.

From the error it seems that Client is nil. In attached Git repo in main you are logging that it should be set as environment variable GCLOUD_PROJECT, however I haven't found any so.Getenv function that gets this value. Maybe this value is wrong...?

So I guess this statement client, _ := firestore.NewClient(ctx, projectID) is being called with wrong projectID. In the statement error handling is omitted, so we do not know if the client has been created properly. If it was not created, that we should get such error.

Maybe you should add error handling like in example in Go Firestore Reference, to ensure that there is no error during client creation.

I hope this will help you!

Body:
I get a Panic if I attempt to run the tests or runthe app directly via: go run main.go
The code works great on my old Macbook Pro. It panics on my new Macbook Pro.

I believe the error has Something to do with accessing the Firestore datastore but I'm not sure what's going wrong.

I'm running the same code so datastore Keys and everything else should be identical.

Here is the Github repo:
https://github.com/golangnewb/FirestoreTestHttp

Working Computer:
go version go1.11.2 darwin/amd64

Panic Computer:
go version go1.13.5 darwin/amd64

❯ go test
--- FAIL: TestCities (0.01s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x14d557a]

goroutine 6 [running]:
testing.tRunner.func1(0xc000312200)
    /usr/local/go/src/testing/testing.go:874 +0x3a3
panic(0x15ac100, 0x1b3e740)
    /usr/local/go/src/runtime/panic.go:679 +0x1b2
cloud.google.com/go/firestore.(*Client).path(...)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:107
cloud.google.com/go/firestore.(*Client).Collection(0x0, 0x1677ac0, 0x6, 0x14)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:122 +0x9a
_/Users/XXX/Dropbox/go/src/firestoreTestHttp.addCitiesFirestore(0x5e4c4feb, 0xc000064760)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/city_handlers_test.go:218 +0x13d
_/Users/XXX/Dropbox/go/src/firestoreTestHttp.TestCities(0xc000312200)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/city_handlers_test.go:19 +0x26
testing.tRunner(0xc000312200, 0x16a1c98)
    /usr/local/go/src/testing/testing.go:909 +0xc9
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:960 +0x350
exit status 2
FAIL    _/Users/XXX/Dropbox/go/src/firestoreTestHttp    0.165s

Here is the panic if I try to run via:

❯ go run main.go

2020/02/18 17:19:39 http: panic serving [::1]:60479: runtime error: invalid memory address or nil pointer dereference
goroutine 9 [running]:
net/http.(*conn).serve.func1(0xc00027c6e0)
    /usr/local/go/src/net/http/server.go:1767 +0x139
panic(0x15a69c0, 0x1b39a50)
    /usr/local/go/src/runtime/panic.go:679 +0x1b2
cloud.google.com/go/firestore.(*Client).path(...)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:107
cloud.google.com/go/firestore.(*Client).Collection(0x0, 0x16728ba, 0x6, 0x14)
    /Users/XXX/go/src/cloud.google.com/go/firestore/client.go:122 +0x9a
main.indexHandler(0x1744360, 0xc000322000, 0xc0002c8200)
    /Users/XXX/Dropbox/go/src/firestoreTestHttp/main.go:50 +0xa2
net/http.HandlerFunc.ServeHTTP(0x169da80, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2007 +0x44
net/http.(*ServeMux).ServeHTTP(0xc0002ea100, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2387 +0x1bd
net/http.serverHandler.ServeHTTP(0xc000312000, 0x1744360, 0xc000322000, 0xc0002c8200)
    /usr/local/go/src/net/http/server.go:2802 +0xa4
net/http.(*conn).serve(0xc00027c6e0, 0x17457a0, 0xc00008cf80)
    /usr/local/go/src/net/http/server.go:1890 +0x875
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2928 +0x384


问:
PhpStorm Library doesn't see library
```<code><?php
use MetzWeb\Instagram\Instagram as InstagramAlias;

$instagram = new InstagramAlias(array(
    'apiKey'      => 'YOUR_APP_KEY',
    'apiSecret'   => 'YOUR_APP_SECRET',
    'apiCallback' => 'YOUR_APP_CALLBACK'
));

echo "<a href='{$instagram->getLoginUrl()}'>Login with Instagram</a>";
</code>```

I added the library with composer when ı make

```<code>use MetzWeb\Instagram\Instagram
</code>```

it saw it but when i start to write the code it says there is no class named instagram

```<code>Fatal error: Uncaught Error: Class 'MetzWeb\Instagram\Instagram' not found in C:\Users\Zera\İnstagram\Insta.php:4 Stack trace: #0 {main} thrown in C:\Users\Zera\İnstagram\Insta.php on line 4
</code>```

答:
I solved it.

Even though you add the library with "use ......" you need to make

```<code>require "the source path of the class"
</code>```

Title: PhpStorm Library doesn't see library

Body:
<?php
use MetzWeb\Instagram\Instagram as InstagramAlias;

$instagram = new InstagramAlias(array(
    'apiKey'      => 'YOUR_APP_KEY',
    'apiSecret'   => 'YOUR_APP_SECRET',
    'apiCallback' => 'YOUR_APP_CALLBACK'
));

echo "getLoginUrl()}'>Login with Instagram";

I added the library with composer when ı make

use MetzWeb\Instagram\Instagram

it saw it but when i start to write the code it says there is no class named instagram

Fatal error: Uncaught Error: Class 'MetzWeb\Instagram\Instagram' not found in C:\Users\Zera\İnstagram\Insta.php:4 Stack trace: #0 {main} thrown in C:\Users\Zera\İnstagram\Insta.php on line 4

Body:
I solved it.

Even though you add the library with "use ......" you need to make

require "the source path of the class"


问:
I can't update my string value with React hooks
Its like the simplest of cases you can think of,

I have a select which updates a string according to the value which is supposed to update a property of the select itself (its background color)

I am using React hooks and Styled Components to achieve this.

I have Redux to be able to bind it an immutable array of colors in the future.

The question is simple, why can't I update the state? I have tried to print it and it is always an empty string.

Here is my styles file

```<code>let currentColor = '';

const SelectColor = styled.div`
  select{
    background-color: ${currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;
</code>```

This is the component that isn't updating the selectValue for reasons I cannot grasp(I have attempted to console log it and it returns always empty string).
I have checked the documentation a couple times and it seems like its meant to be updated this way so I am clueless...

```<code>const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  const handleChange = useCallback(
    (e) => {
      setSelectValue(e.target.value);
      console.log(selectValue);
    },colorList
  );

  return (
    <SelectColor>
      <span className='label'>{label}</span>
      <select onChange={e=>handleChange(e)}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;
</code>```

答:
Your handlechange function is a bit strange to me as the function itself does not take in a variable. try writing it like this </p>

```<code> const handlestring = (e) => {
   setSelectedValue(e.target.value)
}
</code>```

Body:
Its like the simplest of cases you can think of,

I have a select which updates a string according to the value which is supposed to update a property of the select itself (its background color)

I am using React hooks and Styled Components to achieve this.

I have Redux to be able to bind it an immutable array of colors in the future.

The question is simple, why can't I update the state? I have tried to print it and it is always an empty string.

Here is my styles file

let currentColor = '';

const SelectColor = styled.div`
  select{
    background-color: ${currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;

This is the component that isn't updating the selectValue for reasons I cannot grasp(I have attempted to console log it and it returns always empty string).
I have checked the documentation a couple times and it seems like its meant to be updated this way so I am clueless...

const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  const handleChange = useCallback(
    (e) => {
      setSelectValue(e.target.value);
      console.log(selectValue);
    },colorList
  );

  return (
    <SelectColor>
      {label}
      <select onChange={e=>handleChange(e)}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;

Body:
Your handlechange function is a bit strange to me as the function itself does not take in a variable. try writing it like this

 const handlestring = (e) => {
   setSelectedValue(e.target.value)
}


问:
javasript in angular 8
There's a solution on js -

codepen.io/skovtun/pen/VwLvXPB

Can't make an analog for Angular8+.

I need the center block to have a fixed width (1200px), and it is evaluated and compressed by the left, right and both sidebars immediately when they are opened. They should not overlap with the content.

答: You Can Dynamic every css class Using [ngClass] Depending on your logic ..it will render when the value will change..</p>

Title: javasript in angular 8