问:
How can i notify to App for what reload the app to show another screen?
I am in login screen i pressed the button login so

that button have this action

```<code>store.dispatch({
      type: 'login',
      payload: {
        name: email.value
      },
    })
</code>```

on the reducers change the value

```<code>export default function (state, action) {
  switch (action.type) {
    case 'login':
      return {
        ...state,
        user: action.payload,
        isLogged:true
      }
    default:
      return newState
  }
}
</code>```

now i have to notify to App.js for the new change because that is depend to show the stack.screen

```<code>export default function App() {
  return (
    <Provider store={store} theme={theme}>
      <Tabs store={store} />
    </Provider>
  )
}
</code>```

How can i notify to App for what reload the app to show another screen?

but never my component is updated, i was trying to update my component using useEffect but not

```<code>function Tabs ({ user })  {
  const {
    data: { isLogged },
  } = useSelector((state) => state)

  useEffect(() => {
    console.log(1234546)
  }, [isLogged, user])

 return (
     <Stack.Navigator >
            { !store.getState().data.isLogged ?
              <Stack.Screen
                name="loginScreen1"
                component={HomeScreen}
                options={{ headerShown: false }}
              /> :
              <Stack.Screen
                name="main"
                component={MyTabs}
                options={{ headerShown: false }}
              />}
          </Stack.Navigator>
 )
</code>```

答:
App navigator need to subscribe  isLogged state then rerender accordingly.

import { useEffect } from "react";
import { useSelector } from "react-redux";

const App = () => {
  const isLogged = useSelector((state) => state.isLogged);

  // Track authentication state
  useEffect(() => {}, [isLogged]);

  return (
    <Stack.Navigator>
      {!isLogged ? (
        <Stack.Screen
          name="loginScreen1"
          component={HomeScreen}
          options={{ headerShown: false }}
        />
      ) : (
        <Stack.Screen
          name="main"
          component={MyTabs}
          options={{ headerShown: false }}
        />
      )}
    </Stack.Navigator>
  );
};

```

Body:
I am in login screen i pressed the button login so

that button have this action

store.dispatch({
      type: 'login',
      payload: {
        name: email.value
      },
    })

on the reducers change the value

export default function (state, action) {
  switch (action.type) {
    case 'login':
      return {
        ...state,
        user: action.payload,
        isLogged:true
      }
    default:
      return newState
  }
}

now i have to notify to App.js for the new change because that is depend to show the stack.screen

export default function App() {
  return (
    <Provider store={store} theme={theme}>
      <Tabs store={store} />
    </Provider>
  )
}

How can i notify to App for what reload the app to show another screen?

but never my component is updated, i was trying to update my component using useEffect but not

function Tabs ({ user })  {
  const {
    data: { isLogged },
  } = useSelector((state) => state)

  useEffect(() => {
    console.log(1234546)
  }, [isLogged, user])

 return (
     <Stack.Navigator >
            { !store.getState().data.isLogged ?
              <Stack.Screen
                name="loginScreen1"
                component={HomeScreen}
                options={{ headerShown: false }}
              /> :
              <Stack.Screen
                name="main"
                component={MyTabs}
                options={{ headerShown: false }}
              />}
          </Stack.Navigator>
 )


来源: stackexchange

问:
route or applogic
trying to get rails routing to "click" and just not getting it

have a project and a task model:

```<code>class Task
  include Mongoid::Document

  field :title,                     :type => String
  has_many :projects
  belongs_to :user
end

class Project

  include Mongoid::Document

  field :title,                     :type => String
  has_and_belongs_to_many           :tasks
  belongs_to                        :user
end
</code>```

I want to "associate" a task with a project
so I have this in the project controller:

```<code>def connect
  @project = Project.find(params[:id])
  @project.tasks_ids.push(params[:task_id])
  @project.save
  redirect_to project
end
</code>```

with this route:

```<code>resources :projects do
    match 'connect/:id' => 'projects#connect', :as => :connect, :via => :put
    resources :tasks
end
</code>```

I cant seem to get this to work in the view:

```<code> = link_to 'Associate Task', project_connect_path(@task)
</code>```

fails with:

No route matches {:controller=>"projects", :action=>"connect"}

答:
Try to do this:

```<code>resources :projects do
member do
 put 'connect'
end
resources :tasks
end
</code>```

or you can write your route above the resources :projects do ...
and here is the link, you can read more about routes there: Rails routes

ContentLicense: CC BY-SA 3.0

Title: route or applogic

Body:
trying to get rails routing to "click" and just not getting it

have a project and a task model:

class Task
  include Mongoid::Document

  field :title,                     :type => String
  has_many :projects
  belongs_to :user
end

class Project

  include Mongoid::Document

  field :title,                     :type => String
  has_and_belongs_to_many           :tasks
  belongs_to                        :user
end

I want to "associate" a task with a project
so I have this in the project controller:

def connect
  @project = Project.find(params[:id])
  @project.tasks_ids.push(params[:task_id])
  @project.save
  redirect_to project
end

with this route:

resources :projects do
    match 'connect/:id' => 'projects#connect', :as => :connect, :via => :put
    resources :tasks
end

I cant seem to get this to work in the view:

 = link_to 'Associate Task', project_connect_path(@task)

fails with:

No route matches {:controller=>"projects", :action=>"connect"}

Body:
Try to do this:

resources :projects do
member do
 put 'connect'
end
resources :tasks
end

or you can write your route above the resources :projects do ...
and here is the link, you can read more about routes there: Rails routes


答:
Instead of all this, why not use the formula to calculate the time it takes for a value to reach another with compound interest rate?

The problem can be expressed as: A x (1+e)^t = B and we want to find t. So, t = log(B/A) / log(1+e)

```<code>import math
B = 2000
A = 1000
e = 0.07
out = math.ceil(math.log(B/A) / math.log(1+e))
</code>```

Output:

```<code>11
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why is my program calculating the compound interest twice

Body:
I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal:
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001,
1225.0430000000001, 1310.7960100000003, 1310.7960100000003,
1402.5517307000005, 1402.5517307000005, 1500.7303518490005,
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556,
1838.4592124201556, 1967.1513572895667, 1967.1513572895667,
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.

Body:
Instead of all this, why not use the formula to calculate the time it takes for a value to reach another with compound interest rate?

The problem can be expressed as: A x (1+e)^t = B and we want to find t. So, t = log(B/A) / log(1+e)

import math
B = 2000
A = 1000
e = 0.07
out = math.ceil(math.log(B/A) / math.log(1+e))

Output:

11


问:
Design pattern - Python function applied to different objects
I have modified Numpy's apply_along_axis() function and I want to be able to use this function on different objects (such as xarray.DataArray and other multi-dimensional data structures). My modified apply_along_axis() coerces the input to a numpy array using np.asanyarray(). I would like to have a design pattern where i can apply this function to different objects but preserve the meta-data associated with those objects. The meta-data/attributes are now lost because of the coercion to a numpy array.

I do not want to modify the core functionality of apply_along_axis() or do type checking on the arguments within apply_along_axis(). I want to be able to easily add support for new data structures in the future...  I was thinking of either wrapping the input datastructures or the apply_along_axis() function. But I'm not sure how to go about it. Looking for elegant solutions.

Here is the code for the apply_along_axis() function:

```<code>def apply_along_axis(func1d, axis, arr, progress_bar=None, *args, **kwargs):
    '''
    Modified from numpy's apply_along_axis function
    '''

    arr = asanyarray(arr)
    nd = arr.ndim
    # arr, with the iteration axis at the end
    in_dims = list(range(nd))
    inarr_view = np.transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])
    # compute indices for the iteration axes
    inds = iter(ndindex(inarr_view.shape[:-1]))
    # invoke the function on the first item
    try:
        ind0 = next(inds)
    except StopIteration as e:
        raise ValueError(
            'Cannot apply_along_axis when any iteration dimensions are 0'
        ) from None
    res = func1d(inarr_view[ind0], *args, **kwargs)
    # build a buffer for storing evaluations of func1d.
    # remove the requested axis, and add the new ones on the end.
    # laid out so that each write is contiguous.
    # for a tuple index inds, buff[inds] = func1d(inarr_view[inds])
    buff = np.zeros(inarr_view.shape[:-1] + res.shape, res.dtype)
    # permutation of axes such that out = buff.transpose(buff_permute)
    buff_dims = list(range(buff.ndim))
    buff_permute = (
        buff_dims[0 : axis] +
        buff_dims[buff.ndim-res.ndim : buff.ndim] +
        buff_dims[axis : buff.ndim-res.ndim]
    )
    # save the first result, then compute and save all remaining results
    buff[ind0] = res
    if progress_bar:
        inds = progress_bar(list(inds))
    for ind in inds:
        buff[ind] = func1d(inarr_view[ind], *args, **kwargs)

    # finally, rotate the inserted axes back to where they belong
    return np.transpose(buff, buff_permute)
</code>```

