问:
ionic angular ngrx how to access a store
i am working on an ionic angular cordova app. I am trying to print my state, for example, all the objects in the state. However it cannot find the objects i putted inside.

model

```<code>export interface Room {
    id: number;
    name: string;
}
</code>```

action

```<code>export class AddRoom implements Action {
    readonly type = ADD_ROOM;

    constructor(public payload: Room){}
}
</code>```

reducer

```<code>const initialState: Room = {
    id: 111,
    name: 'null'
}

export function reducer(state: Room[] = [initialState], action: RoomActions.Actions ){
    switch (action.type) {
        case RoomActions.ADD_ROOM:
            return [...state];
        case RoomActions.REMOVE_ROOM:
            state.splice(action.payload, 1);
            return state;
            default:
                return state;
    }
}
</code>```

code

```<code>rooms2: any;

constructor(private store: Store<AppState>){
      this.rooms2 = this.store.select('room');
      }
console.log(this.rooms2);
</code>```

but in the console, i can only see a store object in which i cannot find any data i am looking for.

答:
The NgRx Store is reactive.

this.rooms2 = this.store.select('room'); returns an Observable, and this is probably what you're seeing.

Try the following:

```<code>this.rooms2.subscribe(rooms => console.log(rooms))
</code>```

Body:
i am working on an ionic angular cordova app. I am trying to print my state, for example, all the objects in the state. However it cannot find the objects i putted inside.

model

export interface Room {
    id: number;
    name: string;
}

action

export class AddRoom implements Action {
    readonly type = ADD_ROOM;

    constructor(public payload: Room){}
}

reducer

const initialState: Room = {
    id: 111,
    name: 'null'
}

export function reducer(state: Room[] = [initialState], action: RoomActions.Actions ){
    switch (action.type) {
        case RoomActions.ADD_ROOM:
            return [...state];
        case RoomActions.REMOVE_ROOM:
            state.splice(action.payload, 1);
            return state;
            default:
                return state;
    }
}

code

rooms2: any;

constructor(private store: Store<AppState>){
      this.rooms2 = this.store.select('room');
      }
console.log(this.rooms2);

but in the console, i can only see a store object in which i cannot find any data i am looking for.

Body:
The NgRx Store is reactive.

this.rooms2 = this.store.select('room'); returns an Observable, and this is probably what you're seeing.

Try the following:

this.rooms2.subscribe(rooms => console.log(rooms))


来源: stackexchange

问:
How to resend verification code while verifying/updating attribute in aws-amplify/ aws-cognito?
How to resend verification code while verifying/updating email/phone attribute in aws-amplify/ aws-cognito, I'm using this code, to verify email/phone:

```<code>const responce = await Auth.verifyCurrentUserAttributeSubmit("email", confirmationCode)
</code>```

Is there a possibility to resend the code?

答:
I am sure you already tried this but would calling this method again, asking for a new code, not work for you:

https://aws-amplify.github.io/amplify-js/api/classes/authclass.html#verifyuserattribute

ContentLicense: CC BY-SA 4.0

Body:
How to resend verification code while verifying/updating email/phone attribute in aws-amplify/ aws-cognito, I'm using this code, to verify email/phone:

const responce = await Auth.verifyCurrentUserAttributeSubmit("email", confirmationCode)

Is there a possibility to resend the code?


问:
How can I delete a JS created LI with a JS created button?
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

```<code>        <div class="entry-field">
          <label class="task-input" for="task-input">Task:</label>
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>
        </div>
        <section class="task-list">
          <h2>Task List</h2>
          <div class="list-wrap"></div>
            <ul class="item-log">
              <li class="list-item">
                <span class="item-text">this is the item</span>
                <button class="delete-btn">delete</button>
              </li>
            </ul>
          </div>
        </section>
      </main>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

</code>```

答:
Assign a click handler on Delete element creation.

Create an array of tasks to prepopulate

const myTasks = [
  "This is the item",
  "Well, this is Another item"
];

const EL_text = document.querySelector("#text");
const EL_add = document.querySelector("#add");
const EL_tasks = document.querySelector("#tasks");

function addTask(text) {

  // Determine if we have a text string argument (prepopulate)
  // otherwise grab the input value:
  text = typeof text === 'string' ? text : EL_text.value.trim(); // Trim your values!
  if (!text) return; // do nothing if no value!

  const EL_task = document.createElement('li');
  const EL_delete = document.createElement('button');

  EL_delete.textContent = "Delete";
  EL_delete.addEventListener('click', () => EL_task.remove());

  EL_task.insertAdjacentHTML('afterbegin', `<div>${text}</div>`);
  EL_task.appendChild(EL_delete);

  EL_tasks.appendChild(EL_task);
  EL_text.value = ''; // Clear current input text value
}

EL_add.addEventListener("click", addTask);
// Prepopulate
myTasks.forEach(addTask);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tasks {
  padding: 0;
  list-style: none;
}
#tasks li {
  display: flex;
  background: #eee;
  padding: 0.6em;
  margin-bottom: 0.5em;
  border-radius: 0.4em;
}
#tasks li div {
  flex: 1;
}</code>```

Task:<input id="text" type="text" placeholder="Enter text">
<button id="add">ADD</button>

```

Body:
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

          Task:
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>

Task List

                this is the item
                <button class="delete-btn">delete</button>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

Body:
Assign a click handler on Delete element creation.

Create an array of tasks to prepopulate

const myTasks = [
  "This is the item",
  "Well, this is Another item"
];

const EL_text = document.querySelector("#text");
const EL_add = document.querySelector("#add");
const EL_tasks = document.querySelector("#tasks");

function addTask(text) {

  // Determine if we have a text string argument (prepopulate)
  // otherwise grab the input value:
  text = typeof text === 'string' ? text : EL_text.value.trim(); // Trim your values!
  if (!text) return; // do nothing if no value!

  const EL_task = document.createElement('li');
  const EL_delete = document.createElement('button');

  EL_delete.textContent = "Delete";
  EL_delete.addEventListener('click', () => EL_task.remove());

  EL_task.insertAdjacentHTML('afterbegin', `<div>${text}</div>`);
  EL_task.appendChild(EL_delete);

  EL_tasks.appendChild(EL_task);
  EL_text.value = ''; // Clear current input text value
}

EL_add.addEventListener("click", addTask);
// Prepopulate
myTasks.forEach(addTask);

#tasks {
  padding: 0;
  list-style: none;
}
#tasks li {
  display: flex;
  background: #eee;
  padding: 0.6em;
  margin-bottom: 0.5em;
  border-radius: 0.4em;
}
#tasks li div {
  flex: 1;
}

<label>Task:<input id="text" type="text" placeholder="Enter text"></label>
<button id="add">ADD</button>
<ul id="tasks"></ul>


问:
React Performance: What is a good strategy to maintain constant references for event handler props?
Assuming I have a slow component, it makes sense to memoize it, e.g.

```<code>const SlowButton = ({onClick}) => {
    // make some heat
    const value = (function f(n) { return n < 2 ? Math.random() : f(n-1) + f(n-2)})(32)|0;
    return <button onClick={() => onClick(value)}>{value}</button>
}
const MemoButton = React.memo(SlowButton);
</code>```

If I use the MemoButton in a component like:

```<code>const Counter = () => {
    const [clicks, setClicks ] = useState(0);
    const handleClick = () => {
        setClicks(clicks + 1);
    }
    return <div>
            <div>{clicks}</div>
            <MemoButton onClick={handleClick} />
        </div>
}
</code>```

Then the MemoButton still re-renders every time because the onClick property is a new function every render.  It is pretty easy to resolve this with:

```<code>const Counter2 = () => {
    const [clicks, setClicks] = useState(0);
    const handleClick = useCallback(() => {
        setClicks(c => c + 1);
    },[]);

    return <div>
            <div>{clicks}</div>
            <MemoButton onClick={handleClick} />
        </div>
}
</code>```

The above works fine, but with a more complicated component, it doesn't work so well:

```<code>const CounterGroup = () => {
    const numButtons = 3;
    const [message, setMessage] = useState('button X clicked');
    const handleClick = (val, idx) => setMessage(`button ${idx} clicked: ${val}`);
    return <div>
        <div>{message}</div>
        {Array(numButtons).fill(0).map((_, i) =>
            <MemoButton key={i} onClick={(v) => handleClick(v,i)} />)
        }
        </div>
}
</code>```

In the above code, (v) => handleClick(i,v) is always going to be a new function reference.  Is there a good technique to keep this from changing every render?

One possibility is to just ignore changes to 'on...' props, but this just creates new problems:

```<code>const compareValuePropsOnly = (prev, next) => Object.entries(prev).every(
    ([k, v]) => k.substr(0, 2) === "on" || v === next[k]
);
const MemoOnlyValsButton = React.memo(SlowButton, compareValuePropsOnly);
</code>```

Here is a codesandbox version:
https://codesandbox.io/s/memoization-function-reference-changes-9c1fy

答:
It seems like the value that should be memoized is the function/its result, not the component. At least in your example, there is nothing specific to the component that is passed into that expensive function. Even if it did accept values from the prop, you could still memoize that function based on the values specific to it, rather than have it re-evaluated for every other prop change.</p>

```<code>const SlowButton = ({onClick}) => {
  // make some heat
  const value = useMemo(
    () => (function f(n) { return n < 2 ? Math.random() : f(n-1) + f(n-2)})(32)||0,
    []
  );

  return <button onClick={() => onClick(value)}>{value}</button>
}
</code>```

Body:
Assuming I have a slow component, it makes sense to memoize it, e.g.

const SlowButton = ({onClick}) => {
    // make some heat
    const value = (function f(n) { return n < 2 ? Math.random() : f(n-1) + f(n-2)})(32)|0;
    return <button onClick={() => onClick(value)}>{value}</button>
}
const MemoButton = React.memo(SlowButton);

If I use the MemoButton in a component like:

const Counter = () => {
    const [clicks, setClicks ] = useState(0);
    const handleClick = () => {
        setClicks(clicks + 1);
    }
    return

{clicks}

            <MemoButton onClick={handleClick} />

}

Then the MemoButton still re-renders every time because the onClick property is a new function every render.  It is pretty easy to resolve this with:

const Counter2 = () => {
    const [clicks, setClicks] = useState(0);
    const handleClick = useCallback(() => {
        setClicks(c => c + 1);
    },[]);

    return

{clicks}

            <MemoButton onClick={handleClick} />

}

The above works fine, but with a more complicated component, it doesn't work so well:

const CounterGroup = () => {
    const numButtons = 3;
    const [message, setMessage] = useState('button X clicked');
    const handleClick = (val, idx) => setMessage(`button ${idx} clicked: ${val}`);
    return

{message}

        {Array(numButtons).fill(0).map((_, i) =>
            <MemoButton key={i} onClick={(v) => handleClick(v,i)} />)
        }

}

In the above code, (v) => handleClick(i,v) is always going to be a new function reference.  Is there a good technique to keep this from changing every render?

One possibility is to just ignore changes to 'on...' props, but this just creates new problems:

const compareValuePropsOnly = (prev, next) => Object.entries(prev).every(
    ([k, v]) => k.substr(0, 2) === "on" || v === next[k]
);
const MemoOnlyValsButton = React.memo(SlowButton, compareValuePropsOnly);

Here is a codesandbox version:
https://codesandbox.io/s/memoization-function-reference-changes-9c1fy

Body:
It seems like the value that should be memoized is the function/its result, not the component. At least in your example, there is nothing specific to the component that is passed into that expensive function. Even if it did accept values from the prop, you could still memoize that function based on the values specific to it, rather than have it re-evaluated for every other prop change.

const SlowButton = ({onClick}) => {
  // make some heat
  const value = useMemo(
    () => (function f(n) { return n < 2 ? Math.random() : f(n-1) + f(n-2)})(32)||0,
    []
  );

  return <button onClick={() => onClick(value)}>{value}</button>
}


问:
A cumulative sum of consecutive workdays that resets to 1 when consecutive days = 0, per ID
I have 3 columns:

Employee ID(numerical)

Day of work(a date yyyy-mm-dd when employee had a shift)

is_consecutive_work_day (1 if days of work are consecutive, else 0)

I need a 4th: Consecutive_work_days (a cumulative sum of is_consecutive_work_day, which resets to 1 when is_consecutive_work_day = 0). So this will go to a maximum of 5 for any employee id. Some will have 1,2,3 others 1,2...etc.

What am failing to figure out is how to write the 4th column (consecutive_work_days). Not how to write a consecutive sum per employee id, but specifically how to reset to 1 when is_consecutive_work_day = 0 per employee id.

May I ask for your help regarding this 4th column please? Thanks.

答:
Although this seem like a gap-and-islands problem, there is a simpler solution.  Simply calculate the maximum previous value that is 0 and take the date difference.

The only caveat is if there is none.

That would be:

```<code>select t.*,
       datediff(day_of_work,
                coalesce(max(case when is_consecutive_work_day = 0 then day_of_work end) over (partition by employee_id),
                         date_add(min(day_of_work) partition by employee_id), 1)
                        )
               ) as fourth_column
from t;
</code>```

Body:
Although this seem like a gap-and-islands problem, there is a simpler solution.  Simply calculate the maximum previous value that is 0 and take the date difference.

The only caveat is if there is none.

That would be:

select t.*,
       datediff(day_of_work,
                coalesce(max(case when is_consecutive_work_day = 0 then day_of_work end) over (partition by employee_id),
                         date_add(min(day_of_work) partition by employee_id), 1)
                        )
               ) as fourth_column
from t;


问:
How to choose the rows where the first occurrence of a value happens with groupby in pandas and also the first of the consequent occurrences
I have a dataframe that looks like this:

```<code>import pandas as pd

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})
</code>```

This df is already order with respect to id & time.

I would like to keep only the rows where taken has value 1 by id, and if there are two (or more) consequent 1s in the column taken to keep only the first of these.

My output df should like this:

```<code>  id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1
</code>```

Second example

To make the question a bit more clear, if the dataframe looks like this:

```<code>df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})
</code>```

Then the output dataframe should look like this:

```<code>   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1
</code>```

Any ideas on how to do this ?

答:
Create a boolean mask by grouping by id, and then taking the values where taken is True but its shifted value is not True.

```<code>df1 = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})
df2 = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})

df = df1  # First example.
>>> df[df.groupby('id')['taken'].shift().ne(True) & df['taken']]
   id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1

df = df2  # Second example.
>>> df[df.groupby('id')['taken'].shift().ne(True) & df['taken']]
   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1
</code>```

Body:
I have a dataframe that looks like this:

import pandas as pd

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})

This df is already order with respect to id & time.

I would like to keep only the rows where taken has value 1 by id, and if there are two (or more) consequent 1s in the column taken to keep only the first of these.

My output df should like this:

  id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1

Second example

To make the question a bit more clear, if the dataframe looks like this:

df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})

Then the output dataframe should look like this:

   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1

Any ideas on how to do this ?

Body:
Create a boolean mask by grouping by id, and then taking the values where taken is True but its shifted value is not True.

df1 = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,0,1,0,1,0,1]})
df2 = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2], 'time': [1,2,3,4,5,4,7,8,9], 'taken': [0,1,1,1,1,1,1,0,1]})

df = df1  # First example.
>>> df[df.groupby('id')['taken'].shift().ne(True) & df['taken']]
   id  time  taken
1   1     2      1
4   1     5      1
6   2     7      1
8   2     9      1

df = df2  # Second example.
>>> df[df.groupby('id')['taken'].shift().ne(True) & df['taken']]
   id  time  taken
1   1     2      1
5   2     4      1
8   2     9      1


问:
JQuery POST to wordpress PHP plugin execution
I have a script on my Wordpress page, implemented via a code block from the visual page builder.  What I want to know is, how do I pass the correct URL to reach my PHP file?  Since it's in the block of the page builder, I don't think I can use ajax_admin as the url since the file is never enqueued.

```<code>
$("#submit_button").click(function(e,features,totalcost){
  e.preventDefault();
   console.log('clicked')
     $.ajax({
     type: "POST",
     url: '/wp-content/plugins/estimate/estimate.php',
      data: {
      action: 'submitWizard',
// add your parameters here
      features: features,
      total:totalcost,
      email:$("#exampleInputEmail1").value,
      name:$("#exampleInputPassword1").value,
      message:$("#exampleFormControlTextarea1").value,
      },
      success: function(response){
      console.log(response);
      }
      });
})
</code>```

And I have a plugin called estimate with this code:

```<code>
 add_action( 'wp_ajax_submitWizard', 'process_estimate' );

function process_estimate(){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $features = $_POST['features'];
    $total = $_POST['total'];

    wp_mail( 'charlespettisappdevelopment@gmail.com', 'New Submission!', "
        $name,
        $email,
        $message,
        $features,
        $total,
  ");
}

</code>```

答:
On your estimate.php add this code:

```<code>add_action( 'wp_enqueue_scripts', 'wi_enqueue_scripts' );
function wi_enqueue_scripts(){
    wp_localize_script( 'wi-ajax-script', 'wi_ajax_params',
        array(
            'wi_ajax_nonce' => wp_create_nonce( 'wi_ajax_nonce' ),
            'wi_ajax_url' => admin_url( 'admin-ajax.php' )
        )
    );
}
</code>```

Then in javascript file use this:

```<code>$("#submit_button").click(function(e, features, totalcost) {
    e.preventDefault();
    console.log('clicked')
    $.ajax({
        type: "POST",
        //url: wi_ajax_params.wi_ajax_url,
        url: "http://yourdomain.com/wp-admin/admin-ajax.php",
        data: {
            action: 'submitWizard',
            // add your parameters here
            features: features,
            total: totalcost,
            email: $("#exampleInputEmail1").value,
            name: $("#exampleInputPassword1").value,
            message: $("#exampleFormControlTextarea1").value,
        },
        success: function(response) {
            console.log(response);
        }
    });
});
</code>```

Last, add this code again to plugin file:

```<code>add_action( 'wp_ajax_submitWizard', 'process_estimate' );
add_action( 'wp_ajax_nopriv_submitWizard', 'process_estimate' );
function process_estimate(){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $features = $_POST['features'];
    $total = $_POST['total'];

    wp_mail( 'charlespettisappdevelopment@gmail.com', 'New Submission!', "
        $name,
        $email,
        $message,
        $features,
        $total,
  ");
}
</code>```

Not tested but it should work. Let me know.

Body:
I have a script on my Wordpress page, implemented via a code block from the visual page builder.  What I want to know is, how do I pass the correct URL to reach my PHP file?  Since it's in the block of the page builder, I don't think I can use ajax_admin as the url since the file is never enqueued.

$("#submit_button").click(function(e,features,totalcost){
  e.preventDefault();
   console.log('clicked')
     $.ajax({
     type: "POST",
     url: '/wp-content/plugins/estimate/estimate.php',
      data: {
      action: 'submitWizard',
// add your parameters here
      features: features,
      total:totalcost,
      email:$("#exampleInputEmail1").value,
      name:$("#exampleInputPassword1").value,
      message:$("#exampleFormControlTextarea1").value,
      },
      success: function(response){
      console.log(response);
      }
      });
})

And I have a plugin called estimate with this code:

 add_action( 'wp_ajax_submitWizard', 'process_estimate' );