Edit: I realised that the part I left out from the original numpy function might actually be part of the solution. I think i'm looking for a functionality similar to __array_wrap__:

```<code># wrap the array, to preserve subclasses
buff = res.__array_wrap__(buff)
</code>```

Still not sure how to adapt or write my own __array_wrap__ to preserve Xarray and other class attributes... Any ideas are welcome

答:
Just to highlight a couple of features in the function.

First make a view that has axis last:

```<code>inarr_view = np.transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])
</code>```

Then make an iterator - on all axes except the last one:

```<code>inds = iter(ndindex(inarr_view.shape[:-1]))
</code>```

This is a trial calculation, used to determine the dtype and shape of what func1d does:

```<code>res = func1d(inarr_view[ind0], *args, **kwargs)
</code>```

Then it makes an array to receive results:

```<code>buff = np.zeros(inarr_view.shape[:-1] + res.shape, res.dtype)
</code>```

The work is an iteration over all the inds indices:

```<code>for ind in inds:
    buff[ind] = func1d(inarr_view[ind], *args, **kwargs)
</code>```

where inarr_view[ind] is a 1d array.

Imagine arr is a 2d array, and we want to pass rows to func1d.  We could just do np.array([func1d(x) for x in arr]).  That is, just iterate on rows, passing them one at time to func1d, and make an array from that.  apply... is just a generalization of that pattern.

to illustrate:

```<code>In [29]: def foo(x):
    ...:     print('x',x)
    ...:     return x**2
    ...:
In [30]: arr = np.arange(12).reshape(3,4)
In [31]: np.apply_along_axis(foo, 1, arr)
x [0 1 2 3]
x [4 5 6 7]
x [ 8  9 10 11]
Out[31]:
array([[  0,   1,   4,   9],
       [ 16,  25,  36,  49],
       [ 64,  81, 100, 121]])
In [32]: [foo(row) for row in arr]
x [0 1 2 3]
x [4 5 6 7]
x [ 8  9 10 11]
Out[32]: [array([0, 1, 4, 9]), array([16, 25, 36, 49]), array([ 64,  81, 100, 121])]
</code>```

times (without the print):

```<code>In [35]: timeit np.apply_along_axis(foo, 1, arr)
75.7 µs ± 2.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [36]: timeit np.array([foo(row) for row in arr])
11.4 µs ± 18.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

apply scales better, and may be faster for large enough arrays.

Body:
I have modified Numpy's apply_along_axis() function and I want to be able to use this function on different objects (such as xarray.DataArray and other multi-dimensional data structures). My modified apply_along_axis() coerces the input to a numpy array using np.asanyarray(). I would like to have a design pattern where i can apply this function to different objects but preserve the meta-data associated with those objects. The meta-data/attributes are now lost because of the coercion to a numpy array.

I do not want to modify the core functionality of apply_along_axis() or do type checking on the arguments within apply_along_axis(). I want to be able to easily add support for new data structures in the future...  I was thinking of either wrapping the input datastructures or the apply_along_axis() function. But I'm not sure how to go about it. Looking for elegant solutions.

Here is the code for the apply_along_axis() function:

def apply_along_axis(func1d, axis, arr, progress_bar=None, *args, **kwargs):
    '''
    Modified from numpy's apply_along_axis function
    '''

    arr = asanyarray(arr)
    nd = arr.ndim
    # arr, with the iteration axis at the end
    in_dims = list(range(nd))
    inarr_view = np.transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])
    # compute indices for the iteration axes
    inds = iter(ndindex(inarr_view.shape[:-1]))
    # invoke the function on the first item
    try:
        ind0 = next(inds)
    except StopIteration as e:
        raise ValueError(
            'Cannot apply_along_axis when any iteration dimensions are 0'
        ) from None
    res = func1d(inarr_view[ind0], *args, **kwargs)
    # build a buffer for storing evaluations of func1d.
    # remove the requested axis, and add the new ones on the end.
    # laid out so that each write is contiguous.
    # for a tuple index inds, buff[inds] = func1d(inarr_view[inds])
    buff = np.zeros(inarr_view.shape[:-1] + res.shape, res.dtype)
    # permutation of axes such that out = buff.transpose(buff_permute)
    buff_dims = list(range(buff.ndim))
    buff_permute = (
        buff_dims[0 : axis] +
        buff_dims[buff.ndim-res.ndim : buff.ndim] +
        buff_dims[axis : buff.ndim-res.ndim]
    )
    # save the first result, then compute and save all remaining results
    buff[ind0] = res
    if progress_bar:
        inds = progress_bar(list(inds))
    for ind in inds:
        buff[ind] = func1d(inarr_view[ind], *args, **kwargs)

    # finally, rotate the inserted axes back to where they belong
    return np.transpose(buff, buff_permute)

Edit: I realised that the part I left out from the original numpy function might actually be part of the solution. I think i'm looking for a functionality similar to __array_wrap__:

# wrap the array, to preserve subclasses
buff = res.__array_wrap__(buff)

Still not sure how to adapt or write my own __array_wrap__ to preserve Xarray and other class attributes... Any ideas are welcome

Body:
Just to highlight a couple of features in the function.

First make a view that has axis last:

inarr_view = np.transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])

Then make an iterator - on all axes except the last one:

inds = iter(ndindex(inarr_view.shape[:-1]))

This is a trial calculation, used to determine the dtype and shape of what func1d does:

res = func1d(inarr_view[ind0], *args, **kwargs)

Then it makes an array to receive results:

buff = np.zeros(inarr_view.shape[:-1] + res.shape, res.dtype)

The work is an iteration over all the inds indices:

for ind in inds:
    buff[ind] = func1d(inarr_view[ind], *args, **kwargs)

where inarr_view[ind] is a 1d array.

Imagine arr is a 2d array, and we want to pass rows to func1d.  We could just do np.array([func1d(x) for x in arr]).  That is, just iterate on rows, passing them one at time to func1d, and make an array from that.  apply... is just a generalization of that pattern.

to illustrate:

In [29]: def foo(x):
    ...:     print('x',x)
    ...:     return x**2
    ...:
In [30]: arr = np.arange(12).reshape(3,4)
In [31]: np.apply_along_axis(foo, 1, arr)
x [0 1 2 3]
x [4 5 6 7]
x [ 8  9 10 11]
Out[31]:
array([[  0,   1,   4,   9],
       [ 16,  25,  36,  49],
       [ 64,  81, 100, 121]])
In [32]: [foo(row) for row in arr]
x [0 1 2 3]
x [4 5 6 7]
x [ 8  9 10 11]
Out[32]: [array([0, 1, 4, 9]), array([16, 25, 36, 49]), array([ 64,  81, 100, 121])]

times (without the print):

In [35]: timeit np.apply_along_axis(foo, 1, arr)
75.7 µs ± 2.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [36]: timeit np.array([foo(row) for row in arr])
11.4 µs ± 18.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

apply scales better, and may be faster for large enough arrays.


问:
calculating counts and percentages of a variable
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

```<code>UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

</code>```

I want a count of the total observations of substance use like this:

```<code>UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

</code>```

And then, I want the % of visits that participants said yes and no, like this:

```<code>UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%
</code>```

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.

答:
Not sure if you need the aggregated (!) info in each row or rather want to summarize per ID, in which case you can do:
(using the same df1 data as provided in akrun‘s answer)

```<code>library(tidyverse)
library(scales)
df1 %>%
  group_by(UserID) %>%
  summarize(count = n(),
            percent_yes = percent(sum(substance_use == 1)/count),
            percent_no = percent(sum(substance_use == 0)/count))
</code>```

which gives:

```<code># A tibble: 2 x 4
  UserID count percent_yes percent_no
   <int> <int> <chr>       <chr>
1    215     2 100%        0%
2  43124     5 40%         60%
</code>```

Body:
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

I want a count of the total observations of substance use like this:

UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

And then, I want the % of visits that participants said yes and no, like this:

UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.

Body:
Not sure if you need the aggregated (!) info in each row or rather want to summarize per ID, in which case you can do:
(using the same df1 data as provided in akrun‘s answer)

library(tidyverse)
library(scales)
df1 %>%
  group_by(UserID) %>%
  summarize(count = n(),
            percent_yes = percent(sum(substance_use == 1)/count),
            percent_no = percent(sum(substance_use == 0)/count))

which gives:

# A tibble: 2 x 4
  UserID count percent_yes percent_no
   <int> <int> <chr>       <chr>
1    215     2 100%        0%
2  43124     5 40%         60%


问:
Android Studio custom button color is not changing while shape is changing
I added a custom button, changed some values for every state but still when I press the button the button is not changing, and just getting the default style, I changed the shape in form rectangle to oval so I can see if in selector does it enter to the pressed state and I see it does enter now the only problem is the solid or the color that its not changing.

custom button implementation:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><item android:state_enabled="false">
    <shape android:shape="rectangle">
        <solid android:color="@color/LightGray"/>
        <corners android:radius="200dp"/>
    </shape>
</item>

<item android:state_pressed="true">
    <color android:color="@color/Blue"/>
    <shape android:shape="rectangle">
        <corners android:radius="200dp"/>
    </shape>
</item>

<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/DarkBlue"/>
        <corners android:radius="200dp"/>
    </shape>
</item>
</code>```

and Button implementation:

```<code>  <Button
    android:id="@+id/btnNext"
    android:layout_width="102dp"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="68dp"
    android:text="Next >"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
   />
</code>```

答:
I  figured out that when using the custom  button make  sure to change the

```<code><Button.../>
</code>```

to

```<code><androidx.appcompat.widget.AppCompatButton
</code>```

It's due to material io buttons can't accept custom buttons as background.

Body:
I added a custom button, changed some values for every state but still when I press the button the button is not changing, and just getting the default style, I changed the shape in form rectangle to oval so I can see if in selector does it enter to the pressed state and I see it does enter now the only problem is the solid or the color that its not changing.

custom button implementation:

<?xml version="1.0" encoding="utf-8"?>

<item android:state_enabled="false">
    <shape android:shape="rectangle">
        <solid android:color="@color/LightGray"/>
        <corners android:radius="200dp"/>
    </shape>
</item>

<item android:state_pressed="true">
    <color android:color="@color/Blue"/>
    <shape android:shape="rectangle">
        <corners android:radius="200dp"/>
    </shape>
</item>

<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/DarkBlue"/>
        <corners android:radius="200dp"/>
    </shape>
</item>

and Button implementation:

  <Button
    android:id="@+id/btnNext"
    android:layout_width="102dp"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="68dp"
    android:text="Next >"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
   />

Body:
I  figured out that when using the custom  button make  sure to change the

<Button.../>

to

<androidx.appcompat.widget.AppCompatButton

It's due to material io buttons can't accept custom buttons as background.


问:
Azure Logic Apps can't programmatically build And / Or Condition using ASP.Net SDK
I'm programmatically building a Condition in a Logic App. If the user selects Or, I use the Or Condition. If the user selects And, I use the And Condition.

I can get Or to work by itself. I can also get And to work by itself.

```<code>public class Expression
        {
            public Or[] or { get; set; }
        }

public class Expression
        {
            public And[] and { get; set; }
        }
</code>```

When I try to use the Expression class below, I get a "Condition has 2 top level properties. Only 1 is allowed." error.

```<code>public class Expression
    {
        public Or[] or { get; set; }
        public And[] and { get; set; }
    }
</code>```

If I set one to null, I get the error. If I set one to an empty array, I get the error.

UPDATE 1

Here is the Logic App code view in Azure.

```<code>"expression": {
                "and":
                 [
                    {
                      "contains": [
                          "@outputs('Compose_3')",
                          "foo"
                     ]
                    },
                    {
                       "contains": [
                           "@outputs('Compose_3')",
                           "bar"
                     ]
                    }
                  ]
                },
</code>```

Does anyone know how to get this to work? Am I missing something simple here? Any help is much appreciated. Thanks in advance!

答:
I finally got this working. When you Serialize the JSON, use "IgnoreNullValues = true". This will ignore the null value this is present when you set the And or Or value in your Expression object. ReplaceFirst simply adds a "$" to the word "schema" on the first occurrence.</p>
```<code>var options = new JsonSerializerOptions { WriteIndented = true, IgnoreNullValues = true};
            string jsonString = ReplaceFirst(JsonSerializer.Serialize(myApp, options), "schema", "$schema").Replace("_else", "else").Replace("_foreach", "foreach");

string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);
            if (pos < 0)
            {
                return text;
            }
            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
</code>```

Body:
I'm programmatically building a Condition in a Logic App. If the user selects Or, I use the Or Condition. If the user selects And, I use the And Condition.

I can get Or to work by itself. I can also get And to work by itself.

public class Expression
        {
            public Or[] or { get; set; }
        }

public class Expression
        {
            public And[] and { get; set; }
        }

When I try to use the Expression class below, I get a "Condition has 2 top level properties. Only 1 is allowed." error.

public class Expression
    {
        public Or[] or { get; set; }
        public And[] and { get; set; }
    }

If I set one to null, I get the error. If I set one to an empty array, I get the error.

UPDATE 1

Here is the Logic App code view in Azure.

"expression": {
                "and":
                 [
                    {
                      "contains": [
                          "@outputs('Compose_3')",
                          "foo"
                     ]
                    },
                    {
                       "contains": [
                           "@outputs('Compose_3')",
                           "bar"
                     ]
                    }
                  ]
                },

Does anyone know how to get this to work? Am I missing something simple here? Any help is much appreciated. Thanks in advance!

Body:
I finally got this working. When you Serialize the JSON, use "IgnoreNullValues = true". This will ignore the null value this is present when you set the And or Or value in your Expression object. ReplaceFirst simply adds a "$" to the word "schema" on the first occurrence.

var options = new JsonSerializerOptions { WriteIndented = true, IgnoreNullValues = true};
            string jsonString = ReplaceFirst(JsonSerializer.Serialize(myApp, options), "schema", "$schema").Replace("_else", "else").Replace("_foreach", "foreach");

string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);
            if (pos < 0)
            {
                return text;
            }
            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }


问:
Globalization and Localization: When? How?
I'm researching a little about different ways to do Localization and Globalization in .NET as I was asked in my job to do it. However, I've been reading lot of posts about those topics, and I don't think that doing Globalization nor Localization is the best option for us:

Apparently bosses' plans are to duplicate the app in many servers as they need with different domains (.com, .es, .co, etc.) in order to use it in many different countries. As I see it, and please correct me if I'm wrong, doing that would imply that there's no need of Globalization nor Localization, because instead of having one application running and accepting different localized resources you will have many different apps running in different servers with different and exclusive resources...

Does it make any sense to implement globalization and localization if they're proceeding this way? Please help me clarify my thoughts.

Thanks in advance,

答:
I would definitely implement localization and stick to 1 code base as much as possible.

You can deploy the same project to different servers and set a fixed culturecode if you have to or let it depend on the user's browser.

Just splitting your code because you want different languages without a localization mechanism is a bad idea. It will be horrible to maintain.

I have 1 project running for different clients on different domains with slightly different functionality and different languages and i am still sticking to 1 code base for all of them.


问:
Ensure graceful scale down with PCF Autoscaler
I have a PCF spring boot application, which handles some long running batches, and planning to use PCF AutoScaler for automatic scaling.

How to ensure graceful scale-down if app takes approx 15-20 minutes to drain already running jobs? Is there any mechanism to control scale down time so that app instance gets enough time before it's shut down?

答:
The amount of time an application has to gracefully shutdown is set by the platform, not by PCF Autoscaler or your application. With PCF it is going to default to 10 seconds.

By default, apps must finish their in-flight jobs within ten seconds of receiving the SIGTERM before TAS for VMs terminates the app with a SIGKILL.

https://docs.pivotal.io/application-service/2-12/devguide/deploy-apps/app-lifecycle.html#shutdown

As noted at that link, you can change that value but it's platform-wide.

To modify the timeout period on the TAS for VMs tile or IST tile, go to the Advanced Settings tab and edit the “app graceful shutdown period” property.

There are downsides to changing it, like longer evacuation times when updating Diego Cells. You're essentially giving all of your applications that much time to run before the platform can stop the application, which ties up platform resources for longer periods of time.

I would not recommend increasing the value platform-wide to accommodate your need of 15-20 minutes.

My suggestion would be to adjust your batch jobs such that they can be paused or stopped and resumed later. When the SIGTERM is sent, you can then tell the jobs to pause or stop, which can hopefully be done in less than 10 seconds. When your application restarts, the paused or stopped job can be resumed.


问:
Automatically download emails from Outlook with SAS or Outlook rule
I am trying to create a program to automatically download the attached files that are sent to us from a certain email and then transform the delimiter with SAS, of those csv that are attached to us and pass those csv through a flow that I have already created.

I have managed to create a program that treats the csv as I want and the delimiter that I want, the problem is that when it comes to automating the download of files from Outlook it does not work.

What I have done is create a rule with the following VB code that I found on the internet:

```<code>Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\Users\ES010246\Desktop"
For Each oAttachment In MItem.Attachments
oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
Next
End Sub
</code>```

I have changed the path to my personal path where i want the files are downloaded.

website: https://es.extendoffice.com/documents/outlook/3747-outlook

The problem is that this code does not work for me, it does absolutely nothing for me and no matter how much I search the internet, only this code appears.