function process_estimate(){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $features = $_POST['features'];
    $total = $_POST['total'];

    wp_mail( 'charlespettisappdevelopment@gmail.com', 'New Submission!', "
        $name,
        $email,
        $message,
        $features,
        $total,
  ");
}

Body:
On your estimate.php add this code:

add_action( 'wp_enqueue_scripts', 'wi_enqueue_scripts' );
function wi_enqueue_scripts(){
    wp_localize_script( 'wi-ajax-script', 'wi_ajax_params',
        array(
            'wi_ajax_nonce' => wp_create_nonce( 'wi_ajax_nonce' ),
            'wi_ajax_url' => admin_url( 'admin-ajax.php' )
        )
    );
}

Then in javascript file use this:

$("#submit_button").click(function(e, features, totalcost) {
    e.preventDefault();
    console.log('clicked')
    $.ajax({
        type: "POST",
        //url: wi_ajax_params.wi_ajax_url,
        url: "http://yourdomain.com/wp-admin/admin-ajax.php",
        data: {
            action: 'submitWizard',
            // add your parameters here
            features: features,
            total: totalcost,
            email: $("#exampleInputEmail1").value,
            name: $("#exampleInputPassword1").value,
            message: $("#exampleFormControlTextarea1").value,
        },
        success: function(response) {
            console.log(response);
        }
    });
});

Last, add this code again to plugin file:

add_action( 'wp_ajax_submitWizard', 'process_estimate' );
add_action( 'wp_ajax_nopriv_submitWizard', 'process_estimate' );
function process_estimate(){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $features = $_POST['features'];
    $total = $_POST['total'];

    wp_mail( 'charlespettisappdevelopment@gmail.com', 'New Submission!', "
        $name,
        $email,
        $message,
        $features,
        $total,
  ");
}

Not tested but it should work. Let me know.


问:
Optional AttributeGroup
I have to define a attribute group for 2 mutually inclusive data elements. In the below example if TO_DT is present FROM_DT has to be present and TO_DT is not present then FROM_DT is not present.

I thought of creating these as mandatory attributes and define attributegroup as optional but its not working:

```<code><xs:attributeGroup name="DateRangeAttributes" id="Element_Common_545">
  <xs:attribute name="TO_DT" type="xs:date" use="required" id="Element_Common_547"/>
  <xs:attribute name="FROM_DT" type="xs:date" use="required" id="Element_Common_546"/>
<xs:attributeGroup>
</code>```

Can anyone suggest a way to handle this using attributes

答:
Sorry, that kind of constraint can't be enforced by XML Schema (1.0). You'll have a enforce it elsewhere (such as with code or XSLT) or change the format. Possibilities:

Provide default values so both are effectively always present.

Use a single attribute containing a length-2 list of dates.

Use elements (you could also control the order, unlike attributes).

ContentLicense: CC BY-SA 3.0

Title: Optional AttributeGroup

Body:
I have to define a attribute group for 2 mutually inclusive data elements. In the below example if TO_DT is present FROM_DT has to be present and TO_DT is not present then FROM_DT is not present.

I thought of creating these as mandatory attributes and define attributegroup as optional but its not working:

<xs:attributeGroup name="DateRangeAttributes" id="Element_Common_545">
  <xs:attribute name="TO_DT" type="xs:date" use="required" id="Element_Common_547"/>
  <xs:attribute name="FROM_DT" type="xs:date" use="required" id="Element_Common_546"/>
<xs:attributeGroup>

Can anyone suggest a way to handle this using attributes


问:
Excel Visual Studio Design Time Adapter Add-in Error
I am trying to open excel workbook 2003 using VSTO.
but i am getting error again again like

" Project cannot be created because the application add-in is not working correctly and might have been disabled.  To check for disabled items in the Microsoft Office application, open the Help menu, click About Microsoft Office Word or About Microsoft Office Excel, and then click Disabled Items.  If either "Word Visual Studio Design Time Adapter Add-in" or "Excel Visual Studio Design Time Adapter Add-in" appears, select it and click Enable.  If not, reinstall or repair your installation of Visual Studio Tools for Office."

Can somebody help ??

答:
I am from the future, year of 2020, but I had the same issue despite using Office 365, Windows 10, and Visual Studio 2019. Visual Studio Design-Time Adapter Add-in (in my case it was Excel, but that's hardly relevant) kept disabling itself after each restart of Excel.

Reinstalling VSTO components didn't help, and I did not want to mess with the whole Office/VS re-installation.

The problem was solved by changing the value of HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\Addins\VS15ExcelAdaptor key in the registry from 0 to 3.

ContentLicense: CC BY-SA 2.5


问:
Update subarray of objects in mongodb
I have this document in my database:

```<code>{
    "_id": "ObjectId(...)",
    "chapters": [
        {
            "_id": "ObjectId(...)",
            "link": "128371.html",
            "content": ""
        }
    ]
}
</code>```

The chapters array can have up to 3k items, and I have to populate each content attribute with some info. I want to be able to save the info I want inside the right object. Until now I was able to change the content attribute generally (in all items), but I am having trouble filtering it. This is what I managed to code using what I found in other questions:

```<code>let content = "Testing";
await models.ListNovel.updateOne(
  { link: novel_link },
  { $set: { "chapters.$[].content": content } }
);
</code>```

I saw that { arrayFilters: [{ link: { $eq: chapter_link } }], multi: false } may work in some cases, but I don't use the link identifier in the update.

Thank you!

UPDATE

Similar to Suleyman's solution, I ended up with the following working code, I hope it may be useful for you.

```<code>await models.ListNovel.updateOne(
  { link: novel.link },
  { $set: { "chapters.$[elem].content": content } },
  {
    multi: true,
    arrayFilters: [{ "elem.link": { $eq: chapter.link } }]
  }
);
</code>```

答:
The condition in updateOne must match parent object, but you are using { link: novel_link } which belongs to the inner array object field, so it cannot find the document, and update doesn't happen.

To illustrate this, let's say your schema is like this:

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  name: String,
  chapters: [
    new mongoose.Schema({
      link: String,
      content: String
    })
  ]
});

module.exports = mongoose.model("ListNovel", schema);
```

<p>Let's have this existing document in this collection:</p>

```{
    "_id": "5e498a1fe21eea0e10690e39",
    "name": "Novel1",
    "chapters": [
        {
            "_id": "5e498a1fe21eea0e10690e3b",
            "link": "128371.html",
            "content": ""
        },
        {
            "_id": "5e498a1fe21eea0e10690e3a",
            "link": "222222.html",
            "content": ""
        }
    ],
    "__v": 0
}
```

<p>If we want to update this document's chapter with <code>"link": "128371.html"</code>, first we need to find it with name or _id field, and update it using the filtered positional operator $.</p>

<pre class="lang-js prettyprint-override"><code>router.put("/novels/:name", async (req, res) => {
  const novel_link = "128371.html";
  const content = "Testing";

  const result = await ListNovel.findOneAndUpdate(
    { name: req.params.name },
    {
      $set: { "chapters.$[chapter].content": content }
    },
    {
      arrayFilters: [{ "chapter.link": novel_link }],
      new: true
    }
  );
  res.send(result);
});
</code>```

Here I used findOneAndUpdate to immediately retrieve the updated document, but you can also use the updateOne instead of findOneAndUpdate.

The result will be like this:

```<code>{
    "_id": "5e498a1fe21eea0e10690e39",
    "name": "Novel1",
    "chapters": [
        {
            "_id": "5e498a1fe21eea0e10690e3b",
            "link": "128371.html",
            "content": "Testing"  // => UPDATED
        },
        {
            "_id": "5e498a1fe21eea0e10690e3a",
            "link": "222222.html",
            "content": ""
        }
    ],
    "__v": 0
}
</code>```

Title: Update subarray of objects in mongodb

Body:
I have this document in my database:

{
    "_id": "ObjectId(...)",
    "chapters": [
        {
            "_id": "ObjectId(...)",
            "link": "128371.html",
            "content": ""
        }
    ]
}

The chapters array can have up to 3k items, and I have to populate each content attribute with some info. I want to be able to save the info I want inside the right object. Until now I was able to change the content attribute generally (in all items), but I am having trouble filtering it. This is what I managed to code using what I found in other questions:

let content = "Testing";
await models.ListNovel.updateOne(
  { link: novel_link },
  { $set: { "chapters.$[].content": content } }
);

I saw that { arrayFilters: [{ link: { $eq: chapter_link } }], multi: false } may work in some cases, but I don't use the link identifier in the update.

Thank you!

UPDATE

Similar to Suleyman's solution, I ended up with the following working code, I hope it may be useful for you.

await models.ListNovel.updateOne(
  { link: novel.link },
  { $set: { "chapters.$[elem].content": content } },
  {
    multi: true,
    arrayFilters: [{ "elem.link": { $eq: chapter.link } }]
  }
);

Body:
The condition in updateOne must match parent object, but you are using { link: novel_link } which belongs to the inner array object field, so it cannot find the document, and update doesn't happen.

To illustrate this, let's say your schema is like this:

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  name: String,
  chapters: [
    new mongoose.Schema({
      link: String,
      content: String
    })
  ]
});

module.exports = mongoose.model("ListNovel", schema);

Let's have this existing document in this collection:

{
    "_id": "5e498a1fe21eea0e10690e39",
    "name": "Novel1",
    "chapters": [
        {
            "_id": "5e498a1fe21eea0e10690e3b",
            "link": "128371.html",
            "content": ""
        },
        {
            "_id": "5e498a1fe21eea0e10690e3a",
            "link": "222222.html",
            "content": ""
        }
    ],
    "__v": 0
}

If we want to update this document's chapter with "link": "128371.html", first we need to find it with name or _id field, and update it using the filtered positional operator $.

router.put("/novels/:name", async (req, res) => {
  const novel_link = "128371.html";
  const content = "Testing";

  const result = await ListNovel.findOneAndUpdate(
    { name: req.params.name },
    {
      $set: { "chapters.$[chapter].content": content }
    },
    {
      arrayFilters: [{ "chapter.link": novel_link }],
      new: true
    }
  );
  res.send(result);
});

Here I used findOneAndUpdate to immediately retrieve the updated document, but you can also use the updateOne instead of findOneAndUpdate.

The result will be like this:

{
    "_id": "5e498a1fe21eea0e10690e39",
    "name": "Novel1",
    "chapters": [
        {
            "_id": "5e498a1fe21eea0e10690e3b",
            "link": "128371.html",
            "content": "Testing"  // => UPDATED
        },
        {
            "_id": "5e498a1fe21eea0e10690e3a",
            "link": "222222.html",
            "content": ""
        }
    ],
    "__v": 0
}


问:
Rendering video in game engine with dynamic FPS
I'm trying to render a pre-exported video in my game engine and have stumbled upon problems when trying to schedule frames. Namely, while the video is exported at fixed FPS, the engine has a dynamic frame rate (which may be higher or lower than the video's). When trying to choose which video frame to render in the current engine frame, my algorithms keep running into edge cases which ruins either the speed of the video or the distribution of the video frames.

I'm aware at this point that there is probably no algorithm which will run perfectly in all situations, but there are three situations which are likely to happen during the runtime and should be covered by the algorithm:

Arbitrary stable frame rate in the engine, with a ~5% margin of error. (For example, if average frame time is 33.333ms, all of the frame durations would fall within the 31.6666ms - 35ms range.)

Arbitrary semi-stable frame rate, with <5% of the frames having a duration outside the margin of error.

Stable frame rate which can change to a different stable frame rate during the video playback.

During these 3 situations, the following should hold true:

When observing over arbitrary period of time, speed at which the video renders is the same as the speed at which video would render at its original FPS.

When observing over arbitrary period of time, during which engine had a stable frame rate, frame distribution should be balanced.

Having all this in mind, I've tried 2 solutions which didn't yield good results even with a couple of heuristics.

A really naive solution in which delta time of the current frame is multiplied by the frame rate, the result is rounded and video playback is advanced by that many frames. While this solution works perfectly at some frame rates, the speed difference is too high at others. For example, if the video is at 60FPS and engine renders at 30FPS, every engine frame will advance the video playback by 2 frames, which is perfect. However, even at ~39 FPS, due to the rounding effect, the playback will still only be advanced by 2 frames in each engine frame, resulting in the decreased speed of the video.

A timeline-based solution where we keep track of the accumulated duration of all previous engine frames. Summing that and the duration of the current engine frame, then rounding it to the nearest multiple of the video frame duration, we get the approximate video frame which should be rendered in the engine. This solution balances the video speed perfectly, but there's many edge cases where the frame distribution becomes very unbalanced, leading to stuttering in the video. Using the same example as earlier, with video at 60FPS and engine at 30FPS, there's an edge case where one frame with duration of ~41.66666ms will lead to the situation where the video frames are advanced as (1, 3, 1, 3, 1, 3....) instead of (2, 2, 2, 2, 2, 2...).

I guess my questions are: Is there a problem with known algorithms and heuristics which could be reduced to this one? If not, is there a nice heuristic which would yield better results in the 3 situations I've described above?

答:
I think your timeline-based algorithm is pretty close.  I think you just need to define your desires mathematically.

For each frame selection, we could consider two kinds of error.  Let w be the difference between the wall clock time when the selected frame will show, and the time when it should show according to the video frame rate.  Let d be the error in the difference between the show times of the selected frame and the previously shown frame.

Define the relative weights A and B of these errors, and then select the frame that minimizes Aw2 + Bd2


问:
Snowflake Python Connector error in Databricks
I have a simple python script that uses the snowflake python connector to connect and call a Snowflake stored procedure. The script has been running fine through datababricks but I am getting the following error now when creating a connection object (ctx). It runs fine from my laptop using Jupyter notebook but not through databricks anymore. Using Python 3.

ssl_wrap_socket_with_ocsp() got an unexpected keyword argument 'cert_reqs'

Here's my code:

```<code>import snowflake.connector as sc

Username = dbutils.secrets.get(scope = "SnowFlake", key = "username")
Password = dbutils.secrets.get(scope = "SnowFlake", key = "password")

ctx = sc.connect(
account='myaccount',
user=Username,
password=Password,
warehouse='myWH',
database='myDB',
schema='Public'
)
</code>```

答:
This was a bug introduced with the Snowflake Python Connector version 2.0.3, which has since been resolved in the most recent version.

The script has been running fine through datababricks but I am getting the following error now when creating a connection object (ctx).
  It runs fine from my laptop using Jupyter notebook but not through databricks anymore

The change in behaviour is likely because of the installation scripts in use inside your deployment is not pinning versions. If a fresh install of snowflake-python-connector via pip is done without explicitly specifying a version, it will always pull the most recently published one. This may not be a desirable behaviour for use in production workloads, as it pulls in new changes (and breakages, deprecations, or removals) without a developer testing against them first.

Body:
I have a simple python script that uses the snowflake python connector to connect and call a Snowflake stored procedure. The script has been running fine through datababricks but I am getting the following error now when creating a connection object (ctx). It runs fine from my laptop using Jupyter notebook but not through databricks anymore. Using Python 3.

ssl_wrap_socket_with_ocsp() got an unexpected keyword argument 'cert_reqs'

Here's my code:

import snowflake.connector as sc

Username = dbutils.secrets.get(scope = "SnowFlake", key = "username")
Password = dbutils.secrets.get(scope = "SnowFlake", key = "password")

ctx = sc.connect(
account='myaccount',
user=Username,
password=Password,
warehouse='myWH',
database='myDB',
schema='Public'
)


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body:
Using map:

k = [['1','7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1']]

map(','.join, k) # returns ['1,7,U1', '1.5,8,U1', '2,5.5,U1']


问:
Spring MVC Role and Permission to Admin
I am new in spring mvc , In my existing project , there is one admin and they have rights to update data , but now i need to create 2 new admin , admin1 and admin2
that can only see limited page when they login like:

when admin login , they can see Add data, update data, Post message pages in menu bar.
but in case Admin1 , can see only Post meassage page in menu bar.

so, please guide me how can i achieve this task in spring mvc
Thanks in Advance.

答:
I had a similar use-case, where the admins might want to create new roles, with arbitrarily assigned permissions to these roles.

If I were to authorize users on the existence of a ROLE_* in their granted authorities, then the code would need to change every time someone adds a new role, or the business requirements for that role changes.

Like @Ralph, I created a library to inject mapped authorities based on Role to Permissions because I found the hierarchical role implementation lacking...

When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.
You can provide map the permissions in your UserDetailsService, or JWT Authentication Converter for instance.

The PermissionProvider is called to get the effective permissions for each role the user is a member of. The distinct list of permissions are added as GrantedAuthority items in the Authentication object.

Then I can use permission level authorization in the configuration, and the role to permission mapping can change at runtime.

Concept -

```<code>ADMIN1 -> PERM_ADD, PERM_POST
ADMIN2 -> PERM_POST, PERM_UPDATE
</code>```

Implementation example -

```<code>@Autowired
RolePermissionsRepository repository;

public void setup1(){
  String roleName = "ROLE_ADMIN1";
  List<String> permissions = new ArrayList<String>();
  permissions.add("PERM_ADD");
  permissions.add("PERM_POST");
  repository.save(new RolePermissions(roleName, permissions));
}

public void setup2(){
  String roleName = "ROLE_ADMIN2";
  List<String> permissions = new ArrayList<String>();
  permissions.add("PERM_UPDATE");
  permissions.add("PERM_POST");
  repository.save(new RolePermissions(roleName, permissions));
}
</code>```

Then use the permissions for access instead of roles.

```<code><http auto-config="true">
     <intercept-url pattern="/addData" access="PERM_ADD" />
     <intercept-url pattern="/updateData" access="PERM_UPDATE" />
     <intercept-url pattern="/postMessage" access="PERM_POST" />
</http>
</code>```

Or using the authorization annotations -

```<code>@PreAuthorize("hasAuthority('PERM_ADD')")
@RequestMapping("/add")
public String add() {
  ...
}
</code>```

For the source code, see here -
https://github.com/savantly-net/spring-role-permissions

Title: Spring MVC Role and Permission to Admin

Body:
I had a similar use-case, where the admins might want to create new roles, with arbitrarily assigned permissions to these roles.

If I were to authorize users on the existence of a ROLE_* in their granted authorities, then the code would need to change every time someone adds a new role, or the business requirements for that role changes.

Like @Ralph, I created a library to inject mapped authorities based on Role to Permissions because I found the hierarchical role implementation lacking...

When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.
You can provide map the permissions in your UserDetailsService, or JWT Authentication Converter for instance.

The PermissionProvider is called to get the effective permissions for each role the user is a member of. The distinct list of permissions are added as GrantedAuthority items in the Authentication object.

Then I can use permission level authorization in the configuration, and the role to permission mapping can change at runtime.

Concept -

ADMIN1 -> PERM_ADD, PERM_POST
ADMIN2 -> PERM_POST, PERM_UPDATE

Implementation example -

@Autowired
RolePermissionsRepository repository;

public void setup1(){
  String roleName = "ROLE_ADMIN1";
  List<String> permissions = new ArrayList<String>();
  permissions.add("PERM_ADD");
  permissions.add("PERM_POST");
  repository.save(new RolePermissions(roleName, permissions));
}

public void setup2(){
  String roleName = "ROLE_ADMIN2";
  List<String> permissions = new ArrayList<String>();
  permissions.add("PERM_UPDATE");
  permissions.add("PERM_POST");
  repository.save(new RolePermissions(roleName, permissions));
}

Then use the permissions for access instead of roles.

<http auto-config="true">
     <intercept-url pattern="/addData" access="PERM_ADD" />
     <intercept-url pattern="/updateData" access="PERM_UPDATE" />
     <intercept-url pattern="/postMessage" access="PERM_POST" />
</http>

Or using the authorization annotations -

@PreAuthorize("hasAuthority('PERM_ADD')")
@RequestMapping("/add")
public String add() {
  ...
}