Is there any other way to do with SAS what I want? What is it to automatically download 8 csv files sent to me by Outlook, or has someone experienced the same thing as me with VBA?

I have followed all the steps about 7 times so I think the error is not in copying the code or selecting certain options wrong, in fact I had copied and pasted the code and later I modified the path where I wanted those to be saved. files but it doesn't work, does anyone know why?

I will be tremendously grateful, thank you very much for everything!

答:
First of all, you need to make sure the file name and path doesn't include forbidden symbols.

The VBA macro used for a rule in Outlook is absolutely valid except that a mail item may contain the attached files with the same name, so a file saved to the disk may be overwritten (saved with the same name). That's why I'd suggest generating a file name with your own unique IDs making sure that DisplayName property is not empty and has a valid name what can be used for file names (exclude forbidden symbols).

Also you may consider handling the NewMailEx event of the Application class which is fired when a new message arrives in the Inbox and before client rule processing occurs. Use the Entry ID returned in the EntryIDCollection string to call the NameSpace.GetItemFromID method and process the item. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem.

The Items.ItemAdd event can be helpful when items are moved to a folder (from Inbox).  This event does not run when a large number of items are added to the folder at once.

Body:
I am trying to create a program to automatically download the attached files that are sent to us from a certain email and then transform the delimiter with SAS, of those csv that are attached to us and pass those csv through a flow that I have already created.

I have managed to create a program that treats the csv as I want and the delimiter that I want, the problem is that when it comes to automating the download of files from Outlook it does not work.

What I have done is create a rule with the following VB code that I found on the internet:

Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\Users\ES010246\Desktop"
For Each oAttachment In MItem.Attachments
oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
Next
End Sub

I have changed the path to my personal path where i want the files are downloaded.

website: https://es.extendoffice.com/documents/outlook/3747-outlook

The problem is that this code does not work for me, it does absolutely nothing for me and no matter how much I search the internet, only this code appears.

Is there any other way to do with SAS what I want? What is it to automatically download 8 csv files sent to me by Outlook, or has someone experienced the same thing as me with VBA?

I have followed all the steps about 7 times so I think the error is not in copying the code or selecting certain options wrong, in fact I had copied and pasted the code and later I modified the path where I wanted those to be saved. files but it doesn't work, does anyone know why?

I will be tremendously grateful, thank you very much for everything!


问:
How to show number counts on terminal in linux
Please how can I count the list of numbers in a file

```<code>awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'
</code>```

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

```<code>1-20,
2-22,
3-23,
4-24,
etc
</code>```

I know I can use wc but I don't know how to infuse it into the command above

答:
```<code>awk '
    { for(i=1;i<=NF;i++) if (0<=$i && $i<=25) cnts[$i]++ }
    END { for (n in cnts) print n, cnts[n] }
' file
</code>```

Body:
Please how can I count the list of numbers in a file

awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

1-20,
2-22,
3-23,
4-24,
etc

I know I can use wc but I don't know how to infuse it into the command above


问:
nodejs "npm ERR! code SELF_SIGNED_CERT_IN_CHAIN"
I'm new to nodejs and npm. I'm trying to install log4js and this is the command for the install:

```<code>npm install log4js
</code>```

I'm running this from Windows Command Line and I after a while of a marker spinning I get the following error:

```<code>npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "log4js"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code SELF_SIGNED_CERT_IN_CHAIN

npm ERR! self signed certificate in certificate chain
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <http://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\srv\npm-debug.log
</code>```

I tried doing npm config set ca="" like suggested here: http://blog.npmjs.org/post/78085451721/npms-self-signed-certificate-is-no-more but I'm still getting this error.

How can I solve this and install NPMs ?

答: Our corporate environment inflicted this on us via some company cert chicanery, and this bit the Windows devs in both npm and git operations. For npm, the instructions provided previously by gregsonian (building a cert and pointing npm config to use it) still work well. (Win-10 for reference.) I prefer otherwise keeping SSL enabled.</p>

Body:
I'm new to nodejs and npm. I'm trying to install log4js and this is the command for the install:

npm install log4js

I'm running this from Windows Command Line and I after a while of a marker spinning I get the following error:

npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "log4js"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code SELF_SIGNED_CERT_IN_CHAIN

npm ERR! self signed certificate in certificate chain
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <http://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\srv\npm-debug.log

I tried doing npm config set ca="" like suggested here: http://blog.npmjs.org/post/78085451721/npms-self-signed-certificate-is-no-more but I'm still getting this error.

How can I solve this and install NPMs ?


问:
How to override a base class' DB connection string?
I have a base class (written using C#.net) which uses datasets to pull data from DB and the connection string is in App.config file. So after writing the base class it has been compiled into dll.

And to use this base class for different project I have to override the DB connection string, so first is it possible to do and if possible, can anyone give me an example for it?

答:
Make the connection string a protected virtual property in your base class</p>

```<code>class Base {
    protected virtual string ConnectionString { get { ... } } // Get from config.
}

class Sub {
    protected override string ConnectionString { get { ... } } // return the new value.
}
</code>```

Body:
Make the connection string a protected virtual property in your base class

class Base {
    protected virtual string ConnectionString { get { ... } } // Get from config.
}

class Sub {
    protected override string ConnectionString { get { ... } } // return the new value.
}


问:
CSS file is not read properly using actix-web and maud
CSS is not working via link rel attributes of maud with actix-web. Where I've made mistake(s)?

I think that position where I wrote link rel attributes is correct.

main.rs

use actix_files as fs;
use actix_web::{get, App, HttpServer, Result as AwResult};
use maud::{html, Markup};

#[get("/")]
async fn index() -> AwResult<Markup> {
    Ok(html! {
        head{
            link rel="stylesheet" href="/static/style.css"{};
        }
       title{"Help me"}

       p {"Blue text should be shown."}

    })
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(fs::Files::new("/static", ".").show_files_listing())
            .service(index)
    })
    .bind("0.0.0.0:80")?
    .run()
    .await?;
    Ok(())
}
```
<p><strong>style.css</strong></p>
<pre class="lang-css prettyprint-override"><code>p {
    color: blue;
    font-size: 50px;
}
</code>```

答:
Looking at the documentation of actix_files::Files:

The first argument (mount_path) is the root URL at which the static files are served.

The second argument (serve_from) is the location on disk at which files are loaded.

You are using /static as first argument, so your files will be under http://0.0.0.0:80/static, all right.

But as second argument you set . that is the root of the project. This means that you are publishing the whole source of your project! For example, at http://0.0.0.0:80/static/src/main.rs (http://0.0.0.0:80/static/ is the mount point, ./src/main.rs is the local file) you will download the source of your binary, and you do not want that.

To fix your problem write instead:

```<code>fs::Files::new("/static", "./static")
</code>```

The ./ in the second argument is optional, of course, but I like it because it reminds you that it is relative to the current working directory.

Body:
CSS is not working via link rel attributes of maud with actix-web. Where I've made mistake(s)?

I think that position where I wrote link rel attributes is correct.

main.rs

use actix_files as fs;
use actix_web::{get, App, HttpServer, Result as AwResult};
use maud::{html, Markup};

#[get("/")]
async fn index() -> AwResult<Markup> {
    Ok(html! {
        head{
            link rel="stylesheet" href="/static/style.css"{};
        }
       title{"Help me"}

       p {"Blue text should be shown."}

    })
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(fs::Files::new("/static", ".").show_files_listing())
            .service(index)
    })
    .bind("0.0.0.0:80")?
    .run()
    .await?;
    Ok(())
}

style.css

p {
    color: blue;
    font-size: 50px;
}

Body:
Looking at the documentation of actix_files::Files:

The first argument (mount_path) is the root URL at which the static files are served.

The second argument (serve_from) is the location on disk at which files are loaded.

You are using /static as first argument, so your files will be under http://0.0.0.0:80/static, all right.

But as second argument you set . that is the root of the project. This means that you are publishing the whole source of your project! For example, at http://0.0.0.0:80/static/src/main.rs (http://0.0.0.0:80/static/ is the mount point, ./src/main.rs is the local file) you will download the source of your binary, and you do not want that.

To fix your problem write instead:

fs::Files::new("/static", "./static")

The ./ in the second argument is optional, of course, but I like it because it reminds you that it is relative to the current working directory.


问:
Summarizing JSON Object Into Another JSON Object
I am relatively new at using JSON with JavaScript and am struggling with how to summarize data from one JSON object into another JSON object.

The original JSON looks like this:

```<code>{
  "general": {
    "version": "v0.4.0",
    "timeStamp": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)",
    "status": "Complete",
    "outputRollId": "22023_StdJobsAcme",
    "outputRollWidth": "2800mm",
    "productionPlan": "22023_StdJobsAcme",
    "workflowConfiguration": {
      "configName": "XX123",
      "press": {
        "name": "XX123"
      }
    }
  },
  "intent": [
    {
      "piId": "62465290",
      "piSequence": "1",
      "jobType": "Standard",
      "jobId": "4287773301",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878382_Chardonnay_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773301",
      "jobName": "1878382_Chardonnay_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465291",
      "piSequence": "2",
      "jobType": "Standard",
      "jobId": "4287773401",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878376_CabFranc_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773401",
      "jobName": "1878376_CabFranc_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465302",
      "piSequence": "3",
      "jobType": "Standard",
      "jobId": "4287773501",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878377_Mixed_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773501",
      "jobName": "1878377_Mixed_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465303",
      "piSequence": "4",
      "jobType": "Standard",
      "jobId": "4287773601",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878382_Chardonnay_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773601",
      "jobName": "1878382_Chardonnay_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465304",
      "piSequence": "5",
      "jobType": "Standard",
      "jobId": "4287773701",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878376_CabFranc_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773701",
      "jobName": "1878376_CabFranc_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465305",
      "piSequence": "6",
      "jobType": "Standard",
      "jobId": "4287773801",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878377_Mixed_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773801",
      "jobName": "1878377_Mixed_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465306",
      "piSequence": "7",
      "jobType": "Standard",
      "jobId": "4287773901",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773901",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    },
    {
      "piId": "62465307",
      "piSequence": "8",
      "jobType": "Standard",
      "jobId": "4287774001",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287774001",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    },
    {
      "piId": "62465308",
      "piSequence": "9",
      "jobType": "Standard",
      "jobId": "4287774101",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287774101",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    }
  ],
  "actuals": [
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "diagnostic",
      "jobId": "spit-page-lead-in_0k17p",
      "jobLength": "41 inches"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773301",
      "jobLength": "772 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773301",
      "jobLength": "3360 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773501",
      "jobLength": "636 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773601",
      "jobLength": "636 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773701",
      "jobLength": "3360 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773801",
      "jobLength": "772 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773901",
      "jobLength": "1012 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287774001",
      "jobLength": "4404 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287774101",
      "jobLength": "833 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    }
  ]
}
</code>```

The summary JSON should look like this:

```<code>{
  "rollId": "D34100001",
  "rollWidth": 33,
  "totalLength": 3750,
  "totalQuantity": "120500",
  "detail": [
    {
      "jobId": "PRP4287773301",
      "jobName": "1878382_Chardonnay_5up.AotF",
      "jobLength": 1000
    },
    {
      "jobId": "PRP4287773501",
      "jobName": "Acme / CZ372L21",
      "jobLength": 636
    },
    {
      "jobId": "PRP4287773601",
      "jobName": "Alani / SPTC00010",
      "jobLength": 636
    }
  ]
}
</code>```

I am able to process rollId, rollWidth, totalLength, and totalQuantity easy enough, but I'm struggling how to handle the detail array summarization. The array should be comprised of intent.jobId and intent.jobName and the total of actuals.jobLength for each jobId.

My code currently:

```<code>const router = express.Router();
const fs = require('fs');
const RollResults = require('../models/rollResultsModel');

// Process roll results
router.post('/', async (req, res) => {
    const rawRollResults = req.body;
    const finalRollResults = {};
    var totalQty = 0;
    var totalLength = 0;
    try {
        finalRollResults.rollId = rawRollResults.general.outputRollId;
        finalRollResults.rollWidth = Math.round(Number(rawRollResults.general.outputRollWidth.slice(0, -2)) / 25.4);
        for (var i = 0; i < rawRollResults.actuals.length; i++)
        {
            if (rawRollResults.actuals[i].jobType === "Standard")
            {
                totalLength += Number(rawRollResults.actuals[i].jobLength.slice(0, -7));
                totalQty += Number(rawRollResults.actuals[i].sheetsPrintedGood);
            }
        }
        finalRollResults.totalLength = Math.round(totalLength / 12);
        finalRollResults.totalQuantity = totalQty;
        res.json(finalRollResults);
    }
    catch (err) {
        res.json({ message: err });
    }
});

module.exports = router;
</code>```

I would assume that I need to accomplish this in two passes through the original JSON, the first pass adding detail.jobId and detail.jobName for each original JSON intent, and then cycle through the original JSON actuals and update each new JSON detail accordingly, but I am unaware of how to accomplish this.

答:
Part of your problem is that you have a function that is trying to do way too much. To many different things. Refactor it into smaller functions that each do one simple thing. It makes it easier to test, and easier to debug.

But at its heart, the problem doesn't seem like it ought to be anything more complicated than a simple mapper.

You first need a way to convert to inches, something like this:

```<code>function convertToInches( measurement ) {
    const [ n = 0, units = 'mm' ] = /^(\d+)\s*([a-zA-Z]+)$/.exec(measurement) ?? [];
    let f;
    switch (units) {
        case 'mm'     : f = 25.4      ; break ;
        case 'cm'     : f = 2.54      ; break ;
        case 'in'     : f = 1.0       ; break ;
        case 'ins'    : f = 1.0       ; break ;
        case 'inches' : f = 1.0       ; break;
        default       : f = undefined ; break ;
    }
    return f ? Math.round( n / f ) : undefined ;
}
</code>```

And you need a way to correlate the intents and the actuals by jobId, something like this:

```<code>function getJobs( results ) {
  const jobsById = {};

  for ( const intent of results.intent ) {
    if (intent.jobType !== 'Standard' ) continue;

    jobsById[intent.jobId] = { intent };

  }

  for ( const actual of results.actual ) {
    if (actual.jobType !== 'Standard' ) continue;

    jobsById[actual.jobId] = jobsById[actual.jobId] ?? {};
    jobsById[actual.jobId].actual = actual;

  }

  // ---------------------------------------------------------------
  // now that we have an 'intent' and an 'actual' matched by job ID,
  // it's easy to create the job detail that we'll need.
  //
  // Note that 'qty' will get discarded when we no longer need it
  //
  // ---------------------------------------------------------------
  const jobs = Object.values( jobsById ).map( job => ({
    ...job,
    detail: {
      jobId     : job.actual.jobId,
      jobName   : job.intent.jobName,
      jobLength : ConvertToInches( job.actual.jobLength ),
      qty       : Number( job.actual.sheetsPrintedGood )
    }
  }) );

  return jobs;
}
</code>```

And once you have that, it's just a simple mapper to product what you want:

```<code>function mapRollResults( results ) {
    const jobs = getJobs( results );
    return {
        rollId        : results.general.outputRollId,
        rollWidth     : convertToInches( results.general.outputRollWidth ),
        totalLength   : jobs.reduce( (sum,j) => sum += j.detail.jobLength , 0 ),
        totalQuantity : jobs.reduce( (sum,j) => sum += j.detail.qty       , 0 ),
        details       : jobs.map( j => j.detail )
                            .map( d => {
                                delete d.qty;
                                return d;
                            }),
    };
}
</code>```

Body:
I am relatively new at using JSON with JavaScript and am struggling with how to summarize data from one JSON object into another JSON object.

The original JSON looks like this:

{
  "general": {
    "version": "v0.4.0",
    "timeStamp": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)",
    "status": "Complete",
    "outputRollId": "22023_StdJobsAcme",
    "outputRollWidth": "2800mm",
    "productionPlan": "22023_StdJobsAcme",
    "workflowConfiguration": {
      "configName": "XX123",
      "press": {
        "name": "XX123"
      }
    }
  },
  "intent": [
    {
      "piId": "62465290",
      "piSequence": "1",
      "jobType": "Standard",
      "jobId": "4287773301",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878382_Chardonnay_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773301",
      "jobName": "1878382_Chardonnay_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465291",
      "piSequence": "2",
      "jobType": "Standard",
      "jobId": "4287773401",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878376_CabFranc_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773401",
      "jobName": "1878376_CabFranc_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465302",
      "piSequence": "3",
      "jobType": "Standard",
      "jobId": "4287773501",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878377_Mixed_5up.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773501",
      "jobName": "1878377_Mixed_5up.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465303",
      "piSequence": "4",
      "jobType": "Standard",
      "jobId": "4287773601",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878382_Chardonnay_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773601",
      "jobName": "1878382_Chardonnay_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465304",
      "piSequence": "5",
      "jobType": "Standard",
      "jobId": "4287773701",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878376_CabFranc_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773701",
      "jobName": "1878376_CabFranc_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465305",
      "piSequence": "6",
      "jobType": "Standard",
      "jobId": "4287773801",
      "jobSpec": {
        "name": "600fpm ILO 4C120P HEAD",
        "leadEdge": "HEAD",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878377_Mixed_5up.R.AotF.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773801",
      "jobName": "1878377_Mixed_5up.R.AotF",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "174"
    },
    {
      "piId": "62465306",
      "piSequence": "7",
      "jobType": "Standard",
      "jobId": "4287773901",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287773901",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    },
    {
      "piId": "62465307",
      "piSequence": "8",
      "jobType": "Standard",
      "jobId": "4287774001",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287774001",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    },
    {
      "piId": "62465308",
      "piSequence": "9",
      "jobType": "Standard",
      "jobId": "4287774101",
      "jobSpec": {
        "name": "600fpm ILO 4C120P LEFT",
        "leadEdge": "LEFT",
        "scaleFactor": "100.6",
        "colorSetup": "inkLimitsOnly_cmyk_120ng_v5_3",
        "qualityMode": "standard",
        "pressProfile": "42inch NORPAC zero gap",
        "paperProfile": "42inch NORPAC"
      },
      "jobPrintFile": "1878668_ChocolateChipsDC.5up.AotF_1-174.pdf",
      "jobProductId": "",
      "jobDesignId": "",
      "jobSourceItemId": "214287774101",
      "jobName": "1878668_ChocolateChipsDC.5up.AotF_1-174",
      "jobPaperName": "",
      "jobPaperWidth": "2800mm",
      "jobLength": "1"
    }
  ],
  "actuals": [
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "diagnostic",
      "jobId": "spit-page-lead-in_0k17p",
      "jobLength": "41 inches"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773301",
      "jobLength": "772 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773301",
      "jobLength": "3360 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773501",
      "jobLength": "636 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773601",
      "jobLength": "636 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773701",
      "jobLength": "3360 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773801",
      "jobLength": "772 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287773901",
      "jobLength": "1012 inches",
      "sheetsPrintedGood": "17",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287774001",
      "jobLength": "4404 inches",
      "sheetsPrintedGood": "74",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    },
    {
      "outputRollId": "22023_StdJobsAcme",
      "jobType": "Standard",
      "jobId": "PRP4287774101",
      "jobLength": "833 inches",
      "sheetsPrintedGood": "14",
      "sheetsPrintedBad": "0",
      "jobEndPrint": "Wed Feb 02 2022 10:47:06 GMT-0800 (Pacific Standard Time)"
    }
  ]
}

The summary JSON should look like this:

{
  "rollId": "D34100001",
  "rollWidth": 33,
  "totalLength": 3750,
  "totalQuantity": "120500",
  "detail": [
    {
      "jobId": "PRP4287773301",
      "jobName": "1878382_Chardonnay_5up.AotF",
      "jobLength": 1000
    },
    {
      "jobId": "PRP4287773501",
      "jobName": "Acme / CZ372L21",
      "jobLength": 636
    },
    {
      "jobId": "PRP4287773601",
      "jobName": "Alani / SPTC00010",
      "jobLength": 636
    }
  ]
}

I am able to process rollId, rollWidth, totalLength, and totalQuantity easy enough, but I'm struggling how to handle the detail array summarization. The array should be comprised of intent.jobId and intent.jobName and the total of actuals.jobLength for each jobId.

My code currently:

const router = express.Router();
const fs = require('fs');
const RollResults = require('../models/rollResultsModel');

// Process roll results
router.post('/', async (req, res) => {
    const rawRollResults = req.body;
    const finalRollResults = {};
    var totalQty = 0;
    var totalLength = 0;
    try {
        finalRollResults.rollId = rawRollResults.general.outputRollId;
        finalRollResults.rollWidth = Math.round(Number(rawRollResults.general.outputRollWidth.slice(0, -2)) / 25.4);
        for (var i = 0; i < rawRollResults.actuals.length; i++)
        {
            if (rawRollResults.actuals[i].jobType === "Standard")
            {
                totalLength += Number(rawRollResults.actuals[i].jobLength.slice(0, -7));
                totalQty += Number(rawRollResults.actuals[i].sheetsPrintedGood);
            }
        }
        finalRollResults.totalLength = Math.round(totalLength / 12);
        finalRollResults.totalQuantity = totalQty;
        res.json(finalRollResults);
    }
    catch (err) {
        res.json({ message: err });
    }
});

module.exports = router;

I would assume that I need to accomplish this in two passes through the original JSON, the first pass adding detail.jobId and detail.jobName for each original JSON intent, and then cycle through the original JSON actuals and update each new JSON detail accordingly, but I am unaware of how to accomplish this.

Body:
Part of your problem is that you have a function that is trying to do way too much. To many different things. Refactor it into smaller functions that each do one simple thing. It makes it easier to test, and easier to debug.

But at its heart, the problem doesn't seem like it ought to be anything more complicated than a simple mapper.

You first need a way to convert to inches, something like this:

function convertToInches( measurement ) {
    const [ n = 0, units = 'mm' ] = /^(\d+)\s*([a-zA-Z]+)$/.exec(measurement) ?? [];
    let f;
    switch (units) {
        case 'mm'     : f = 25.4      ; break ;
        case 'cm'     : f = 2.54      ; break ;
        case 'in'     : f = 1.0       ; break ;
        case 'ins'    : f = 1.0       ; break ;
        case 'inches' : f = 1.0       ; break;
        default       : f = undefined ; break ;
    }
    return f ? Math.round( n / f ) : undefined ;
}

And you need a way to correlate the intents and the actuals by jobId, something like this:

function getJobs( results ) {
  const jobsById = {};

  for ( const intent of results.intent ) {
    if (intent.jobType !== 'Standard' ) continue;

    jobsById[intent.jobId] = { intent };

  }

  for ( const actual of results.actual ) {
    if (actual.jobType !== 'Standard' ) continue;

    jobsById[actual.jobId] = jobsById[actual.jobId] ?? {};
    jobsById[actual.jobId].actual = actual;

  }

  // ---------------------------------------------------------------
  // now that we have an 'intent' and an 'actual' matched by job ID,
  // it's easy to create the job detail that we'll need.
  //
  // Note that 'qty' will get discarded when we no longer need it
  //
  // ---------------------------------------------------------------
  const jobs = Object.values( jobsById ).map( job => ({
    ...job,
    detail: {
      jobId     : job.actual.jobId,
      jobName   : job.intent.jobName,
      jobLength : ConvertToInches( job.actual.jobLength ),
      qty       : Number( job.actual.sheetsPrintedGood )
    }
  }) );

  return jobs;
}

And once you have that, it's just a simple mapper to product what you want:

function mapRollResults( results ) {
    const jobs = getJobs( results );
    return {
        rollId        : results.general.outputRollId,
        rollWidth     : convertToInches( results.general.outputRollWidth ),
        totalLength   : jobs.reduce( (sum,j) => sum += j.detail.jobLength , 0 ),
        totalQuantity : jobs.reduce( (sum,j) => sum += j.detail.qty       , 0 ),
        details       : jobs.map( j => j.detail )
                            .map( d => {
                                delete d.qty;
                                return d;
                            }),
    };
}


问:
Miscalculation of Lagrange interpolation formula for higher degree
I am approximating Runge’s function using Lagrange’s interpolation formula for 50 interpolation points. I have written the following program to do this, but I am getting the wrong value for x= -0.992008. That wrong value is  4817543.091313, but it should be 5197172.55933613. I have got this value from the following link: Link The code used are as follows:</p>
```<code>#include <stdio.h>
#include <math.h>

double
runge(double x)
{
    return (1 / (1 + (25 * x * x)));
}

double
ab(double x)
{
    if (x < 0)
        return -1 * x;
    return x;
}

double
lag_func(double x, double *y_i, double *x_i, int n)
{
    double ex = 0.0;

    for (int i = 0; i <= n; i++) {
        double numer = 1.0,
            denom = 1.0,
            prod = 1.0;

        for (int j = 0; j <= n; j++) {
            if (i != j) {
                numer = (x - x_i[j]);
                denom = (x_i[i] - x_i[j]);
                prod *= numer / denom;
            }
        }
        ex += (prod) * y_i[i];
    }
    return ex;
}

int
main()
{
    int n;

    scanf("%d", &n);
    double y_i[n + 1],
     x_i[n + 1];

    for (int i = 0; i < n + 1; i++) {
        x_i[i] = ((2 * (double) i) / (double) n) - 1;
        y_i[i] = runge(x_i[i]);
    }

    printf("%lf\n", lag_func(-0.992008, y_i, x_i, n));
    return 0;
}
</code>```

答:
The web site is rounding its Runge coefficients to six digits. Given the magnitudes of the terms involved, up to 3.9978•1011, this introduces multiple errors up to around 2•105.

This can be seen by inserting y_i[i] = round(y_i[i] * 1e6) / 1e6; after y_i[i] = runge(x_i[i]);. Then the output of the program is 5197172.558199, matching the web site’s inaccurate result.

The web site is wrong; the result of the code in the question is better.

Body:
I am approximating Runge’s function using Lagrange’s interpolation formula for 50 interpolation points. I have written the following program to do this, but I am getting the wrong value for x= -0.992008. That wrong value is  4817543.091313, but it should be 5197172.55933613. I have got this value from the following link: <a href="https://atozmath.com/CONM/NumeInterPola.aspx?q=LI&q1=1%60-1.000000%2C-0.960000%2C-0.920000%2C-0.880000%2C-0.840000%2C-0.800000%2C-0.760000%2C-0.720000%2C-0.680000%2C-0.640000%2C-0.600000%2C-0.560000%2C-0.520000%2C-0.480000%2C-0.440000%2C-0.400000%2C-0.360000%2C-0.320000%2C-0.280000%2C-0.240000%2C-0.200000%2C-0.160000%2C-0.120000%2C-0.080000%2C-0.040000%2C0.000000%2C0.040000%2C0.080000%2C0.120000%2C0.160000%2C0.200000%2C0.240000%2C0.280000%2C0.320000%2C0.360000%2C0.400000%2C0.440000%2C0.480000%2C0.520000%2C0.560000%2C0.600000%2C0.640000%2C0.680000%2C0.720000%2C0.760000%2C0.800000%2C0.840000%2C0.880000%2C0.920000%2C0.960000%2C1.000000%600.038462%2C0.041597%2C0.045126%2C0.049116%2C0.053648%2C0.058824%2C0.064767%2C0.071633%2C0.079618%2C0.088968%2C0.100000%2C0.113122%2C0.128866%2C0.147929%2C0.171233%2C0.200000%2C0.235849%2C0.280899%2C0.337838%2C0.409836%2C0.500000%2C0.609756%2C0.735294%2C0.862069%2C0.961538%2C1.000000%2C0.961538%2C0.862069%2C0.735294%2C0.609756%2C0.500000%2C0.409836%2C0.337838%2C0.280899%2C0.235849%2C0.200000%2C0.171233%2C0.147929%2C0.128866%2C0.113122%2C0.100000%2C0.088968%2C0.079618%2C0.071633%2C0.064767%2C0.058824%2C0.053648%2C0.049116%2C0.045126%2C0.041597%2C0.038462%23%60-0.992008%60LI%601&dp=12&do=1#PrevPart" rel="nofollow noreferrer">Link The code used are as follows:

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

double
runge(double x)
{
    return (1 / (1 + (25 * x * x)));
}

double
ab(double x)
{
    if (x < 0)
        return -1 * x;
    return x;
}

double
lag_func(double x, double *y_i, double *x_i, int n)
{
    double ex = 0.0;

    for (int i = 0; i <= n; i++) {
        double numer = 1.0,
            denom = 1.0,
            prod = 1.0;

        for (int j = 0; j <= n; j++) {
            if (i != j) {
                numer = (x - x_i[j]);
                denom = (x_i[i] - x_i[j]);
                prod *= numer / denom;
            }
        }
        ex += (prod) * y_i[i];
    }
    return ex;
}

int
main()
{
    int n;

    scanf("%d", &n);
    double y_i[n + 1],
     x_i[n + 1];

    for (int i = 0; i < n + 1; i++) {
        x_i[i] = ((2 * (double) i) / (double) n) - 1;
        y_i[i] = runge(x_i[i]);
    }

    printf("%lf\n", lag_func(-0.992008, y_i, x_i, n));
    return 0;
}


问:
how can i extract a 6 digit alphanumeric part of txt from a string (i want them kept together not pulled apart)
How can I extract a 6 digit alphanumeric part of txt from a string (I want them kept together not pulled apart).

ie I want to extract 3B3520 from 'Media Hold Vessel 3B3520, Vessel drawing'

Can extract the text or numbers alone but not both.

答:
To extract a six character alphanumeric string where at least 2 of the characters are digits, you can add a custom column with the formula:

```<code>=List.Select(
    Text.Split(
        Text.Remove([Column1],{",",".","!","?"}),
    " "),
    each (Text.Length(_)=6) and
        (Text.Length(Text.Remove(_,{"0".."9"})) <=4)){0}
</code>```

Adjust the number of needed digits by adjusting the Text.Length(...)<=4) parameter.