For the source code, see here -
https://github.com/savantly-net/spring-role-permissions


问:
Append with input value with <li> tag
Thanks in advance.
I am trying to append a list using the input value. I can append a list using predefined string, and I can append using input value to non list item. But I'm having trouble combining these, it seems to add extra list items.
This is the code I'm using:</p>

```<code>    <ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<form>
    <div><textarea class="example-default-value" id="example-textarea" style="width: 400px; height: 50px;">Type some text in here to be appended</textarea></div>
    <div><input type="button" value="Append" onclick="example_append()" /></div>
</form>
<script language="javascript">
$('.example-default-value').each(function() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = default_value;
        }
    });
});
function example_append() {
    $('ol').append("<li>"+($('#example-textarea').val())+"<li>");
}
</script>
</code>```

答:
If you dont use jquery anywhere else you can use javascript for this function as following:

function example_append() {
let textInput = document.getElementById("example-textarea");
if(textInput.value !==""){
    let node = document.createElement("LI");
    node.innerHTML = textInput.value;
    textInput.value="";
    document.getElementById("myList").appendChild(node);
  }else {
    alert("Enter something in textarea")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol id="myList">
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<form>
   <div>
    <textarea class="example-default-value" placeholder="Type here"
    id="example-textarea" style="width: 400px; height: 50px;"></textarea>
    </div>
    <div>
    <input type="button" value="Append"
    onclick="example_append()" />
   </div>
</form></code>```

Title: Append with input value with <li> tag

Body:
Thanks in advance.
I am trying to append a list using the input value. I can append a list using predefined string, and I can append using input value to non list item. But I'm having trouble combining these, it seems to add extra list items.
This is the code I'm using:

List item 1

List item 2

List item 3

<form>

<textarea class="example-default-value" id="example-textarea" style="width: 400px; height: 50px;">Type some text in here to be appended</textarea>

<input type="button" value="Append" onclick="example_append()" />

</form>

Body:
If you dont use jquery anywhere else you can use javascript for this function as following:

function example_append() {
let textInput = document.getElementById("example-textarea");
if(textInput.value !==""){
    let node = document.createElement("LI");
    node.innerHTML = textInput.value;
    textInput.value="";
    document.getElementById("myList").appendChild(node);
  }else {
    alert("Enter something in textarea")
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol id="myList">
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<form>
   <div>
    <textarea class="example-default-value" placeholder="Type here"
    id="example-textarea" style="width: 400px; height: 50px;"></textarea>
    </div>
    <div>
    <input type="button" value="Append"
    onclick="example_append()" />
   </div>
</form>


问:
Is using a ref in a custom hook feasible or advised for mutating the DOM?
I am working on incorporating a 3rd-party library into a React app, and hooks are making this very easy overall.
However I have encountered a few issues, and I was hoping for some clarity on what is going on 'under the hood'.

For simplicity, let's say this is my 3rd-party code that mutates the DOM directly:

```<code>const renderStuff = (div, txt) => {
  if(div) div.innerHTML = txt;
}
</code>```

And my component is something like this:

```<code>export const EffectRender = () => {
  const divRef = useRef();
  useRenderer(divRef, "Hello, world");
  return <div ref={divRef}></div>;
}
</code>```

Here is the proposed custom hook:

```<code>const useRenderer = (ref, txt) => {
  const div = ref.current;
  useEffect(() => {
    renderStuff(div, txt);
  },[div, txt])
};
</code>```

This works if one of the params (in this case, txt) is late-updated, say as a result of an async load.
But the useEffect never recognizes when the ref.current value changes.
So if the txt is set before ref.current is set (as in this case) the component never renders.

I understand that I can fix that by using setState in the custom hook, as in this example.
But this starts to feel cumbersome.

I also understand that I could put the renderStuff call in a useEffect hook on the main component, and that guarantees the ref.current is set.
So: useEffect(() => { renderStuff(divRef.current, txt); },[txt]); is fine.

My question really is whether this whole approach of using a ref inside a custom hook is a good idea.
Is there a simpler way of getting the hook to recognize when the ref has changed?
Or is this a case where custom hooks are not suited to the task?

答:
Thank you Alvaro for clarifying the issue. I want to explain where my thinking went wrong here, assuming I'm not the only one to make this mistake.

My bad logic

We use effect hooks because the code is mutating the DOM, and useEffect exists to handle exactly this sort of side-effect.

We use ref hooks to connect to a given DOM element. The ref instance is like a singleton, in that the instance doesn't change during the life of the app. Only the ref.current property changes.

And directly under the relevant section in the hooks reference docs I read this:

Keep in mind that useRef doesn’t notify you when its content changes.
  Mutating the .current property doesn’t cause a re-render.

From that, I understood that relevant dependencies need to be passed to the useEffect call. And that the element to be updated (in ref.current) was one of these dependencies. And since changing the ref.current property doesn't trigger a re-render, it presumably wasn't triggering the useEffect call either.

BTW: this thinking was reinforced by es-lint demanding I add ref.current (in my case, div = ref.current) into the dependencies list: React Hook useEffect has a missing dependency: 'div'. Either include it or remove the dependency array. I always trust the linter, of course.

My conclusion: there was no simple way to use an effect hook to render to a ref instance. I needed to put the ref.current into a useState setter somehow. Ugly!

My core assumption

I assumed that the way the useEffect handles side-effects is not relevant. The effect hook is a black-box buried in the bowels of the typescript source code, and it moves in mysterious ways.

But the only thing 'buried' was this sentence in the use-effect docs:

The function passed to useEffect will run after the render is
  committed to the screen.

"After the render". Of course. That is how useEffect handles side-effects, by guaranteeing not to run until the DOM is ready to go.

The solution

As Alvaro's answer suggests, make sure to read the ref.current property inside the useEffect hook. The ref never changes, and ref.current is guaranteed to be already populated with a DOM element.

As usual, it is obvious in hindsight. Thanks again, Alvaro.

Body:
I am working on incorporating a 3rd-party library into a React app, and hooks are making this very easy overall.
However I have encountered a few issues, and I was hoping for some clarity on what is going on 'under the hood'.

For simplicity, let's say this is my 3rd-party code that mutates the DOM directly:

const renderStuff = (div, txt) => {
  if(div) div.innerHTML = txt;
}

And my component is something like this:

export const EffectRender = () => {
  const divRef = useRef();
  useRenderer(divRef, "Hello, world");
  return

;
}

Here is the proposed custom hook:

const useRenderer = (ref, txt) => {
  const div = ref.current;
  useEffect(() => {
    renderStuff(div, txt);
  },[div, txt])
};

This works if one of the params (in this case, txt) is late-updated, say as a result of an async load.
But the useEffect never recognizes when the ref.current value changes.
So if the txt is set before ref.current is set (as in this case) the component never renders.

I understand that I can fix that by using setState in the custom hook, as in this example.
But this starts to feel cumbersome.

I also understand that I could put the renderStuff call in a useEffect hook on the main component, and that guarantees the ref.current is set.
So: useEffect(() => { renderStuff(divRef.current, txt); },[txt]); is fine.

My question really is whether this whole approach of using a ref inside a custom hook is a good idea.
Is there a simpler way of getting the hook to recognize when the ref has changed?
Or is this a case where custom hooks are not suited to the task?


问:
Rails Database Query .order GREATEST ignore if NULL or empty
I am trying to filter by a specific user's last activity in a discussion, so if a user made a post or a comment this discussion gets to be the first in their personal list.

Relations:

a Discussion has_many posts.

a Post has_many comments.

a User has_many posts.

a User has_many comments.

a discussion has_many comments through posts.

My query pretty much works but only when both a post and comment from a user exist in a discussion.

How could I adjust my query to look either for the last_created post or last_created comment, meaning in my .order how can I ignore the MAX(comments.created_at) if this is empty and just
use MAX(posts.created_at)

```<code>@discussions = Discussion.
  joins(:posts,:comments).
  where(posts: {user: current_user}).
  where(comments: {user: current_user}).
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

</code>```

答:
I think that two things are problematic in your query:

the joins statement

the where statements that use a reference to a table (users) that has not been join

Try doing changing the joins to a left_joins like so, and update your where condition as well so that it does not rely on joining the users table - which could cause other issues.

```<code>@discussions = Discussion.
  left_joins(:posts,:comments).
  where('? IN (posts.user_id, comments.user_id)', current_user.id)
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')
</code>```

Indeed with a regular INNER JOIN (which is what the joins method do under the hood), you would only retrieve discussions for which there are both a comment and a post by your user, which is not what you want to do.

Body:
I am trying to filter by a specific user's last activity in a discussion, so if a user made a post or a comment this discussion gets to be the first in their personal list.

Relations:

a Discussion has_many posts.

a Post has_many comments.

a User has_many posts.

a User has_many comments.

a discussion has_many comments through posts.

My query pretty much works but only when both a post and comment from a user exist in a discussion.

How could I adjust my query to look either for the last_created post or last_created comment, meaning in my .order how can I ignore the MAX(comments.created_at) if this is empty and just
use MAX(posts.created_at)

@discussions = Discussion.
  joins(:posts,:comments).
  where(posts: {user: current_user}).
  where(comments: {user: current_user}).
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

Body:
I think that two things are problematic in your query:

the joins statement

the where statements that use a reference to a table (users) that has not been join

Try doing changing the joins to a left_joins like so, and update your where condition as well so that it does not rely on joining the users table - which could cause other issues.

@discussions = Discussion.
  left_joins(:posts,:comments).
  where('? IN (posts.user_id, comments.user_id)', current_user.id)
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

Indeed with a regular INNER JOIN (which is what the joins method do under the hood), you would only retrieve discussions for which there are both a comment and a post by your user, which is not what you want to do.


问:
Collapsing a 10 period curve to 4 periods
I have a 10 period cost curve table below.  How do I programmatically collapse/condense/shrink this to 4 periods.  I'm using VBA but I should be able to follow other languages.  The routine should work for whatever period you pass to it.  For example, if I pass it a 7 it should condense the percentages to 7 periods.  If I pass it 24 then expand the percentages to 24 periods, spreading the percentages based on the original curve.  Any help or example will be appreciated.  Thanks...

```
ORIGINAL
Period  Pct
1       10.60%
2       19.00%
3       18.30%
4       14.50%
5       10.70%
6        8.90%
7        6.50%
8        3.10%
9        3.00%
10       5.40%
```

```
COLLAPSED
Period  Pct
1       38.75%
2       34.35%
3       16.95%
4        9.95%
```

EDITED:  I've added sample code below as to what I have so far.  It only works for periods 1, 2, 3, 5, 9, 10.  Maybe someone can help modify it to work for any period.  Disclaimer, I'm not a programmer so my coding is bad.  Plus, I have no clue as to what I'm doing.

```
Sub Collapse_Periods()
    Dim aPct As Variant
    Dim aPer As Variant
    aPct = Array(0.106, 0.19, 0.183, 0.145, 0.107, 0.089, 0.065, 0.031, 0.03, 0.054)
    aPer = Array(1, 2, 3, 5, 9, 10)
    For i = 0 To UBound(aPer)
        pm = 10 / aPer(i)
        pct1 = 1
        p = 0
        ttl = 0
        For j = 1 To aPer(i)
            pct = 0
            k = 1
            Do While k <= pm
                pct = pct + aPct(p) * pct1
                pct1 = 1
                p = p + 1
                If k <> pm And k = Int(pm) Then
                    pct1 = (pm - Int(pm)) * j
                    pct = pct + (pct1 * aPct(p))
                    pct1 = 1 - pct1
                End If
                k = k + 1
            Loop
            Debug.Print aPer(i) & " : " & j & " : " & pct
            ttl = ttl + pct
        Next j
        Debug.Print "Total:  " & ttl
    Next i
End Sub
```

答:
I would like to know how this is done also using an Integral? This is how I would have done it - perhaps it's a longhand/longwinded method but I'd like to see some better suggestions.

It's probably easier to see the method in Excel first using the LINEST function and Named ranges. I've assumed the function is logarithmic. I've outlined steps [1.] - [5.]

This VBA code then essentially replicates the Excel method using a function to pass 2 arrays, periods and a return array that can be written to a range

```<code>Sub CallingProc()
Dim Periods As Long, returnArray() As Variant
Dim X_Values() As Variant, Y_Values() As Variant

Periods = 4
ReDim returnArray(1 To Periods, 1 To 2)

With Sheet1
    X_Values = Application.Transpose(.Range("A2:A11"))
    Y_Values = Application.Transpose(.Range("B2:B11"))
End With

FGraph X_Values, Y_Values, Periods, returnArray 'pass 1D array of X, 1D array of Y,    Periods, Empty ReturnArray
End Sub

Function FGraph(ByVal x As Variant, ByVal y As Variant, ByVal P As Long, ByRef returnArray As Variant)
Dim i As Long, mConstant As Double, cConstant As Double

'calc cumulative Y and take Ln (Assumes Form of Graph is logarithmic!!)
For i = LBound(y) To UBound(y)
    If i = LBound(y) Then
        y(i) = y(i)
    Else
        y(i) = y(i) + y(i - 1)
    End If

    x(i) = Log(x(i))
Next i

'calc line of best fit
With Application.WorksheetFunction
    mConstant = .LinEst(y, x)(1)
    cConstant = .LinEst(y, x)(2)
End With

'redim array to fill for new Periods
ReDim returnArray(1 To P, 1 To 2)

'Calc new periods based on line of best fit
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    returnArray(i, 1) = UBound(y) / P * i
    If i = LBound(returnArray, 1) Then
        returnArray(i, 2) = (Log(returnArray(i, 1)) * mConstant) + cConstant
    Else
        returnArray(i, 2) = ((Log(returnArray(i, 1)) * mConstant) + cConstant) - _
        ((Log(returnArray(i - 1, 1)) * mConstant) + cConstant)
    End If
Next i

'returnArray can be written to range

End Function
</code>```

EDIT:

This VBA code now calculates the linear trend of the points either side of the new period reduction. The data is returned in a 2dimension array named returnArray

```<code>Sub CallingProc()
Dim Periods As Long, returnArray() As Variant
Dim X_Values() As Variant, Y_Values() As Variant

Periods = 4
ReDim returnArray(1 To Periods, 1 To 2)

With Sheet1
    X_Values = Application.Transpose(.Range("A2:A11"))
    Y_Values = Application.Transpose(.Range("B2:B11"))
End With

FGraph X_Values, Y_Values, returnArray 'pass 1D array of X, 1D array of Y, Dimensioned  ReturnArray
End Sub

Function FGraph(ByVal x As Variant, ByVal y As Variant, ByRef returnArray As Variant)
Dim i As Long, j As Long, mConstant As Double, cConstant As Double, Period As Long

Period = UBound(returnArray, 1)

'calc cumulative Y
For i = LBound(y) + 1 To UBound(y)
        y(i) = y(i) + y(i - 1)
Next i

'Calc new periods based on line of best fit
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    returnArray(i, 1) = UBound(y) / Period * i

        'find position of new period to return adjacent original data points
        For j = LBound(x) To UBound(x)
          If returnArray(i, 1) <= x(j) Then Exit For
        Next j

        'calc linear line of best fit between existing data points
        With Application.WorksheetFunction
            mConstant = .LinEst(Array(y(j), y(j - 1)), Array(x(j), x(j - 1)))(1)
            cConstant = .LinEst(Array(y(j), y(j - 1)), Array(x(j), x(j - 1)))(2)
        End With

        returnArray(i, 2) = (returnArray(i, 1) * mConstant) + cConstant

Next i

'returnarray holds cumulative % so calc period only %
For i = UBound(returnArray, 1) To LBound(returnArray, 1) + 1 Step -1
    returnArray(i, 2) = returnArray(i, 2) - returnArray(i - 1, 2)
Next i

'returnArray now holds your data

End Function
</code>```

Returns:

COLLAPSED

1       38.75%

2       34.35%

3       16.95%

4        9.95%

Body:
I have a 10 period cost curve table below.  How do I programmatically collapse/condense/shrink this to 4 periods.  I'm using VBA but I should be able to follow other languages.  The routine should work for whatever period you pass to it.  For example, if I pass it a 7 it should condense the percentages to 7 periods.  If I pass it 24 then expand the percentages to 24 periods, spreading the percentages based on the original curve.  Any help or example will be appreciated.  Thanks...

ORIGINAL
Period  Pct
1       10.60%
2       19.00%
3       18.30%
4       14.50%
5       10.70%
6        8.90%
7        6.50%
8        3.10%
9        3.00%
10       5.40%

COLLAPSED
Period  Pct
1       38.75%
2       34.35%
3       16.95%
4        9.95%

EDITED:  I've added sample code below as to what I have so far.  It only works for periods 1, 2, 3, 5, 9, 10.  Maybe someone can help modify it to work for any period.  Disclaimer, I'm not a programmer so my coding is bad.  Plus, I have no clue as to what I'm doing.

Sub Collapse_Periods()
    Dim aPct As Variant
    Dim aPer As Variant
    aPct = Array(0.106, 0.19, 0.183, 0.145, 0.107, 0.089, 0.065, 0.031, 0.03, 0.054)
    aPer = Array(1, 2, 3, 5, 9, 10)
    For i = 0 To UBound(aPer)
        pm = 10 / aPer(i)
        pct1 = 1
        p = 0
        ttl = 0
        For j = 1 To aPer(i)
            pct = 0
            k = 1
            Do While k <= pm
                pct = pct + aPct(p) * pct1
                pct1 = 1
                p = p + 1
                If k <> pm And k = Int(pm) Then
                    pct1 = (pm - Int(pm)) * j
                    pct = pct + (pct1 * aPct(p))
                    pct1 = 1 - pct1
                End If
                k = k + 1
            Loop
            Debug.Print aPer(i) & " : " & j & " : " & pct
            ttl = ttl + pct
        Next j
        Debug.Print "Total:  " & ttl
    Next i
End Sub

Body:
I would like to know how this is done also using an Integral? This is how I would have done it - perhaps it's a longhand/longwinded method but I'd like to see some better suggestions.

It's probably easier to see the method in Excel first using the LINEST function and Named ranges. I've assumed the function is logarithmic. I've outlined steps [1.] - [5.]

This VBA code then essentially replicates the Excel method using a function to pass 2 arrays, periods and a return array that can be written to a range

Sub CallingProc()
Dim Periods As Long, returnArray() As Variant
Dim X_Values() As Variant, Y_Values() As Variant

Periods = 4
ReDim returnArray(1 To Periods, 1 To 2)

With Sheet1
    X_Values = Application.Transpose(.Range("A2:A11"))
    Y_Values = Application.Transpose(.Range("B2:B11"))
End With

FGraph X_Values, Y_Values, Periods, returnArray 'pass 1D array of X, 1D array of Y,    Periods, Empty ReturnArray
End Sub

Function FGraph(ByVal x As Variant, ByVal y As Variant, ByVal P As Long, ByRef returnArray As Variant)
Dim i As Long, mConstant As Double, cConstant As Double

'calc cumulative Y and take Ln (Assumes Form of Graph is logarithmic!!)
For i = LBound(y) To UBound(y)
    If i = LBound(y) Then
        y(i) = y(i)
    Else
        y(i) = y(i) + y(i - 1)
    End If

    x(i) = Log(x(i))
Next i

'calc line of best fit
With Application.WorksheetFunction
    mConstant = .LinEst(y, x)(1)
    cConstant = .LinEst(y, x)(2)
End With

'redim array to fill for new Periods
ReDim returnArray(1 To P, 1 To 2)

'Calc new periods based on line of best fit
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    returnArray(i, 1) = UBound(y) / P * i
    If i = LBound(returnArray, 1) Then
        returnArray(i, 2) = (Log(returnArray(i, 1)) * mConstant) + cConstant
    Else
        returnArray(i, 2) = ((Log(returnArray(i, 1)) * mConstant) + cConstant) - _
        ((Log(returnArray(i - 1, 1)) * mConstant) + cConstant)
    End If
Next i

'returnArray can be written to range

End Function

EDIT:

This VBA code now calculates the linear trend of the points either side of the new period reduction. The data is returned in a 2dimension array named returnArray

Sub CallingProc()
Dim Periods As Long, returnArray() As Variant
Dim X_Values() As Variant, Y_Values() As Variant

Periods = 4
ReDim returnArray(1 To Periods, 1 To 2)

With Sheet1
    X_Values = Application.Transpose(.Range("A2:A11"))
    Y_Values = Application.Transpose(.Range("B2:B11"))
End With

FGraph X_Values, Y_Values, returnArray 'pass 1D array of X, 1D array of Y, Dimensioned  ReturnArray
End Sub

Function FGraph(ByVal x As Variant, ByVal y As Variant, ByRef returnArray As Variant)
Dim i As Long, j As Long, mConstant As Double, cConstant As Double, Period As Long

Period = UBound(returnArray, 1)

'calc cumulative Y
For i = LBound(y) + 1 To UBound(y)
        y(i) = y(i) + y(i - 1)
Next i

'Calc new periods based on line of best fit
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    returnArray(i, 1) = UBound(y) / Period * i

        'find position of new period to return adjacent original data points
        For j = LBound(x) To UBound(x)
          If returnArray(i, 1) <= x(j) Then Exit For
        Next j

        'calc linear line of best fit between existing data points
        With Application.WorksheetFunction
            mConstant = .LinEst(Array(y(j), y(j - 1)), Array(x(j), x(j - 1)))(1)
            cConstant = .LinEst(Array(y(j), y(j - 1)), Array(x(j), x(j - 1)))(2)
        End With

        returnArray(i, 2) = (returnArray(i, 1) * mConstant) + cConstant

Next i

'returnarray holds cumulative % so calc period only %
For i = UBound(returnArray, 1) To LBound(returnArray, 1) + 1 Step -1
    returnArray(i, 2) = returnArray(i, 2) - returnArray(i - 1, 2)
Next i

'returnArray now holds your data

End Function

Returns:

COLLAPSED

1       38.75%

2       34.35%

3       16.95%

4        9.95%


问:
How do I set up an automated CSV export job from Azure SQL Server?
In an on-prem SQL Server I have the option to set up scheduled Jobs with the SQL Server Agent. This feature is not present in Azure. Is there any way to do this easily in Azure or will I have to rely on automation scripts  / powershell scripting for this?

The task I want to accomplish is to export a bunch of SQL views to CSV and send them to a remote FTP server.

答:
In Azure, through Logic Apps, you can achieve this. Please check below steps.

Go to Azure Portal ( http://portal.azure.com/ ) and Search Logic Apps.

Click Add and fill the details like Logic App Name, Subscription,Resource group, Location and click Create.

After refreshing the page, click the Created Logic App. In the home page, choose Blank Logic App.

In the Logic Apps designer Page, Search for Schedule or Recurrence and click it.

Fill the Interval, Frequency, Time zone (Format is important – 2018-10-16T21:00:00Z ), Start time, at these hours, at these minutes, Check the Preview.

Choose an Action, Search for SQL Server and Click Execute Stored Procedure in the list.

Click Add New connection at the end if you want to create new connection. Then Click Manually Enter Connection Information at the end if you want to create new connection.

Or else use anyone of the Existing connections. Fill the Procedure name with the required SP & below are the input parameters of the SP that you selected.

Choose an Action, Search for Create CSV Table and Click it. Fill the From (choose dynamic result set from the right side-Choose first result set alone), Include Headers (Yes), Columns (Automatic).

Choose an Action, Search for Office 365 Outlook & Search for Send an Email and Click it. Before proceeding, Please check mail id at the bottom. Change as yours. Fill the To (zzzzzz@xxxxxx.com;zzzzz@xxxxx.com), Subject (Demo mail), Body (Please check the test attachment), From & CC & BCC (email id’s for whom you want to send), Important (Normal), Is HTML (NO), Attachment Name {choose expression from the right hand side and type concat('Test_mail',utcnow('dd-MM-yyyy'),'.csv')  }, Attachment Content (Choose output from the right hand side).

Finally Click Save at the left hand side top. Click Designer option to edit, after edit completes, again save that. Click Run for Demo Run.
Click Run to initiate the trigger. Then only the automated mails should come at mentioned intervals.
Select the Required Logic App and click Delete to delete it (will ask Logic App name to delete).
You should have access to do the above changes and you have to sign in to open the azure portal.


问:
display grid empty div as spacer?
Building out a navbar that will look something like this:

```<code>|----------------------------------------------------------|
|                  link     Logo     link            link  |
|----------------------------------------------------------|
</code>```

My thought process for creating this layout is to have a html structure that looks like:

```<code><nav>
  <div></div>
  <div>
    link
    logo
    link
  </div>
  <div>
    link
  </div>
</nav>
</code>```

and then with CSS, I would do something like:

```<code>display: grid;
grid-template-columns: 200px auto 200px;
...
</code>```

My question here is: is there a better way to recreate this layout? I don't like how I use an empty div to create the space.

I know I can remove the empty div and put something like margin-left: 200px on the 2nd div but that seems kinda hacky as well.

Appreciate the input.

答:
From the comments from the original question, I was able to find the grid-column-start property and that was exactly what I needed. I appreciate everyone commenting but I feel like the ones saying to use a library/frameworks to build a navbar is overkill. Knowing how to actually build these layouts are what makes you a better developer.

This is what I ended up doing:

```<code><div class="navbar">
    <div class="navbar--content">
        <div class="navbar--content--middle">
            <div class='row row__align-center row__center'>
                <a href="#">shop now</a>
                <a href="#">logo</a>
                <a href="#">FAQ</a>
               </div>
        </div>
        <div class="navbar--content--right">
            <a href="#">user img</a>
            <a href="#">bag</a>
        </div>
    </div>
</div>
</code>```

And the css:

```<code>.navbar {

    &--content {
        padding: 20px 0;

        display: grid;
        grid-template-columns: 200px auto 200px;
        align-items: center;

        &--middle {
            grid-column-start: 2;

            a {
                width: 100px;
                text-decoration: none;
                font-weight: 600;

                &:first-child {
                    margin-right: 100px;
                }

                &:nth-child(2) {
                    display: flex;
                    flex-flow: column nowrap;
                    justify-content: center;
                }

                &:last-child {
                    margin-left: 100px;
                }
            }
        }

        &--right {
            text-align: right;

            a {
                &:first-child img {
                    height: 30px;
                    margin-right: 10px;
                }

                &:last-child img {
                    height: 35px;
                }
            }
        }
    }
}
</code>```

Title: display grid empty div as spacer?

Body:
Building out a navbar that will look something like this:

|----------------------------------------------------------|
|                  link     Logo     link            link  |
|----------------------------------------------------------|

My thought process for creating this layout is to have a html structure that looks like:

    link
    logo
    link

    link

and then with CSS, I would do something like:

display: grid;
grid-template-columns: 200px auto 200px;
...

My question here is: is there a better way to recreate this layout? I don't like how I use an empty div to create the space.

I know I can remove the empty div and put something like margin-left: 200px on the 2nd div but that seems kinda hacky as well.

Appreciate the input.

Body:
From the comments from the original question, I was able to find the grid-column-start property and that was exactly what I needed. I appreciate everyone commenting but I feel like the ones saying to use a library/frameworks to build a navbar is overkill. Knowing how to actually build these layouts are what makes you a better developer.

This is what I ended up doing:

<div class="navbar">
    <div class="navbar--content">
        <div class="navbar--content--middle">
            <div class='row row__align-center row__center'>
                <a href="#">shop now</a>
                <a href="#">logo</a>
                <a href="#">FAQ</a>
               </div>
        </div>
        <div class="navbar--content--right">
            <a href="#">user img</a>
            <a href="#">bag</a>
        </div>
    </div>
</div>

And the css:

.navbar {

    &--content {
        padding: 20px 0;

        display: grid;
        grid-template-columns: 200px auto 200px;
        align-items: center;

        &--middle {
            grid-column-start: 2;

            a {
                width: 100px;
                text-decoration: none;
                font-weight: 600;

                &:first-child {
                    margin-right: 100px;
                }

                &:nth-child(2) {
                    display: flex;
                    flex-flow: column nowrap;
                    justify-content: center;
                }

                &:last-child {
                    margin-left: 100px;
                }
            }
        }

        &--right {
            text-align: right;

            a {
                &:first-child img {
                    height: 30px;
                    margin-right: 10px;
                }

                &:last-child img {
                    height: 35px;
                }
            }
        }
    }
}


问:
SQL join greater than / less then
I have 2 tables

I
So i need to get a table in which rows will be excluded for which the date for each "id" is more than in the second table "datestop"

I tried inner join with double condition:
id = id and Date < DateStop, but in this way also excluded rows which not contained in table 2 (id1)

For imagine, thats what i want to get:

答:
This is a situation where all can be helpful:

```<code>select a.*
from a
where a.date < all (select b.datestop
                    from b
                    where b.id = a.id and b.status = 'Stopped'
                   );
</code>```

Title: SQL join greater than / less then

Body:
This is a situation where all can be helpful:

select a.*
from a
where a.date < all (select b.datestop
                    from b
                    where b.id = a.id and b.status = 'Stopped'
                   );


问:
Converting number to currency in MERN app - where to include the function to generate the currency output?
I am trying to generate a number to display as currency.  I am using the following code in the app.js file:

```<code>function currencyFormat(num) {
        return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
      };
</code>```

In the ejs file to intake the data I have:

```<code><input id="input" class="form-control" type="number" name="targetVolume">
</code>```

In the show file to display the data, I have:

```<code><p><span>Volume: </span><%= plan.targetVolume %></p>
</code>```

Where do I put the currencyFormat to display the inputted number to display it as currency on the show page?

Thank you.

答:
You may want to use Javascript's Intl.NumberFormat class for this purpose to implement your function.  Like so:

```<code>function currencyFormat(num) {
  const currency = new Intl.NumberFormat('en-US', {
                                                    style: 'currency',
                                                    currency: 'USD'
                                                  })
  return currency.format(number)
};
</code>```

It's tested; it's documented; it's adaptable to different locales and currencies.

Then call your function when rendering the currency value, something like this.

```<code><p><span>Price: </span><%= currencyFormat(plan.price) %></p>
</code>```

Body:
I am trying to generate a number to display as currency.  I am using the following code in the app.js file:

function currencyFormat(num) {
        return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
      };

In the ejs file to intake the data I have:

<input id="input" class="form-control" type="number" name="targetVolume">

In the show file to display the data, I have:

Volume: <%= plan.targetVolume %>

Where do I put the currencyFormat to display the inputted number to display it as currency on the show page?

Thank you.

Body:
You may want to use Javascript's Intl.NumberFormat class for this purpose to implement your function.  Like so:

function currencyFormat(num) {
  const currency = new Intl.NumberFormat('en-US', {
                                                    style: 'currency',
                                                    currency: 'USD'
                                                  })
  return currency.format(number)
};

It's tested; it's documented; it's adaptable to different locales and currencies.

Then call your function when rendering the currency value, something like this.

<p><span>Price: </span><%= currencyFormat(plan.price) %></p>


问:
How to find all possible combinations from a list with only two elements and no duplicates with Python?
I have the following:

```<code>list = ["player1", "player2", "player3"]
</code>```

I want to find all possible combinations of two elements of that list, but with no duplicates. I have tried to work with the itertools.combinations() but without the desired result.

I'm looking for a result like this:

```<code>player1, player2
player1, player3
player2, player3
</code>```

Can someone help me in the right direction?

Thanks in advance

答:
You can try this, as it makes use of combinations so import it from itertools like this:

```<code>from itertools import combinations

#also it's good practice not to use list, so for sake of it call it something else
listPlayers = ["player1", "player2", "player3"]

getPairPlayers = sorted(map(sorted, combinations(set(listPlayers), 2)))

print(getPairPlayers)
</code>```

Output:

```<code>[['player1', 'player2'], ['player1', 'player3'], ['player2', 'player3']]
</code>```

Body:
I have the following:

list = ["player1", "player2", "player3"]

I want to find all possible combinations of two elements of that list, but with no duplicates. I have tried to work with the itertools.combinations() but without the desired result.

I'm looking for a result like this:

player1, player2
player1, player3
player2, player3

Can someone help me in the right direction?

Thanks in advance

Body:
You can try this, as it makes use of combinations so import it from itertools like this:

from itertools import combinations

#also it's good practice not to use list, so for sake of it call it something else
listPlayers = ["player1", "player2", "player3"]

getPairPlayers = sorted(map(sorted, combinations(set(listPlayers), 2)))

print(getPairPlayers)

Output:

[['player1', 'player2'], ['player1', 'player3'], ['player2', 'player3']]


问:
didn't return an HttpResponse object. It returned None instead
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

```<code>def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)
</code>```

urls.py:

```<code>urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
</code>```

main/urls.py:

```<code>urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
Your return should be four space back, That means the return should not be under the else condition.

change the views.py from this:

```<code>else:
  form = RegistrationForm()

  args = {'form': form}
  return render(request, 'accounts/reg_form.html', args)
</code>```

to this:

```<code>else:
  form = RegistrationForm()

  args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
</code>```

Body:
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)

urls.py:

urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

main/urls.py:

urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
Your return should be four space back, That means the return should not be under the else condition.

change the views.py from this:

else:
  form = RegistrationForm()

  args = {'form': form}
  return render(request, 'accounts/reg_form.html', args)

to this:

else:
  form = RegistrationForm()

  args = {'form': form}
return render(request, 'accounts/reg_form.html', args)


问:
How to return documents from firebase with specific variables?
I want to view documents only with Number is less than or equal to 10 (not to show all documents).
here is my code:

```<code>Future getHomeWsyl()async{
    var firestore = Firestore.instance;
    QuerySnapshot snapshot = await firestore.collection("HomePageWsyl").getDocuments();
    return snapshot.documents;
}
</code>```

what to correct in this code to do this?

enter image description here

答:
To only get a limit number of documents, use the limit method.

So something like:

```<code>firestore.collection("HomePageWsyl").limit(10).getDocuments();
</code>```

To only get documents where a field matches a certain condition, use the where method.

So something like:

```<code>firestore.collection("HomePageWsyl").where("Number", isLessThanOrEqualTo: 10).getDocuments();
</code>```

This means that your documents must have a field named Number with a numeric value.

I recommend getting familiar with the Firestore documentation on queries and ordering and limiting data, and with the reference documentation for the cloud_firestore package, specifically the Query class.