M Code

```<code>let
    Source = Excel.CurrentWorkbook(){[Name="Table6"]}[Content],
    #"Added Custom" = Table.AddColumn(Source, "Custom", each
    List.Select(
        Text.Split(
            Text.Remove([Column1],{",",".","!","?"}),
        " "),
        each (Text.Length(_)=6) and
            (Text.Length(Text.Remove(_,{"0".."9"})) <=4)){0}, type text)

in
    #"Added Custom"
</code>```

Body:
To extract a six character alphanumeric string where at least 2 of the characters are digits, you can add a custom column with the formula:

=List.Select(
    Text.Split(
        Text.Remove([Column1],{",",".","!","?"}),
    " "),
    each (Text.Length(_)=6) and
        (Text.Length(Text.Remove(_,{"0".."9"})) <=4)){0}

Adjust the number of needed digits by adjusting the Text.Length(...)<=4) parameter.

M Code

let
    Source = Excel.CurrentWorkbook(){[Name="Table6"]}[Content],
    #"Added Custom" = Table.AddColumn(Source, "Custom", each
    List.Select(
        Text.Split(
            Text.Remove([Column1],{",",".","!","?"}),
        " "),
        each (Text.Length(_)=6) and
            (Text.Length(Text.Remove(_,{"0".."9"})) <=4)){0}, type text)

in
    #"Added Custom"


问:
XSLT value-of returns text only
I'm using XSLT to show a node from XML. This node contains a HTML unordered list like this:

one

two

but <xsl:value-of select="root/node1" disable-output-escaping="yes" /> returns only onetwo

I know i need to use disable-output-escaping="yes" But this does nothing.

I want the output to be the same as in the node, like this:

one

two

答: I think you want to use <xsl:copy-of> instead.

Title: XSLT value-of returns text only


问:
Latex: \tableofcontent start with an arbitrary section
Usually when use \tableofcontent in Latex, it starts with Section 1, e.g.,

```<code>Contents

1 Introduction ..... 1
2 Something ........ 2
3 Conclusion ....... 4
4 blablabla ........ 6
</code>```

Is there anything to create a table of content like this:

```<code>Contents

3 Conclusion ....... 4
4 blablabla ........ 6
</code>```

That is, in this example, skipping sections 1 and 2 and only list sections 3 and 4?

LaTeX example: I want to insert the table of contents after Section 3 and before Section S-1:

```<code>\documentclass[pdftex, noinfoline]{imsart}

\begin{document}

\section{sec1}

\section{sec2}

\section{sec3}

\tableofcontents

\section{secS-1}

\section{secS-2}

</code>```

答:
You could use the titletoc package:

```<code>\documentclass[pdftex, noinfoline]{imsart}

\usepackage{titletoc}

\begin{document}

\section{sec1}

\section{sec2}

\section{sec3}

\section*{Table of Contents}
\startcontents
\printcontents{ }{1}{}

\section{secS-1}

\section{secS-2}

\end{document}
</code>```

Body:
Usually when use \tableofcontent in Latex, it starts with Section 1, e.g.,

Contents

1 Introduction ..... 1
2 Something ........ 2
3 Conclusion ....... 4
4 blablabla ........ 6

Is there anything to create a table of content like this:

Contents

3 Conclusion ....... 4
4 blablabla ........ 6

That is, in this example, skipping sections 1 and 2 and only list sections 3 and 4?

LaTeX example: I want to insert the table of contents after Section 3 and before Section S-1:

\documentclass[pdftex, noinfoline]{imsart}

\begin{document}

\section{sec1}

\section{sec2}

\section{sec3}

\tableofcontents

\section{secS-1}

\section{secS-2}

Body:
You could use the titletoc package:

\documentclass[pdftex, noinfoline]{imsart}

\usepackage{titletoc}

\begin{document}

\section{sec1}

\section{sec2}

\section{sec3}

\section*{Table of Contents}
\startcontents
\printcontents{ }{1}{}

\section{secS-1}

\section{secS-2}

\end{document}


答:
Why you compute each value twice:

You insert P0 only once, but you use it twice. You use P[n-1], which in the first loop is P[-1]. Python lists support negative indexes, index -1 gives you the last element, which is the value P0. In the second loop you use P[0], using the same element again (just using a different index). After that, you don't use the same element twice again, but you've appended the same value twice, so those two equal values will make you append two equal values. Which in turn will make you append two more equal values. Etc.

Body:
I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal:
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001,
1225.0430000000001, 1310.7960100000003, 1310.7960100000003,
1402.5517307000005, 1402.5517307000005, 1500.7303518490005,
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556,
1838.4592124201556, 1967.1513572895667, 1967.1513572895667,
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.


问:
Link to id but navbar in the way
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

```<code>.main-content article .anchor{
    position: absolute;
    top: -106px;
}
</code>```

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

答:
I had this problem as well, I found it easy to just place an anchor tag above where you want to jump to and then add scroll-margin-top to my CSS with a value.

#jumpto {
    scroll-margin-top: (insert value here);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
    <ul>
        <li>Nav Link</li>
    </ul>
</nav>

<section>
    <h2>
        This is where I want to jump to but the stupid navbar is in the way!
    </h2>
</section></code>```

Title: Link to id but navbar in the way

Body:
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

.main-content article .anchor{
    position: absolute;
    top: -106px;
}

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

Body:
I had this problem as well, I found it easy to just place an anchor tag above where you want to jump to and then add scroll-margin-top to my CSS with a value.

#jumpto {
    scroll-margin-top: (insert value here);
}

<nav>
    <ul>
        <li><a href="#jumpto">Nav Link</a></li>
    </ul>
</nav>

<a id="jumpto"></a>
<section>
    <h2>
        This is where I want to jump to but the stupid navbar is in the way!
    </h2>
</section>


问:
How to flush entire row when printing status
I have a code like this:

```<code>import time

print("some previous print", end='\r', flush=True)

for i in range(10):
    print("progress " + str(i), end='\r', flush=True)
    time.sleep(1)
</code>```

The result is something like progress 9ous print - so it just cuts previous print by length.

I could have something like end='          \r' to make length longer, but not ideal and flexible solution. Any ideas?

答:
To solve:

prepend an additional carriage-return (CR or \r) before the output-string

and make sure all previous printed characters are over-written (if necessary by space):

```<code>import time

print("About to start shortly.", end='\r', flush=True)
time.sleep(3)
print(" "*50, end='\r', flush=True) # overwritting a length of 50 with space

for i in range(10):
    print(f"\rprogress {i:2}", end='\r', flush=True)  # prefixed with CR, f-string right-aligned
    time.sleep(1)
</code>```

Note: the status-lines have a constant width of 11 (9+ 2 digits reserved for the number, right-aligned).

Body:
I have a code like this:

import time

print("some previous print", end='\r', flush=True)

for i in range(10):
    print("progress " + str(i), end='\r', flush=True)
    time.sleep(1)

The result is something like progress 9ous print - so it just cuts previous print by length.

I could have something like end='          \r' to make length longer, but not ideal and flexible solution. Any ideas?

Body:
To solve:

prepend an additional carriage-return (CR or \r) before the output-string

and make sure all previous printed characters are over-written (if necessary by space):

import time

print("About to start shortly.", end='\r', flush=True)
time.sleep(3)
print(" "*50, end='\r', flush=True) # overwritting a length of 50 with space

for i in range(10):
    print(f"\rprogress {i:2}", end='\r', flush=True)  # prefixed with CR, f-string right-aligned
    time.sleep(1)

Note: the status-lines have a constant width of 11 (9+ 2 digits reserved for the number, right-aligned).


问:
How do you add a header to an excel csv file using python
So I'm trying to add a header to a csv file dynamically. My current code looks like the following:

```<code>import csv
from datetime import datetime
import pandas as pd

rows = []

with open(r'Test_Timestamp.csv', 'r', newline='') as file:
    with open(r'Test_Timestamp_Result.csv', 'w', newline='') as file2:
        reader = csv.reader(file, delimiter=',')
        for row in reader:
            rows.append(row)
        file_write = csv.writer(file2)
        for val in rows:
            current_date_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
            val.insert(0, current_date_time)
            file_write.writerow(val)

</code>```

Currently how this works is it inserts a new timestamp at column A which is exactly what I want it to do, as I want everything to be pushed as I'll be working with csv files with various different number of columns.
What I'm having trouble with is, how am I able to add a column header? Currently a timestamp is created next to the header. I would want to create a new header named: Execution_Date

I have looked at pandas as a solution but from the documentation I've seen the examples given looks like its a set of column headers already pre-determined. I've tried inserting a column header with df.insert(0, "Execution_Date", current_date_time) but gives me an error when trying to accomplish this.

I know I'm fairly close to doing this but I'm running into errors. Is there a way to do this dynamically so it automatically does this with various different csv files and number of different columns in each csv file, etc.? The current output looks like:

What I want the final result to look like is:

Any help with this would be greatly appreciated! I'm going to continue to see if I can solve this in the meantime, but I'm at a wall with how to proceed.

答:
One way to do this is to utilize to_csv().

Example:

```<code># importing python package
import pandas as pd

# read contents of csv file
file = pd.read_csv("gfg.csv")
print("\nOriginal file:")
print(file)

# adding header
headerList = ['id', 'name', 'profession']

# converting data frame to csv
file.to_csv("gfg2.csv", header=headerList, index=False)

# display modified csv file
file2 = pd.read_csv("gfg2.csv")
print('\nModified file:')enter code here
print(file2)
</code>```

Body:
So I'm trying to add a header to a csv file dynamically. My current code looks like the following:

import csv
from datetime import datetime
import pandas as pd

rows = []

with open(r'Test_Timestamp.csv', 'r', newline='') as file:
    with open(r'Test_Timestamp_Result.csv', 'w', newline='') as file2:
        reader = csv.reader(file, delimiter=',')
        for row in reader:
            rows.append(row)
        file_write = csv.writer(file2)
        for val in rows:
            current_date_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
            val.insert(0, current_date_time)
            file_write.writerow(val)

Currently how this works is it inserts a new timestamp at column A which is exactly what I want it to do, as I want everything to be pushed as I'll be working with csv files with various different number of columns.
What I'm having trouble with is, how am I able to add a column header? Currently a timestamp is created next to the header. I would want to create a new header named: Execution_Date

I have looked at pandas as a solution but from the documentation I've seen the examples given looks like its a set of column headers already pre-determined. I've tried inserting a column header with df.insert(0, "Execution_Date", current_date_time) but gives me an error when trying to accomplish this.

I know I'm fairly close to doing this but I'm running into errors. Is there a way to do this dynamically so it automatically does this with various different csv files and number of different columns in each csv file, etc.? The current output looks like:

What I want the final result to look like is:

Any help with this would be greatly appreciated! I'm going to continue to see if I can solve this in the meantime, but I'm at a wall with how to proceed.

Body:
One way to do this is to utilize to_csv().

Example:

# importing python package
import pandas as pd

# read contents of csv file
file = pd.read_csv("gfg.csv")
print("\nOriginal file:")
print(file)

# adding header
headerList = ['id', 'name', 'profession']

# converting data frame to csv
file.to_csv("gfg2.csv", header=headerList, index=False)

# display modified csv file
file2 = pd.read_csv("gfg2.csv")
print('\nModified file:')enter code here
print(file2)


问:
Docker container file permissions
I have a java application that saves a CSV file to the root folder of the application. I am trying to create a docker image of this and run it as a container. However, I want a non-root user with ID of 1010 to be able to access this file and not root. I get errors when trying to specify USER 1010 in my dockerfile

FROM adoptjdk (placeholder)
COPY ./myapp.jar /app/
USER 1010
WORKDIR /opt
EXPOSE PORTNO
```

That's just the basics of the dockerfile, essentially I want user 1010 to be able to access the CSV file that my java application creates. I am not sure where it saves my CSV file when it is run through docker.

答:
If your application shall write to / inside the container, and your application shall be running as user id 1010, then just set the filesystem privileges accordingly. I chime in that it may not be the recommended setup, but it is not impossible.

So put in your Dockerfile lines like

```<code>RUN chmod 777 /
</code>```

or to be a bit smoother check the GID of / with

```<code>RUN ls -ln /
RUN chmod 775 /
</code>```

then ensure your java application runs with uid 1010 and the GID you saw from the filesystem. In short, such things are the same, be it inside the container or outside.

Title: Docker container file permissions

Body:
I have a java application that saves a CSV file to the root folder of the application. I am trying to create a docker image of this and run it as a container. However, I want a non-root user with ID of 1010 to be able to access this file and not root. I get errors when trying to specify USER 1010 in my dockerfile

FROM adoptjdk (placeholder)
COPY ./myapp.jar /app/
USER 1010
WORKDIR /opt
EXPOSE PORTNO

That's just the basics of the dockerfile, essentially I want user 1010 to be able to access the CSV file that my java application creates. I am not sure where it saves my CSV file when it is run through docker.

Body:
If your application shall write to / inside the container, and your application shall be running as user id 1010, then just set the filesystem privileges accordingly. I chime in that it may not be the recommended setup, but it is not impossible.

So put in your Dockerfile lines like

RUN chmod 777 /

or to be a bit smoother check the GID of / with

RUN ls -ln /
RUN chmod 775 /

then ensure your java application runs with uid 1010 and the GID you saw from the filesystem. In short, such things are the same, be it inside the container or outside.