Body:
I want to view documents only with Number is less than or equal to 10 (not to show all documents).
here is my code:

Future getHomeWsyl()async{
    var firestore = Firestore.instance;
    QuerySnapshot snapshot = await firestore.collection("HomePageWsyl").getDocuments();
    return snapshot.documents;
}

what to correct in this code to do this?

enter image description here

Body:
To only get a limit number of documents, use the limit method.

So something like:

firestore.collection("HomePageWsyl").limit(10).getDocuments();

To only get documents where a field matches a certain condition, use the where method.

So something like:

firestore.collection("HomePageWsyl").where("Number", isLessThanOrEqualTo: 10).getDocuments();

This means that your documents must have a field named Number with a numeric value.

I recommend getting familiar with the Firestore documentation on queries and ordering and limiting data, and with the reference documentation for the cloud_firestore package, specifically the Query class.


问:
ASP.Net Web Api Get Reques By Selected Column
I have a database with primary key Auto increment id when a send a get request to web api I want to filter datas by specified columns equals something.
When i tried this in SSMS its working
Select top 1000 from [dbo.][ogrencisonuclar] where kullaniciid='1'
But How can i do this request by web api ? I'm using entity framework. When I requested datas filtering by primary key id not kullaniciid..

This is code on my web api

```<code> public ogrencisonuclar Get(int ID)
        {
            using (denemetabloEntities entities = new denemetabloEntities())
            {

                ogrencisonuclar sonuc = entities.ogrencisonuclar.Find(ID);
                return sonuc;
            }
        }
</code>```

This is the code on Xamarin to request datas by kullaniciid;

```<code>var client1 = new RestClient("http://mikrontasarim.somee.com/api/ogrencisonuclar/Get/" + kullid);
            client1.Timeout = -1;
            var request1 = new RestRequest(Method.GET);

            var response1 = client1.Execute<List<Models.sonucagecismodeli>>(request1);
            List<Models.sonucagecismodeli> events = response1.Data;
</code>```

答:
Find always queries by the PK.  You can use a LINQ query to query on other parameters

```<code>ogrencisonuclar sonuc = entities.ogrencisonuclar.Where(x => x.kullaniciid == ID).FirstOrDefault();
</code>```

to fetch all matching rows

```<code>ogrencisonuclar sonuc = entities.ogrencisonuclar.Where(x => x.kullaniciid == ID).ToList();
</code>```

Docs

Body:
I have a database with primary key Auto increment id when a send a get request to web api I want to filter datas by specified columns equals something.
When i tried this in SSMS its working
Select top 1000 from [dbo.][ogrencisonuclar] where kullaniciid='1'
But How can i do this request by web api ? I'm using entity framework. When I requested datas filtering by primary key id not kullaniciid..

This is code on my web api

 public ogrencisonuclar Get(int ID)
        {
            using (denemetabloEntities entities = new denemetabloEntities())
            {

                ogrencisonuclar sonuc = entities.ogrencisonuclar.Find(ID);
                return sonuc;
            }
        }

This is the code on Xamarin to request datas by kullaniciid;

var client1 = new RestClient("http://mikrontasarim.somee.com/api/ogrencisonuclar/Get/" + kullid);
            client1.Timeout = -1;
            var request1 = new RestRequest(Method.GET);

            var response1 = client1.Execute<List<Models.sonucagecismodeli>>(request1);
            List<Models.sonucagecismodeli> events = response1.Data;

Body:
Find always queries by the PK.  You can use a LINQ query to query on other parameters

ogrencisonuclar sonuc = entities.ogrencisonuclar.Where(x => x.kullaniciid == ID).FirstOrDefault();

to fetch all matching rows

ogrencisonuclar sonuc = entities.ogrencisonuclar.Where(x => x.kullaniciid == ID).ToList();

Docs


问:
Optimal inversion counting on int arrays
Today I was looking the latest exam of the local informatics olympiad and I found a interesting problem. Briefly, it asks to, given an integer array, count how many inversions it has, where an inversion is a pair of indicies i, j such that i > j and A[i] < A[j]. Informally, the number of inversions is the number of pairs that are out of order. Initially I made a O(n²) solution (yes, the naive one), but seeing it wouldn't fit well with the size of the input, I thought about the problem a bit more and then I realized it's possible to do it within O(n log n) time by a variant of merge sort, which handles good the size of the input.

But seeing the input constraints (n integers between 1 and M, and no duplicates), I was wondering if my solution is optimal, or do you know if is there any other solution to this problem that beats O(n log n) runtime?

答: The best result in the literature is an O(n √(log n)) algorithm due to Chan and Patrascu. No idea about the constant.</p>