问:
Invariant Violation: Objects are not valid as a React child
In my component's render function I have:

```<code>render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
    });
    return (
      <div>
        ...
                <ul>
                  {items}
                </ul>
         ...
      </div>
    );
  }
</code>```

everything renders fine, however when clicking the
 element I receive the following error:

Uncaught Error: Invariant Violation: Objects are not valid as a React
  child (found: object with keys {dispatchConfig, dispatchMarker,
  nativeEvent, target, currentTarget, type, eventPhase, bubbles,
  cancelable, timeStamp, defaultPrevented, isTrusted, view, detail,
  screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey,
  metaKey, getModifierState, button, buttons, relatedTarget, pageX,
  pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners,
  _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from
  the React add-ons. Check the render method of Welcome.

If I change to this.onItemClick.bind(this, item) to (e) => onItemClick(e, item) inside the map function everything works as expected.

If someone could explain what I am doing wrong and explain why do I get this error, would be great

UPDATE 1:

onItemClick function is as follows and removing this.setState results in error disappearing.

```<code>onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}
</code>```

But I cannot remove this line as I need to update state of this component

答:
I too was getting this "Objects are not valid as a React child" error and for me the cause was due to calling an asynchronous function in my JSX.  See below.

```<code>class App extends React.Component {
    showHello = async () => {
        const response = await someAPI.get("/api/endpoint");

        // Even with response ignored in JSX below, this JSX is not immediately returned,
        // causing "Objects are not valid as a React child" error.
        return (<div>Hello!</div>);
    }

    render() {
        return (
            <div>
                {this.showHello()}
            </div>
        );
    }
}
</code>```

What I learned is that asynchronous rendering is not supported in React.  The React team is working on a solution as documented here.

Body:
In my component's render function I have:

render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (
{item}
);
    });
    return (

        ...

                  {items}

         ...

    );
  }

everything renders fine, however when clicking the
 element I receive the following error:

Uncaught Error: Invariant Violation: Objects are not valid as a React
  child (found: object with keys {dispatchConfig, dispatchMarker,
  nativeEvent, target, currentTarget, type, eventPhase, bubbles,
  cancelable, timeStamp, defaultPrevented, isTrusted, view, detail,
  screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey,
  metaKey, getModifierState, button, buttons, relatedTarget, pageX,
  pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners,
  _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from
  the React add-ons. Check the render method of Welcome.

If I change to this.onItemClick.bind(this, item) to (e) => onItemClick(e, item) inside the map function everything works as expected.

If someone could explain what I am doing wrong and explain why do I get this error, would be great

UPDATE 1:

onItemClick function is as follows and removing this.setState results in error disappearing.

onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}

But I cannot remove this line as I need to update state of this component

Body:
I too was getting this "Objects are not valid as a React child" error and for me the cause was due to calling an asynchronous function in my JSX.  See below.

class App extends React.Component {
    showHello = async () => {
        const response = await someAPI.get("/api/endpoint");

        // Even with response ignored in JSX below, this JSX is not immediately returned,
        // causing "Objects are not valid as a React child" error.
        return (<div>Hello!</div>);
    }

    render() {
        return (
            <div>
                {this.showHello()}
            </div>
        );
    }
}

What I learned is that asynchronous rendering is not supported in React.  The React team is working on a solution as documented here.


来源: stackexchange

问:
How to add the input field inside the select option using ant design and react
I created select option using ant design .But I need create editable cell inside the select option.

This my select option code

```<code><Select
  showSearch
  style={{ width: 400 }}
  placeholder="Select a Bank"
  optionFilterProp="children"
  onChange={this.handleChange.bind(this)}
>
  <option value="1">Bank1</option>
  <option value="2"> Bank2</option>
  <option value="3"> Bank3</option>
</Select>
</code>```

And onChange functions is

```<code>handleChange(value) {
  console.log(`selected ${value}`);
  this.setState({
    bank:value,
  });
}
</code>```

Can you help me?

答:
You could use another modal to input the additional value.

Check this : https://codesandbox.io/s/antdselectaddoption-7fov7

ContentLicense: CC BY-SA 4.0

Body:
I created select option using ant design .But I need create editable cell inside the select option.

This my select option code

<Select
  showSearch
  style={{ width: 400 }}
  placeholder="Select a Bank"
  optionFilterProp="children"
  onChange={this.handleChange.bind(this)}
>
  <option value="1">Bank1</option>
  <option value="2"> Bank2</option>
  <option value="3"> Bank3</option>
</Select>

And onChange functions is

handleChange(value) {
  console.log(`selected ${value}`);
  this.setState({
    bank:value,
  });
}

Can you help me?


问:
how to extract a number in between strings using regex
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

```<code>with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)
</code>```

答:
If you don't want to use regex, you could implement a straightforward loop.</p>

```<code>  1 with open('test.txt') as fd:
  2     data = fd.read()
  3
  4 nums = []
  5 temp = ""
  6 is_dig = False
  7 for char in data:
  8      if char.isdigit():
  9           temp += char
 10           is_dig = True
 11      elif is_dig:
 12           nums.append(temp)
 13           temp = ""
 14           is_dig = False
 15 print(nums)
</code>```

Body:
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)

Body:
If you don't want to use regex, you could implement a straightforward loop.

  1 with open('test.txt') as fd:
  2     data = fd.read()
  3
  4 nums = []
  5 temp = ""
  6 is_dig = False
  7 for char in data:
  8      if char.isdigit():
  9           temp += char
 10           is_dig = True
 11      elif is_dig:
 12           nums.append(temp)
 13           temp = ""
 14           is_dig = False
 15 print(nums)


问:
Controlling frame-by-frame drawing in Shady
I'm struggling to understand how I can control the flow of what is being drawn on the screen by Shady. I'm used to Psychtoolbox, where you keep adding to a frame by drawing on the backbuffer, and then explicitly push it onto the screen with a call to flip(). With Shady things seem to happen automatically, so that when you add a Stimulus object to a World it gets drawn ASAP. But if I have to add several stimuli, how can I guarantee that nothing gets updated on the screen until they all get drawn?

Suppose, for example, that I want to draw a blank screen, and a small square on top of it in the top left corner. I could do something like:

```<code>w = Shady.World()
s1 = w.Stimulus(None, 'blank', envelopeSize=[1920, 1200], backgroundColor=[0, 0, 0], z=0)
s2 = w.Stimulus(None, 'square', envelopeSize=[20, 20], x=-950, y=590, backgroundColor=[1, 1, 1], z=1)
</code>```

But how can I guarantee that I do not end up with s1 being drawn from frame n onwards, and s2 from frame n+1 onward? Perhaps they can be combined into one Stimulus object, but I'd like to keep them separate (in my real case problem, the small square is actually used to trigger a photocell, and so I need to be able to flash it for a single frame, at various times during the task).

答:
First it would be a good idea to read the Shady documentation on Concurrency.  The first two examples (under the heading "Running single-threaded") do not have the problem you're worried about, since Stimulus instances are created before a single frame is actually rendered. Here's a simple example:

```<code>import Shady
w = Shady.World(threaded=False)
# s1 = ...
# s2 = ...
# ...
w.Run()
</code>```

Beyond that point, you're right that one of Shady's inherent paradigm shifts is that you never call any flip() equivalent yourself. And that may feel unfamiliar at first, but be assured: in the applications we've built on Shady, we do not miss the days of calling flip() ourselves. Updates to stimulus parameters get done in callbacks, such as:

the so-called "animation callback" that you can optionally install into every World or Stimulus instance;

dynamic (callable) values that you can assign to any World or Stimulus property (these get evaluated immediately after any animation callbacks);

event callbacks that respond to key-presses, etc.

Changes that you make within the same callback are guaranteed to be rendered on the same frame—and that's the answer to how we keep tight control of timing even when  not running single-threaded.  It's true that if you run multi-threaded and issue one w.Stimulus() call after another, they're not guaranteed to appear on the same frame (in fact, they are guaranteed to appear on different frames because a .Stimulus() call in the non-drawing thread actually defers the real work of stimulus creation into the drawing thread and then waits until that has been completed before returning). The possible antidotes are (1) run single-threaded; (2) perform all w.Stimulus() creation calls in a dedicated Prepare() method, as in the documentation's second example; or (3) ensure the stimuli have visible=False when created, and only make them visible later.   In all of those cases, we are careful to separate creation of stimuli (which can be slow) from manipulation of their properties.

The first two callback types are most relevant to what you're describing. They are covered in Shady's documentation on "Making properties dynamic". Within the framework they provide, there are (as always in Python, and in Shady) many different ways to achieve the goal you describe.  Personally, I like to use a StateMachine instance as my animation callback.   Here's how I would create a simple repetitively-presented stimulus whose onset is heralded by a sensor patch flashing for a single frame:

```<code>import random
import Shady

w = Shady.World(canvas=True, gamma=2.2)

# STIMULI

Shady.Stimulus.SetDefault(visible=False)
# let all stimuli be invisible by default when created

gabor = w.Sine(pp=0)
sensorPatch = w.Stimulus(
    size = 100,  # small,
    color = 1,   # bright,
    anchor = Shady.UPPER_LEFT, # with its top-left corner stuck...
    position = w.Place(Shady.UPPER_LEFT),  # to the top-left corner of the screen
)

# STATE MACHINE

sm = Shady.StateMachine()

@sm.AddState
class InterTrialInterval(sm.State):
    # state names should be descriptive but can be anything you want

    def duration(self):
        return random.uniform(1.0, 3.0)

    next = 'PresentGabor'

@sm.AddState
class PresentGabor(sm.State):

    def onset(self):
        gabor.visible = True
        sensorPatch.visible = Shady.Impulse() # a dynamic object: returns 1.0 the first time it is evaluated, then 0.0 thereafter

    duration = 2.0

    def offset(self):
        gabor.visible = False

    next = 'InterTrialInterval'

w.SetAnimationCallback( sm )
# now sm(t) will be called at every new time `t`, i.e. on every frame,
# and this will in turn call `onset()` and `offset()` whenever appropriate
</code>```

Body:
I'm struggling to understand how I can control the flow of what is being drawn on the screen by Shady. I'm used to Psychtoolbox, where you keep adding to a frame by drawing on the backbuffer, and then explicitly push it onto the screen with a call to flip(). With Shady things seem to happen automatically, so that when you add a Stimulus object to a World it gets drawn ASAP. But if I have to add several stimuli, how can I guarantee that nothing gets updated on the screen until they all get drawn?

Suppose, for example, that I want to draw a blank screen, and a small square on top of it in the top left corner. I could do something like:

w = Shady.World()
s1 = w.Stimulus(None, 'blank', envelopeSize=[1920, 1200], backgroundColor=[0, 0, 0], z=0)
s2 = w.Stimulus(None, 'square', envelopeSize=[20, 20], x=-950, y=590, backgroundColor=[1, 1, 1], z=1)

But how can I guarantee that I do not end up with s1 being drawn from frame n onwards, and s2 from frame n+1 onward? Perhaps they can be combined into one Stimulus object, but I'd like to keep them separate (in my real case problem, the small square is actually used to trigger a photocell, and so I need to be able to flash it for a single frame, at various times during the task).

Body:
First it would be a good idea to read the Shady documentation on Concurrency.  The first two examples (under the heading "Running single-threaded") do not have the problem you're worried about, since Stimulus instances are created before a single frame is actually rendered. Here's a simple example:

import Shady
w = Shady.World(threaded=False)
# s1 = ...
# s2 = ...
# ...
w.Run()

Beyond that point, you're right that one of Shady's inherent paradigm shifts is that you never call any flip() equivalent yourself. And that may feel unfamiliar at first, but be assured: in the applications we've built on Shady, we do not miss the days of calling flip() ourselves. Updates to stimulus parameters get done in callbacks, such as:

the so-called "animation callback" that you can optionally install into every World or Stimulus instance;

dynamic (callable) values that you can assign to any World or Stimulus property (these get evaluated immediately after any animation callbacks);

event callbacks that respond to key-presses, etc.

Changes that you make within the same callback are guaranteed to be rendered on the same frame—and that's the answer to how we keep tight control of timing even when  not running single-threaded.  It's true that if you run multi-threaded and issue one w.Stimulus() call after another, they're not guaranteed to appear on the same frame (in fact, they are guaranteed to appear on different frames because a .Stimulus() call in the non-drawing thread actually defers the real work of stimulus creation into the drawing thread and then waits until that has been completed before returning). The possible antidotes are (1) run single-threaded; (2) perform all w.Stimulus() creation calls in a dedicated Prepare() method, as in the documentation's second example; or (3) ensure the stimuli have visible=False when created, and only make them visible later.   In all of those cases, we are careful to separate creation of stimuli (which can be slow) from manipulation of their properties.

The first two callback types are most relevant to what you're describing. They are covered in Shady's documentation on "Making properties dynamic". Within the framework they provide, there are (as always in Python, and in Shady) many different ways to achieve the goal you describe.  Personally, I like to use a StateMachine instance as my animation callback.   Here's how I would create a simple repetitively-presented stimulus whose onset is heralded by a sensor patch flashing for a single frame:

import random
import Shady

w = Shady.World(canvas=True, gamma=2.2)

# STIMULI

Shady.Stimulus.SetDefault(visible=False)
# let all stimuli be invisible by default when created

gabor = w.Sine(pp=0)
sensorPatch = w.Stimulus(
    size = 100,  # small,
    color = 1,   # bright,
    anchor = Shady.UPPER_LEFT, # with its top-left corner stuck...
    position = w.Place(Shady.UPPER_LEFT),  # to the top-left corner of the screen
)

# STATE MACHINE

sm = Shady.StateMachine()

@sm.AddState
class InterTrialInterval(sm.State):
    # state names should be descriptive but can be anything you want

    def duration(self):
        return random.uniform(1.0, 3.0)

    next = 'PresentGabor'

@sm.AddState
class PresentGabor(sm.State):

    def onset(self):
        gabor.visible = True
        sensorPatch.visible = Shady.Impulse() # a dynamic object: returns 1.0 the first time it is evaluated, then 0.0 thereafter

    duration = 2.0

    def offset(self):
        gabor.visible = False

    next = 'InterTrialInterval'

w.SetAnimationCallback( sm )
# now sm(t) will be called at every new time `t`, i.e. on every frame,
# and this will in turn call `onset()` and `offset()` whenever appropriate


问:
Windows copy command does not concatenates video files properly
I have concatenated 3 mpg files to one avi file using windows COPY command.
I tried this from the command prompt as well as from my application that i created in C# (using system.diagnostics.process.start)

I found that the resultant file plays well on VLC but when i try to play the same file on Windows Media Player then the resultant file plays only parts belonging to 1st and 2nd mpg's and not the third one.Though the file size is perfect.

I also tried copying the 3 mpg files to output.mpg and then converting this to final.avi..But the problem is same

Command:

```<code>Copy /b first.mpg /b + second.mpg /b + third.mpg /b output.avi /b
</code>```

can anybody suggest me what should i do or what could be the possible issue.

Thanks.

答:
Concatenating files this way does not make sense.  It actually only makes sense for plain text files (and even then, only if they don't include a BOM marker).

In general files have an internal structure, and concatenating two of these structures doesn't make it a valid new structure.  E.g. take a simple HTML page:

```<code><HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
</BODY>
</HTML>
</code>```

If you concatenate two of these files you get this:

```<code><HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
</BODY>
</HTML>
<HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello Again</H1>
</BODY>
</HTML>
</code>```

But you problably want this:

```<code><HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
   <H1>Hello Again</H1>
</BODY>
</HTML>
</code>```

Therefore, concatenating files must be done using the correct software that knows the internal structure and knows how to correctly concatenate these files.

Because it may work in some cases, it doesn't mean that the resulting file is correct.  Maybe in your example, VLC is rather forgiving and skips unrecognized blocks.  Other media players may not be that forgiving and play only the first part, play nothing at all, or crash.

ContentLicense: CC BY-SA 3.0

Body:
I have concatenated 3 mpg files to one avi file using windows COPY command.
I tried this from the command prompt as well as from my application that i created in C# (using system.diagnostics.process.start)

I found that the resultant file plays well on VLC but when i try to play the same file on Windows Media Player then the resultant file plays only parts belonging to 1st and 2nd mpg's and not the third one.Though the file size is perfect.

I also tried copying the 3 mpg files to output.mpg and then converting this to final.avi..But the problem is same

Command:

Copy /b first.mpg /b + second.mpg /b + third.mpg /b output.avi /b

can anybody suggest me what should i do or what could be the possible issue.

Thanks.

Body:
Concatenating files this way does not make sense.  It actually only makes sense for plain text files (and even then, only if they don't include a BOM marker).

In general files have an internal structure, and concatenating two of these structures doesn't make it a valid new structure.  E.g. take a simple HTML page:

<HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
</BODY>
</HTML>

If you concatenate two of these files you get this:

<HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
</BODY>
</HTML>
<HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello Again</H1>
</BODY>
</HTML>

But you problably want this:

<HTML>
<HEAD></HEAD>
<BODY>
   <H1>Hello World</H1>
   <H1>Hello Again</H1>
</BODY>
</HTML>

Therefore, concatenating files must be done using the correct software that knows the internal structure and knows how to correctly concatenate these files.

Because it may work in some cases, it doesn't mean that the resulting file is correct.  Maybe in your example, VLC is rather forgiving and skips unrecognized blocks.  Other media players may not be that forgiving and play only the first part, play nothing at all, or crash.


问:
How do I speed up this file creation process?
I am trying to create a large flat file with fixed width columns that contains multiple layers, but processing seems to be very slow, most likely because I am iterating over each row.
For context, this is for transmitting insurance policy information.

The hierarchy goes like this:

```<code>-Policy row
--Property on policy
---Coverage on property
--Property on policy
---Coverage on property
--Owner on policy
--Owner on policy
--Owner on policy
</code>```

Currently I'm loading the four record types into separate dataframes, and then doing a for loop over each type by pulling them based on the parent record's ID, and then writing them to the file. I'm hoping for some sort of hierarchical dataFrame merge that doesn't force me to scan the file each time I want a record.

```<code>import re
import pandas as pd
import math

def MakeNumeric(instring):
    output = re.sub('[^0-9]', '', str(instring))
    return str(output)

def Pad(instring, padchar, length, align):
    if instring is None:  # Takes care of NULL values
        instring = ''
    instring = str(instring).upper()
    instring = instring.replace(',', '').replace('\n', '').replace('\r', '')
    instring = instring[:length]
    if align == 'L':
        output = instring + (padchar * (length - len(instring)))
    elif align == 'R':
        output = (padchar * (length - len(instring))) + instring
    else:
        output = instring
    return output

def FileCreation():
    POLR = pd.read_parquet(r'POLR.parquet')
    PRP1 = pd.read_parquet(r'PRP1.parquet')
    PROP = pd.read_parquet(r'PROP.parquet')
    SUBJ = pd.read_parquet(r'SUBJ.parquet')
    rownum = 1
    totalrownum = 1
    POLRCt = 0
    size = 900000
    POLR = [POLR.loc[i:i + size - 1, :] for i in range(0, len(POLR), size)]
    FileCt = 0
    print('Predicted File Count: ' + str(math.ceil(len(POLR[0])/ size)) )
    for df in POLR:
        FileCt += 1
        filename = r'OutputFile.' + Pad(FileCt, '0', 2, 'R')
        with open(filename, 'a+') as outfile:
            for i, row in df.iterrows():
                row[0] = Pad(rownum, '0', 9, 'R')
                row[1] = Pad(row[1], ' ', 4, 'L')
                row[2] = Pad(row[2], '0', 5, 'R')
                # I do this for all 50 columns
                outfile.write((','.join(row[:51])).replace(',', '') + '\n')
                rownum += 1
                totalrownum += 1
                for i2, row2 in PROP[PROP.ID == row[51]].iterrows():
                    row2[0] = Pad(rownum, '0', 9, 'R')
                    row2[1] = Pad(row2[1], ' ', 4, 'L')
                    row2[2] = Pad(row2[2], '0', 5, 'R')
                    # I do this for all 105 columns
                    outfile.write((','.join(row2[:106])).replace(',', '') + '\n')
                    rownum += 1
                    totalrownum += 1
                    for i3, row3 in PRP1[(PRP1['id'] == row2['ID']) & (PRP1['VNum'] == row2['vnum'])].iterrows():
                        row3[0] = Pad(rownum, '0', 9, 'R')
                        row3[1] = Pad(row3[1], ' ', 4, 'L')
                        row3[2] = Pad(row3[2], '0', 5, 'R')
                        # I do this for all 72 columns
                        outfile.write((','.join(row3[:73])).replace(',', '') + '\n')
                        rownum += 1
                        totalrownum += 1
                for i2, row2 in SUBJ[SUBJ['id'] == row['id']].iterrows():
                    row2[0] = Pad(rownum, '0', 9, 'R')
                    row2[1] = Pad(row2[1], ' ', 4, 'L')
                    row2[2] = Pad(row2[2], '0', 5, 'R')
                    # I do this for all 24 columns
                    outfile.write((','.join(row2[:25])).replace(',', '') + '\n')
                    rownum += 1
                    totalrownum += 1
                POLRCt += 1
                print('File {} of {} '.format(str(FileCt),str(len(POLR)) ) + str((POLRCt - 1) / len(df.index) * 100) + '% Finished\r')
            rownum += 1
        rownum = 1
        POLRCt = 1
</code>```

I'm essentially looking for a script that doesn't take multiple days to create a 27M record file.

答:
I ended up populating temp tables for each record level, and creating keys, then inserting them into a permanent staging table and assigning an clustered index to the keys.
I then queried the results while using OFFSET and FETCH NEXT %d ROWS ONLY to reduce memory size. I then used the multiprocessing library to break the workload out for each thread on the CPU.
Ultimately, the combination of these have reduced the runtime to about 20% of what it was when this question was originally posted.

Body:
I am trying to create a large flat file with fixed width columns that contains multiple layers, but processing seems to be very slow, most likely because I am iterating over each row.
For context, this is for transmitting insurance policy information.

The hierarchy goes like this:

-Policy row
--Property on policy
---Coverage on property
--Property on policy
---Coverage on property
--Owner on policy
--Owner on policy
--Owner on policy

Currently I'm loading the four record types into separate dataframes, and then doing a for loop over each type by pulling them based on the parent record's ID, and then writing them to the file. I'm hoping for some sort of hierarchical dataFrame merge that doesn't force me to scan the file each time I want a record.

import re
import pandas as pd
import math

def MakeNumeric(instring):
    output = re.sub('[^0-9]', '', str(instring))
    return str(output)

def Pad(instring, padchar, length, align):
    if instring is None:  # Takes care of NULL values
        instring = ''
    instring = str(instring).upper()
    instring = instring.replace(',', '').replace('\n', '').replace('\r', '')
    instring = instring[:length]
    if align == 'L':
        output = instring + (padchar * (length - len(instring)))
    elif align == 'R':
        output = (padchar * (length - len(instring))) + instring
    else:
        output = instring
    return output

def FileCreation():
    POLR = pd.read_parquet(r'POLR.parquet')
    PRP1 = pd.read_parquet(r'PRP1.parquet')
    PROP = pd.read_parquet(r'PROP.parquet')
    SUBJ = pd.read_parquet(r'SUBJ.parquet')
    rownum = 1
    totalrownum = 1
    POLRCt = 0
    size = 900000
    POLR = [POLR.loc[i:i + size - 1, :] for i in range(0, len(POLR), size)]
    FileCt = 0
    print('Predicted File Count: ' + str(math.ceil(len(POLR[0])/ size)) )
    for df in POLR:
        FileCt += 1
        filename = r'OutputFile.' + Pad(FileCt, '0', 2, 'R')
        with open(filename, 'a+') as outfile:
            for i, row in df.iterrows():
                row[0] = Pad(rownum, '0', 9, 'R')
                row[1] = Pad(row[1], ' ', 4, 'L')
                row[2] = Pad(row[2], '0', 5, 'R')
                # I do this for all 50 columns
                outfile.write((','.join(row[:51])).replace(',', '') + '\n')
                rownum += 1
                totalrownum += 1
                for i2, row2 in PROP[PROP.ID == row[51]].iterrows():
                    row2[0] = Pad(rownum, '0', 9, 'R')
                    row2[1] = Pad(row2[1], ' ', 4, 'L')
                    row2[2] = Pad(row2[2], '0', 5, 'R')
                    # I do this for all 105 columns
                    outfile.write((','.join(row2[:106])).replace(',', '') + '\n')
                    rownum += 1
                    totalrownum += 1
                    for i3, row3 in PRP1[(PRP1['id'] == row2['ID']) & (PRP1['VNum'] == row2['vnum'])].iterrows():
                        row3[0] = Pad(rownum, '0', 9, 'R')
                        row3[1] = Pad(row3[1], ' ', 4, 'L')
                        row3[2] = Pad(row3[2], '0', 5, 'R')
                        # I do this for all 72 columns
                        outfile.write((','.join(row3[:73])).replace(',', '') + '\n')
                        rownum += 1
                        totalrownum += 1
                for i2, row2 in SUBJ[SUBJ['id'] == row['id']].iterrows():
                    row2[0] = Pad(rownum, '0', 9, 'R')
                    row2[1] = Pad(row2[1], ' ', 4, 'L')
                    row2[2] = Pad(row2[2], '0', 5, 'R')
                    # I do this for all 24 columns
                    outfile.write((','.join(row2[:25])).replace(',', '') + '\n')
                    rownum += 1
                    totalrownum += 1
                POLRCt += 1
                print('File {} of {} '.format(str(FileCt),str(len(POLR)) ) + str((POLRCt - 1) / len(df.index) * 100) + '% Finished\r')
            rownum += 1
        rownum = 1
        POLRCt = 1

I'm essentially looking for a script that doesn't take multiple days to create a 27M record file.


问:
Getting TS to complain about null comparison to a non-nullable field?
Is there a way to get TS to complain about this?  I have strictNullChecks on

```<code>const foo: string = 'asdf';

if (foo !== null) {
    console.log(foo);
}
</code>```

If, for instance, I change that condition to:

```<code>if (foo !== 42) {
</code>```

I get:

This condition will always return 'true' since the types 'string' and 'number' have no overlap.

答:
You can't cause an error with === because TS has special carve-outs that make comparison with null/undefined always allowed.

If you're willing to use a helper function, you can use a conditional type to ensure that null is a possible value of the tested expression:

```<code>function isNull<T>(x: T): null extends T ? boolean: void {
   return (x === null) as any;
}

// Error
declare const a: string;
if (isNull(a)) { }

// OK
declare const b: string | null;
if (isNull(b)) { }
</code>```

Body:
Is there a way to get TS to complain about this?  I have strictNullChecks on

const foo: string = 'asdf';

if (foo !== null) {
    console.log(foo);
}

If, for instance, I change that condition to:

if (foo !== 42) {

I get:

This condition will always return 'true' since the types 'string' and 'number' have no overlap.

Body:
You can't cause an error with === because TS has special carve-outs that make comparison with null/undefined always allowed.

If you're willing to use a helper function, you can use a conditional type to ensure that null is a possible value of the tested expression:

function isNull<T>(x: T): null extends T ? boolean: void {
   return (x === null) as any;
}

// Error
declare const a: string;
if (isNull(a)) { }

// OK
declare const b: string | null;
if (isNull(b)) { }


问:
C# Server side DateTime
Please tell me, is it good to store DateTime, for example createtime of posts, on server in ticks?</p>

```<code>DateTime.Ticks
</code>```

答:
Every modern database have DATETIME, DATE and/or TIMESTAMP datatypes, so there is no need for using an Int64.

But you could use DateTime.Ticks if you're saving data into a text file, for instance. Seems to be a good option in that case.

Title: C# Server side DateTime

Body:
Please tell me, is it good to store DateTime, for example createtime of posts, on server in ticks?

DateTime.Ticks


问:
Ant pattern matching to select file is not working
```<code><fileset dir="${server.src}" casesensitive="yes">
  <patternset id="non.test.sources">
    <include name="**/test-[0-9-]+.zip"/>
  </patternset>
</fileset>
</code>```

I am using pattern matching to select only particular file in ant build.xml
But its not selecting any file.
I have a file with name  test-123453.zip

答:
A fileset's include element expects glob patterns, not regex patterns. Nesting it in a patternset doesn't change this functionality.

You can use the filename selector with the regex attribute to accomplish what you're trying to do:

```<code><fileset dir="${server.src}">
    <filename regex="test-[0-9-]+\.zip" />
</fileset>
</code>```

Body:
<fileset dir="${server.src}" casesensitive="yes">
  <patternset id="non.test.sources">
    <include name="**/test-[0-9-]+.zip"/>
  </patternset>
</fileset>

I am using pattern matching to select only particular file in ant build.xml
But its not selecting any file.
I have a file with name  test-123453.zip

Body:
A fileset's include element expects glob patterns, not regex patterns. Nesting it in a patternset doesn't change this functionality.

You can use the filename selector with the regex attribute to accomplish what you're trying to do:

<fileset dir="${server.src}">
    <filename regex="test-[0-9-]+\.zip" />
</fileset>


问:
Should I open a new repository on GitHub or simply branch?
I have a project we've been working on that is a tool which visualizes word embeddings on certain trained data. This was a small school project that we are kind of done with.

Now, I want to take this further by letting users upload their trained models and giving them the tool of visualization. This future project will contain much of the previous project's code. However, I want both to be two separate 'products' because I do not want to mess with our first project's code. Should I branch on the first project, or should I create a new repository?

答:
I think the question you are asking falls into a long going debate between mono-repository vs. multi-repository project.

This post (https://medium.com/@patrickleet/mono-repo-or-multi-repo-why-choose-one-when-you-can-have-both-e9c77bd0c668) discussed some of the things you want to consider before making the decision.

I would say if it is a hobby project, I will suggest using mono-repository strategy because most likely you won't have the time or money to invest on a synchronized build infrastructure that fetches and assembles from different repositories. If modifying and modularizing your code seems to be too much work. I suggest opening a new repository, plan ahead for two products as a group, migrate the code, and dump the old repository.

This project I built as my own reminder notebook is a fairly straight forward mono-repository project:

https://github.com/tianhaoz95/developer-note

as there are many mini projects in the project directory, and they all share the same Travis or CircleCI build infrastructure.

Feel free to send me messages if you want to discuss this topic.


问:
How do I setup CFReadStreamRead to timeout in iOS?
I have legacy code using CFReadStreamRead on the iOS, but if there is no/loss of a connection CFReadStreamRead will block forever.  How do I setup CFReadStreamRead to timeout?

Thanks in advance

答:
I set a custom timeout method:</p>

```<code>var hasRecievedUpdate = false
var httpStream: CFReadStream?
var handler: ((Data?, URLResponse?, Error?) -> Void)?

func send() {
        let stream = httpStream as Stream
        stream.delegate = self

        stream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
        stream.open()

        hasRecievedUpdate = false

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.timeout) {
            if !self.hasRecievedUpdate
            {
                stream.close()
                self.handler?(nil, nil, nil)
            }
        }
}

 func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

        self.hasRecievedUpdate = true
        ...
}
</code>```

Body:
I set a custom timeout method:

var hasRecievedUpdate = false
var httpStream: CFReadStream?
var handler: ((Data?, URLResponse?, Error?) -> Void)?

func send() {
        let stream = httpStream as Stream
        stream.delegate = self

        stream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
        stream.open()

        hasRecievedUpdate = false

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.timeout) {
            if !self.hasRecievedUpdate
            {
                stream.close()
                self.handler?(nil, nil, nil)
            }
        }
}

 func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

        self.hasRecievedUpdate = true
        ...
}


问:
How can I test Android WorkManager with setRequiredNetworkType(NetworkType.CONNECTED) constraint?
I am trying to write Android instrumentation tests for a class that contains WorkManager WorkRequests.

For a long time I was stuck at the point where I could see the workers being enqueued but they never got executed. After some time and trial and error I realised the following constraint was blocking the test:

```<code>...
 setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
...
</code>```

If I remove that constraint the work item is executed as expected.

My virtual device has a network connection so not sure why this constraint isn't being met in my test.

Does anyone have any advice on how to fix this as I need to write tests that cover cases where this constraint is met and when it isn't.

My work request is pretty simple but here it is:

```<code>val workRequest = OneTimeWorkRequestBuilder<T>()
                .addTag(syncWork.getSyncType().name)
                .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
                .build()

syncWorkRepository.save(syncWork.apply { id = workRequest.id.toString() })

workManager.enqueue(workRequest)
</code>```

I have tried:

```<code>val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    wifi.isWifiEnabled = true
</code>```

but this throws a Security exception:

```<code>SecurityException: WifiService: Neither user 10139 nor current process has android.permission.CHANGE_WIFI_STATE.
</code>```

I have also added code to my test to check network state:

```<code>val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
    val isConnected: Boolean = activeNetwork?.isConnected == true
</code>```

And isConnected is true but still the WorkManager constraint is not met and so the work is not executed.

Also tried:

```<code>val testDriver = getTestDriver()
</code>```

with

```<code>testDriver?.setAllConstraintsMet(workInfo.id)
</code>```

inside my observe LiveData by tag method which I can see being executed once for the ENQUEUED state.

Here is my observer in the test:

```<code>syncManager.syncWork(SyncType.ALL)
        .observe(lifecycleOwner, Observer { listOfWorkInfo ->
        listOfWorkInfo.forEach { workInfo ->
            Log.d("TAG", "${workInfo.id}")
            testDriver?.setAllConstraintsMet(workInfo.id)
            if(workInfo.state == WorkInfo.State.SUCCEEDED) {
                Log.d("TAG", workInfo.state.name)
                latch.countDown()
            } else if(workInfo.state != WorkInfo.State.ENQUEUED) {
                Log.d("TAG", workInfo.state.name)
                latch.countDown()
            }
        }
    })
</code>```

Thanks,
Paul

答: You should be using WorkManagerTestInitHelper. Once you use the TestDriver and mark your constraint as met, your Worker should execute.

Body:
I am trying to write Android instrumentation tests for a class that contains WorkManager WorkRequests.

For a long time I was stuck at the point where I could see the workers being enqueued but they never got executed. After some time and trial and error I realised the following constraint was blocking the test:

...
 setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
...

If I remove that constraint the work item is executed as expected.

My virtual device has a network connection so not sure why this constraint isn't being met in my test.

Does anyone have any advice on how to fix this as I need to write tests that cover cases where this constraint is met and when it isn't.

My work request is pretty simple but here it is:

val workRequest = OneTimeWorkRequestBuilder<T>()
                .addTag(syncWork.getSyncType().name)
                .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
                .build()

syncWorkRepository.save(syncWork.apply { id = workRequest.id.toString() })

workManager.enqueue(workRequest)

I have tried:

val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    wifi.isWifiEnabled = true

but this throws a Security exception:

SecurityException: WifiService: Neither user 10139 nor current process has android.permission.CHANGE_WIFI_STATE.

I have also added code to my test to check network state:

val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
    val isConnected: Boolean = activeNetwork?.isConnected == true

And isConnected is true but still the WorkManager constraint is not met and so the work is not executed.

Also tried:

val testDriver = getTestDriver()

with

testDriver?.setAllConstraintsMet(workInfo.id)

inside my observe LiveData by tag method which I can see being executed once for the ENQUEUED state.

Here is my observer in the test:

syncManager.syncWork(SyncType.ALL)
        .observe(lifecycleOwner, Observer { listOfWorkInfo ->
        listOfWorkInfo.forEach { workInfo ->
            Log.d("TAG", "${workInfo.id}")
            testDriver?.setAllConstraintsMet(workInfo.id)
            if(workInfo.state == WorkInfo.State.SUCCEEDED) {
                Log.d("TAG", workInfo.state.name)
                latch.countDown()
            } else if(workInfo.state != WorkInfo.State.ENQUEUED) {
                Log.d("TAG", workInfo.state.name)
                latch.countDown()
            }
        }
    })

Thanks,
Paul


问:
Apple Touch icon for websites
Up to now, I've been including the line for the Apple Touch icon in my head like this:

<link rel="apple-touch-icon" href="/apple-touch-icon.png">

However, in the Q&A "What are the correct pixel dimensions for an apple-touch-icon?" it is stated in the accepted answer that three images are now needed according to Apple's guidelines.

So how would one go about inserting these into the head section of the code?

答:
Here you go, hope this helps.

If you want Apple to do the aesthetic bit for you (add the gloss) then you'd put in these to the  tags:

```<code><link rel="apple-touch-icon" href="apple-touch-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-iphone4.png" />
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-ipad-retina.png" />
</code>```

If you want to precompose the image, so that Apple displays it without the gloss, then you'd do this:

```<code><link rel="apple-touch-icon-precomposed" href="apple-touch-iphone.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-ipad.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-iphone4.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-ipad-retina.png" />
</code>```

Providing you include more than one, the iOS device will look for the correct size and utilise that image automatically. As you can see from the names of the images in the example, the iPad with retina display needs an icon which is 144x144px, the iPhone 4/4S/5 needs an icon which is 114x114px, the original iPad (and iPad 2, as the screen resolution is no different) needs an icon which is 72x72px, and the original iPhone doesn’t need a size specification, but for your reference it is 57x57px.

Title: Apple Touch icon for websites

Body:
Here you go, hope this helps.

If you want Apple to do the aesthetic bit for you (add the gloss) then you'd put in these to the <head> tags:

<link rel="apple-touch-icon" href="apple-touch-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-iphone4.png" />
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-ipad-retina.png" />

If you want to precompose the image, so that Apple displays it without the gloss, then you'd do this:

<link rel="apple-touch-icon-precomposed" href="apple-touch-iphone.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-ipad.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-iphone4.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-ipad-retina.png" />

Providing you include more than one, the iOS device will look for the correct size and utilise that image automatically. As you can see from the names of the images in the example, the iPad with retina display needs an icon which is 144x144px, the iPhone 4/4S/5 needs an icon which is 114x114px, the original iPad (and iPad 2, as the screen resolution is no different) needs an icon which is 72x72px, and the original iPhone doesn’t need a size specification, but for your reference it is 57x57px.


问:
Test class for setting same value to two diferents objects
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

```<code>for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...
</code>```

答:
There isn't much context to what you're trying to do but you have to create the account</p>

```<code>Account acct = new Account();
acct.Yield__c = 50;
acct.Yield2__c = 60;
insert acct;
</code>```

Body:
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...

Body:
There isn't much context to what you're trying to do but you have to create the account

Account acct = new Account();
acct.Yield__c = 50;
acct.Yield2__c = 60;
insert acct;


问:
why map() is mutating original objects in a nested array?
I'm trying to create a new array of objects (usersData) using map() in order to add a new property assigned with a value from a secondary array (countries).
During my tests I've noticed that my original array of objects (users) has been modified and the new property (countryName) has been added to it. The same did not happen when I use map to create a new array of objects for my array countries.
Could someone tell me what is causing this and help me to understand how to avoid such a behaviour?

```<code>const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {
  const newUser = {};
  newUser.name = user.name;
  newUser.contactDetails = user.contactDetails;
  newUser.contactDetails.countryName = "UK";
  return newUser;
});

const countriesData = countries.map(country =>
  {
    const newCountry = {};
    newCountry.name = country.countryName;
    newCountry.continent = "Europe";
    return newCountry;
});
console.log(countries);
console.log(countriesData);
console.log(users);
console.log(usersData);
</code>```

I expect the elements in the array users to keep its original structure but it has now the property contactDetails.countryName set to "UK"

答:
You're building a new array. That doesn't mean you're building a new everything-inside-the-array too.

This:

```<code>newUser.contactDetails = user.contactDetails;
</code>```

is reusing the user.contactDetails object from the original array element, so this:

```<code>newUser.contactDetails.countryName = "UK";
</code>```

is modifying an object shared between both the new and the old array.

Body:
I'm trying to create a new array of objects (usersData) using map() in order to add a new property assigned with a value from a secondary array (countries).
During my tests I've noticed that my original array of objects (users) has been modified and the new property (countryName) has been added to it. The same did not happen when I use map to create a new array of objects for my array countries.
Could someone tell me what is causing this and help me to understand how to avoid such a behaviour?

const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {
  const newUser = {};
  newUser.name = user.name;
  newUser.contactDetails = user.contactDetails;
  newUser.contactDetails.countryName = "UK";
  return newUser;
});

const countriesData = countries.map(country =>
  {
    const newCountry = {};
    newCountry.name = country.countryName;
    newCountry.continent = "Europe";
    return newCountry;
});
console.log(countries);
console.log(countriesData);
console.log(users);
console.log(usersData);

I expect the elements in the array users to keep its original structure but it has now the property contactDetails.countryName set to "UK"

Body:
You're building a new array. That doesn't mean you're building a new everything-inside-the-array too.

This:

newUser.contactDetails = user.contactDetails;

is reusing the user.contactDetails object from the original array element, so this:

newUser.contactDetails.countryName = "UK";

is modifying an object shared between both the new and the old array.


问:
cannot calculate mean() with dplyr()
I have the following code where I cannot calculate the last line of code (the average of top 5 values in the 17th column), which results in a warning message Warning message:In mean.default(df[1:5, 17], na.rm = TRUE) :  argument is not numeric or logical: returning NA

Any suggestions what I'm doing wrong? Thanks!

```<code>library(eurostat)
library(dplyr)
library(tidyr)

earn_mw_avgr2 <- get_eurostat("earn_mw_avgr2", stringsAsFactors = FALSE)

df <- earn_mw_avgr2 %>%
    filter(geo %in% c("BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR",
                   "IT","CY","LV","LU","HU","MT","NL","AT","PL","PT","RO",
                   "SI","SK","FI","SE","UK"),
        indic_se=="MW_MEAGE",
        nace_r2=="B-S") %>%
    spread(time, values)%>%
    select(-c(17,18))%>%
    mutate(avg=rowMeans(.[14:16], na.rm = TRUE))%>%
    arrange(desc(avg))

mean(df[1:5,17], na.rm = TRUE)
</code>```

答:
Issue is that it is a tibble and it won't drop dimensions as data.frame (where the ?Extract would be drop = TRUE)

```<code>mean(df[1:5,][[17]])
#[1] 47.29667
</code>```

mean works on vectors.  If we check the ?mean

x - An R object. Currently there are methods for numeric/logical vectors and date, date-time and time interval objects. Complex vectors are allowed for trim = 0, only.

Title: cannot calculate mean() with dplyr()

Body:
I have the following code where I cannot calculate the last line of code (the average of top 5 values in the 17th column), which results in a warning message Warning message:In mean.default(df[1:5, 17], na.rm = TRUE) :  argument is not numeric or logical: returning NA

Any suggestions what I'm doing wrong? Thanks!

library(eurostat)
library(dplyr)
library(tidyr)

earn_mw_avgr2 <- get_eurostat("earn_mw_avgr2", stringsAsFactors = FALSE)

df <- earn_mw_avgr2 %>%
    filter(geo %in% c("BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR",
                   "IT","CY","LV","LU","HU","MT","NL","AT","PL","PT","RO",
                   "SI","SK","FI","SE","UK"),
        indic_se=="MW_MEAGE",
        nace_r2=="B-S") %>%
    spread(time, values)%>%
    select(-c(17,18))%>%
    mutate(avg=rowMeans(.[14:16], na.rm = TRUE))%>%
    arrange(desc(avg))

mean(df[1:5,17], na.rm = TRUE)

Body:
Issue is that it is a tibble and it won't drop dimensions as data.frame (where the ?Extract would be drop = TRUE)

mean(df[1:5,][[17]])
#[1] 47.29667

mean works on vectors.  If we check the ?mean

x - An R object. Currently there are methods for numeric/logical vectors and date, date-time and time interval objects. Complex vectors are allowed for trim = 0, only.


答:
Adding $avg to df[1:5,17] fixes it. Full code below.

```<code>library(dplyr)
library(tidyr)

earn_mw_avgr2 <- get_eurostat("earn_mw_avgr2", stringsAsFactors = FALSE)

df <- earn_mw_avgr2 %>%
  filter(geo %in% c("BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR",
                    "IT","CY","LV","LU","HU","MT","NL","AT","PL","PT","RO",
                    "SI","SK","FI","SE","UK"),
         indic_se=="MW_MEAGE",
         nace_r2=="B-S") %>%
  spread(time, values)%>%
  select(-c(17,18))%>%
  mutate(avg=rowMeans(.[14:16], na.rm = TRUE))%>%
  arrange(desc(avg))

mean(df[1:5,17]$avg, na.rm = TRUE)
</code>```

Title: cannot calculate mean() with dplyr()

Body:
Adding $avg to df[1:5,17] fixes it. Full code below.

library(dplyr)
library(tidyr)

earn_mw_avgr2 <- get_eurostat("earn_mw_avgr2", stringsAsFactors = FALSE)

df <- earn_mw_avgr2 %>%
  filter(geo %in% c("BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR",
                    "IT","CY","LV","LU","HU","MT","NL","AT","PL","PT","RO",
                    "SI","SK","FI","SE","UK"),
         indic_se=="MW_MEAGE",
         nace_r2=="B-S") %>%
  spread(time, values)%>%
  select(-c(17,18))%>%
  mutate(avg=rowMeans(.[14:16], na.rm = TRUE))%>%
  arrange(desc(avg))

mean(df[1:5,17]$avg, na.rm = TRUE)


问:
PropTypes in React
In some examples, I have seen something like this:

```<code>Footer.propTypes = {
  completedCount: PropTypes.number.isRequired,
  activeCount: PropTypes.number.isRequired,
  filter: PropTypes.string.isRequired,
  onClearCompleted: PropTypes.func.isRequired,
  onShow: PropTypes.func.isRequired
}
</code>```

What are these PropTypes really doing? Are they nice-to-have or must-have?

答:
In React, you should write reusable components and to do that you have to define their interface in the clearest possible way.If you want your components to be reused across the application, it is crucial to make sure that our components and their parameters are well-defined and straightforward to use. You  ALWAYS HAVE TO VALIDATE your data.

Let's imagine you have an ecommerce website and you want to display your products in your homepage. For this, you need to create Product component and inside of it, you have to validate the data to prevent yourself displaying "true" where you want to display "number" for price. Here is an example:

```<code>Product.propTypes = {
  product: PropTypes.shape({
    id: PropTypes.number,
    img: PropTypes.string,
    price: PropTypes.number,
    inCart: PropTypes.bool,
  }).isRequired
};
</code>```

Using these features will greatly reduce the amount of time spent debugging applications.
   The shape function lets us declare objects with nested properties and, for each one of those, we can define their types.

If you realize that you are declaring too many props for a single component, and they are not related to each other, it may be better to create multiple components, each one with fewer props and responsibilities.

In the production version of React, the propTypes validation is disabled for performance reasons.

Title: PropTypes in React

Body:
In some examples, I have seen something like this:

Footer.propTypes = {
  completedCount: PropTypes.number.isRequired,
  activeCount: PropTypes.number.isRequired,
  filter: PropTypes.string.isRequired,
  onClearCompleted: PropTypes.func.isRequired,
  onShow: PropTypes.func.isRequired
}

What are these PropTypes really doing? Are they nice-to-have or must-have?

Body:
In React, you should write reusable components and to do that you have to define their interface in the clearest possible way.If you want your components to be reused across the application, it is crucial to make sure that our components and their parameters are well-defined and straightforward to use. You  ALWAYS HAVE TO VALIDATE your data.

Let's imagine you have an ecommerce website and you want to display your products in your homepage. For this, you need to create Product component and inside of it, you have to validate the data to prevent yourself displaying "true" where you want to display "number" for price. Here is an example:

Product.propTypes = {
  product: PropTypes.shape({
    id: PropTypes.number,
    img: PropTypes.string,
    price: PropTypes.number,
    inCart: PropTypes.bool,
  }).isRequired
};

Using these features will greatly reduce the amount of time spent debugging applications.
   The shape function lets us declare objects with nested properties and, for each one of those, we can define their types.

If you realize that you are declaring too many props for a single component, and they are not related to each other, it may be better to create multiple components, each one with fewer props and responsibilities.

In the production version of React, the propTypes validation is disabled for performance reasons.


问:
Getting an "Internal Service Exception" when trying to run an extremely basic AWS-glue crawler with a large number of columns
I'm trying to do some POC-testing by getting S3 parquet files to be queryable through Athena.

I'm starting with something pretty basic: a single parquet file, with around 400 rows and about 800 columns (this is an unusual storage system I know; but for business logic reasons there aren't a ton of other options)

This seems to fail when I try to run a glue crawler across it, with a generic Internal Service Exception error.

I tried the same thing with a smaller number of columns (everything else the same) and low and behold, it worked. Is this some sort of limitation I'm unaware of?

Any help would be appreciated.

答: Okay, this was ultimately resolved. It turns out that glue didn't like some funky characters in my column names (a few contained \r). I wish this error was more obvious, but for future people it may be helpful to simplify your columns names and try again</p>


问:
SSIS EXECUTE TASK not working as expected through sqlserver agent
I have created a SSIS Execute Task package to export CSV and write into d:/ drive
It works when i execute from SSIS.However when i run from SQLServer agent, the job shows sucess but the export file is not available in the location
Can anyone please advise if anything i am missing.
Thank you</p>

答:
I think that the issue is that the SQL agent doesn't have access to the file system location. Make sure that SQL service account has needed permissions:

Configure File System Permissions for Database Engine Access


问:
Configuration .net core web application and webapi on IIS
I'm in progress a create my web application (WebUI) and webapi (WebApi). In ASP.Net I have always worked that way create web application on IIS with path to result debug folder, and WebApi as web application inside webside. In Visual Studio attach process w3wp.exe and I could debug the code. I would like to achieve the same effect now.

Now I have WebUI (Web application .net Core 2.2) and WebApi (web api .net Core 2.2). In IIS add new Site (path to WebUi Debug folder) and inside create application (path to WebApi Debug folder)

my routing

```<code>[Route("api/v1/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
</code>```

Desired effect:

http://localhost:8100/ - website

http://localhost:8100/webapi/api/v1/values - endpoint webapi

website it works but WebApi not. I need to use site and api at the same time. When I run Web Api in Visual Studio web Api work correct. Any advice or a better idea for debug in the same time? Everything work fine when application web api in iis navigate to publish webapi.

答:
Try this in RouteConfig.cs.

```<code>routes.MapRoute(
    name: "Home",
    url: "",
    defaults: new { controller = "Home", action = "Index" }
);
</code>```

And for api routes in WebAPiConfig.cs

```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

On the other hand you can define route directly in Api Controller like this.

```<code>[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    [Route("webapi/api/v1/values")]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
}
</code>```

Good luck.

Body:
I'm in progress a create my web application (WebUI) and webapi (WebApi). In ASP.Net I have always worked that way create web application on IIS with path to result debug folder, and WebApi as web application inside webside. In Visual Studio attach process w3wp.exe and I could debug the code. I would like to achieve the same effect now.

Now I have WebUI (Web application .net Core 2.2) and WebApi (web api .net Core 2.2). In IIS add new Site (path to WebUi Debug folder) and inside create application (path to WebApi Debug folder)

my routing

[Route("api/v1/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

Desired effect:

http://localhost:8100/ - website

http://localhost:8100/webapi/api/v1/values - endpoint webapi

website it works but WebApi not. I need to use site and api at the same time. When I run Web Api in Visual Studio web Api work correct. Any advice or a better idea for debug in the same time? Everything work fine when application web api in iis navigate to publish webapi.

Body:
Try this in RouteConfig.cs.

routes.MapRoute(
    name: "Home",
    url: "",
    defaults: new { controller = "Home", action = "Index" }
);

And for api routes in WebAPiConfig.cs

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

On the other hand you can define route directly in Api Controller like this.

[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    [Route("webapi/api/v1/values")]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

Good luck.


问:
Alternative eval() to execute the string
My array is A=['Apple','Peach','Orange']in Javascript, someone pass me the string like "A[1]" , how to convert the string "A[1]" to an executable item, so I can get 'Peach' as the result.

eval(A[1]) used to work but is not allowed here.

答:
You could split by apostrophe and then filter out the odd array members:

var arrayString = "A=['Apple','Peach','Orange']"
var parsed = arrayString.split("'").filter(function(a, b){return b % 2});
console.log(parsed)```


问:
Send learners reminder email and admin
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"

I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.

the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.

I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.

```<code>    <?php
include 'db.php';

function check_emailaddress($email) {
    // First, we check that there is one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
    {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
    {
        if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
        {
            return false;
        }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
    {
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
        {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++)
        {
        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
        {
            return false;
        }
        }
    }
    return true;
}

$extraParam = "";
if (isset($_GET["ex"]) ) {
  $extraParam = $_GET["ex"]."---";
}

//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail;    //"From: info@visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6@gmail.com";
$email_to = "" ;//"respite@safeguards-training.net";

$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;

if ($usetemplate == 0) exit;            // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info@visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;

$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                  WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                  AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                  AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");

$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){

    $fn = $email_row->a01FirstName;
    $email = $email_row->a01Email;
    $password = $email_row->a002password;

    if ($pre_email == $email){
        $course .= "web url" . $email_row->a03CourseName . "</a><br>";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }else{
        $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
        $course = "web url" . $email_row->a03CourseName . "</a><br>";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }

}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

array_shift($nofinish);

set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;

foreach($nofinish as $no){
    $email_from = $from;
    $email_address = $no['email'];

//  $email_address = "lyan3000@gmail.com";
//  if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
    $email_subject = "Course Completion Reminder";

    $top = "<div style='font-family:Arial'>";
    $top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";

    $variable = array(
        '{$firstname}' => $no['firstname'],
        '{$course}' => $no['courses'],
        '{$password}'=> $no['password'],
        '{$email}'=> $no['email']
      );
    $email_body = strtr($eb1, $variable);

    $bottom = "<p><img src='cid:logoimg'></p>";
    $bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
    $email_message = $top . $email_body . $bottom;
/*
    echo $email_from . "<br>";
    echo $email_address . "<br>";
    echo $email_subject . "<br>";
    echo $email_message;
    echo "<hr>";
*/

    if (mail($email_address, $email_subject, $email_message, $email_from))
    {
        //echo "Reminder email sent to: " . $no['firstname'] . "<br>";
        echo "Yes. <br>";
    }else{
        //echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
        echo "No. <br>";
    }

}

$file_name = "record_for_cron_expire_email.txt";

$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');

$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);

//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;

$variable = array(
    '{$learnerCourse}' => $learnercourse,
    '{$date}' => $date
  );
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);

//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
                    SET a04Status = 0
                    WHERE a04ExpirationDate <= '$expiredRightNow'
                    AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
</code>```

答:
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).

chances are you might be missing it.

have a look at this posts, that might help you.

mysqli fetch_all() not a valid function?

Title: Send learners reminder email and admin

Body:
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"

I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.

the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.

I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.

    <?php
include 'db.php';

function check_emailaddress($email) {
    // First, we check that there is one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
    {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
    {
        if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
        {
            return false;
        }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
    {
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
        {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++)
        {
        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
        {
            return false;
        }
        }
    }
    return true;
}

$extraParam = "";
if (isset($_GET["ex"]) ) {
  $extraParam = $_GET["ex"]."---";
}

//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail;    //"From: info@visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6@gmail.com";
$email_to = "" ;//"respite@safeguards-training.net";

$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;

if ($usetemplate == 0) exit;            // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info@visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;

$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                  WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                  AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                  AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.
$strSQL_expire");

$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){

    $fn = $email_row->a01FirstName;
    $email = $email_row->a01Email;
    $password = $email_row->a002password;

    if ($pre_email == $email){
        $course .= "web url" . $email_row->a03CourseName . "
";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }else{
        $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
        $course = "web url" . $email_row->a03CourseName . "
";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }

}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

array_shift($nofinish);

set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;

foreach($nofinish as $no){
    $email_from = $from;
    $email_address = $no['email'];

//  $email_address = "lyan3000@gmail.com";
//  if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
    $email_subject = "Course Completion Reminder";

    $top = "
";
    $top .= "

Service Centre

";

    $variable = array(
        '{$firstname}' => $no['firstname'],
        '{$course}' => $no['courses'],
        '{$password}'=> $no['password'],
        '{$email}'=> $no['email']
      );
    $email_body = strtr($eb1, $variable);

    $bottom = "

";
    $bottom .="

";
    $email_message = $top . $email_body . $bottom;
/*
    echo $email_from . "
";
    echo $email_address . "
";
    echo $email_subject . "
";
    echo $email_message;
    echo "
";
*/

    if (mail($email_address, $email_subject, $email_message, $email_from))
    {
        //echo "Reminder email sent to: " . $no['firstname'] . "
";
        echo "Yes.
";
    }else{
        //echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "
";
        echo "No.
";
    }

}

$file_name = "record_for_cron_expire_email.txt";

$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');

$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);

//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;

$variable = array(
    '{$learnerCourse}' => $learnercourse,
    '{$date}' => $date
  );
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);

//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
                    SET a04Status = 0
                    WHERE a04ExpirationDate <= '$expiredRightNow'
                    AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.
$strSQL_setExpire");
?>


问:
Which library is the best in php for making async requests
I have a lot of data, which I want to transfer to Logz.io.

Basically, the project is written in Laravel and I want to create an event manager  which will do all the job of logging info to  Logz.io. I need an advice about which library h is better to use , something like guzzle curl, which can help me to send logs info to logz.io in the  background. I mean, I don't want to wait until the request with data for logz.io will finish.

Thank you.

答:
PHP is not an async language. Laravel has a queue system that works out of the box.

Basically you put some jobs in a queue and another process (it can be also in another machine), run them. It will work well in your scenario because you don't need a real-time log collection but you can delegate it by few seconds.


答:
On each iteration of users.map() the user.contactDetails holds a reference to an object that you are storing in the new newUser.contactDetails. So both will refer to the same object on memory. On your particular case, you can solve this spreading the user.contactDetails into a new object (like a way of cloning it). But note this will only work for a 1-level deep object. You should search for deep-cloning if your structure is more complicated.

const countries = [{id:3,countryName:"UK"},{id:4,countryName:"Spain"},{id:6,countryName:"Germany"}];

const users = [{id :1,name:"Douglas Camp",dateOfBirth:"23-06-1984",contactDetails:{country:3,phone:"7373724997"}},{id :2,name:"Martin Stein",dateOfBirth:"19-08-1992",contactDetails:{country:6,phone:"3334343434"}},];

const usersData = users.map(user =>
{
    const newUser = {};
    newUser.name = user.name;
    newUser.contactDetails = {...user.contactDetails};
    newUser.contactDetails.countryName = "UK";
    return newUser;
});

const countriesData = countries.map(country =>
{
    const newCountry = {};
    newCountry.name = country.countryName;
    newCountry.continent = "Europe";
    return newCountry;
});

console.log("countries:", countries);
console.log("countriesData:",countriesData);
console.log("users:", users);
console.log("usersData:", usersData);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Title: why map() is mutating original objects in a nested array?

Body:
On each iteration of users.map() the user.contactDetails holds a reference to an object that you are storing in the new newUser.contactDetails. So both will refer to the same object on memory. On your particular case, you can solve this spreading the user.contactDetails into a new object (like a way of cloning it). But note this will only work for a 1-level deep object. You should search for deep-cloning if your structure is more complicated.

const countries = [{id:3,countryName:"UK"},{id:4,countryName:"Spain"},{id:6,countryName:"Germany"}];

const users = [{id :1,name:"Douglas Camp",dateOfBirth:"23-06-1984",contactDetails:{country:3,phone:"7373724997"}},{id :2,name:"Martin Stein",dateOfBirth:"19-08-1992",contactDetails:{country:6,phone:"3334343434"}},];

const usersData = users.map(user =>
{
    const newUser = {};
    newUser.name = user.name;
    newUser.contactDetails = {...user.contactDetails};
    newUser.contactDetails.countryName = "UK";
    return newUser;
});

const countriesData = countries.map(country =>
{
    const newCountry = {};
    newCountry.name = country.countryName;
    newCountry.continent = "Europe";
    return newCountry;
});

console.log("countries:", countries);
console.log("countriesData:",countriesData);
console.log("users:", users);
console.log("usersData:", usersData);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
How to add trace id to each logs in go micro service
I wanted to add trace id to logging done for each request to the micro service.I want this in similar as for springboot application we can set trace id in MDC and fetch it and use it while logging.

I have done some research and I found that MDC equivalent in go lang is context. So, I have set the trace id in my context. Now the problem is where ever I have to log with trace id ,I need to pass context to that function which is very ugly way. I am looking for a better solution for this problem.

```<code>func HandlerFunction(f gin.HandlerFunc) gin.HandlerFunc{
    return func(cxt *gin.Context) {
        reqraceId := cxt.Request.Header.Get("trace-id")
        requid , _ := uuid.NewRandom()

        if reqTraceId == "" {
            c.Request.Header.Set("trace-id", requid.String())
        }

        f(c)
    }
}
</code>```

答:
It might be worth reading up on context.Context particularly this article which has a section that says:

At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests.

TL;DR - it's fine to pass the context, but what's the best way?

There's two main patterns

Ask the context to give you a logger

Give the logger the context

Context can be used to store values:

```<code>context.WithValue(ctx, someKey, someValue)
</code>```

This means we can either do:

```<code>somepackage.Log(ctx).Info("hello world")
// or
sompackage.Info(ctx, "hello world")
</code>```

The implementation of these two sample APIs could interact with the context to retrieve the values required with out needing to worry about the extra information that would have been in MDC at any of the logging call sites.

Body:
I wanted to add trace id to logging done for each request to the micro service.I want this in similar as for springboot application we can set trace id in MDC and fetch it and use it while logging.

I have done some research and I found that MDC equivalent in go lang is context. So, I have set the trace id in my context. Now the problem is where ever I have to log with trace id ,I need to pass context to that function which is very ugly way. I am looking for a better solution for this problem.

func HandlerFunction(f gin.HandlerFunc) gin.HandlerFunc{
    return func(cxt *gin.Context) {
        reqraceId := cxt.Request.Header.Get("trace-id")
        requid , _ := uuid.NewRandom()

        if reqTraceId == "" {
            c.Request.Header.Set("trace-id", requid.String())
        }

        f(c)
    }
}

Body:
It might be worth reading up on context.Context particularly this article which has a section that says:

At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests.

TL;DR - it's fine to pass the context, but what's the best way?

There's two main patterns

Ask the context to give you a logger

Give the logger the context

Context can be used to store values:

context.WithValue(ctx, someKey, someValue)

This means we can either do:

somepackage.Log(ctx).Info("hello world")
// or
sompackage.Info(ctx, "hello world")

The implementation of these two sample APIs could interact with the context to retrieve the values required with out needing to worry about the extra information that would have been in MDC at any of the logging call sites.


问:
Ansible playbook - NPM Tasks are not running in parallel
I'm using Terraform to build AWS infra (100 spot instances) and Ansible to deploy some tasks on Ubuntu Linux (spot instances). In Ansible Playbook when I'm running npm install task (nodeJS), I see that only 5 machines are getting that task at the same time, then it continues to the next batch of 5 machines and so on. After 30 min Ansible is done performing the tasks.

Other tasks such as install service on machines goes fine which works in parallel.

```<code>- name: Wait 100 seconds, but only start checking after 5 seconds
  wait_for_connection:
    delay: 5
    timeout: 100

- name: Connect as jenkins slave - Create agent-label file
  copy:
    dest: "/home/ubuntu/jenkins-swarm/run-jenkins-agent-label"
    content: AGENTS_LABEL_{{ job_name }}_{{ build_number }}
  register: sout
#- debug: msg="{{ sout.stdout_lines }}"

- name: Connect as jenkins slave
  shell: |
    sudo service jenkins-agent start
    sudo service jenkins-agent status
  register: sout
- debug: msg="{{ sout.stdout_lines }}"

- name: Copy from S3 to FS (shared)
  shell: /home/{{ ansible_ssh_user }}/.local/bin/aws s3 sync "s3://automationtool/{{ job_name }}_{{ build_number }}" "/home/{{ ansible_ssh_user }}/src_temp"
  register: sout

- name: NPM install source on FS (shared)
  shell: |
    cd /home/{{ ansible_ssh_user }}/src_temp
    sudo npm install
  register: sout
- debug: msg="{{ sout.stdout_lines }}"
</code>```

I expect to see that all the machines (~100) are getting the task on the same time, and execute it

答:
To explain why you

see that only 5 machines are getting that task on the same time, then continue to the next 5 batch and so on. after 30 min the ansible is done to perfom the tasks

let me quote from Strategies:

By default, plays run with a linear strategy, in which all hosts will run each task before any host starts the next task, using the number of forks (default 5) to parallelize.

Set serial in the playbook

```<code>- hosts: all
  serial: "100%"
</code>```

to see that all the machines (~100) are getting the task on the same time, and executed it.

Other options are available in Delegation, Rolling Updates, and Local Actions and in ANSIBLE PERFORMANCE TUNING.

Body:
I'm using Terraform to build AWS infra (100 spot instances) and Ansible to deploy some tasks on Ubuntu Linux (spot instances). In Ansible Playbook when I'm running npm install task (nodeJS), I see that only 5 machines are getting that task at the same time, then it continues to the next batch of 5 machines and so on. After 30 min Ansible is done performing the tasks.

Other tasks such as install service on machines goes fine which works in parallel.

- name: Wait 100 seconds, but only start checking after 5 seconds
  wait_for_connection:
    delay: 5
    timeout: 100

- name: Connect as jenkins slave - Create agent-label file
  copy:
    dest: "/home/ubuntu/jenkins-swarm/run-jenkins-agent-label"
    content: AGENTS_LABEL_{{ job_name }}_{{ build_number }}
  register: sout
#- debug: msg="{{ sout.stdout_lines }}"

- name: Connect as jenkins slave
  shell: |
    sudo service jenkins-agent start
    sudo service jenkins-agent status
  register: sout
- debug: msg="{{ sout.stdout_lines }}"

- name: Copy from S3 to FS (shared)
  shell: /home/{{ ansible_ssh_user }}/.local/bin/aws s3 sync "s3://automationtool/{{ job_name }}_{{ build_number }}" "/home/{{ ansible_ssh_user }}/src_temp"
  register: sout

- name: NPM install source on FS (shared)
  shell: |
    cd /home/{{ ansible_ssh_user }}/src_temp
    sudo npm install
  register: sout
- debug: msg="{{ sout.stdout_lines }}"

I expect to see that all the machines (~100) are getting the task on the same time, and execute it

Body:
To explain why you

see that only 5 machines are getting that task on the same time, then continue to the next 5 batch and so on. after 30 min the ansible is done to perfom the tasks

let me quote from Strategies:

By default, plays run with a linear strategy, in which all hosts will run each task before any host starts the next task, using the number of forks (default 5) to parallelize.

Set serial in the playbook

- hosts: all
  serial: "100%"

to see that all the machines (~100) are getting the task on the same time, and executed it.

Other options are available in Delegation, Rolling Updates, and Local Actions and in ANSIBLE PERFORMANCE TUNING.


问:
looping through images and displaying associated image details
I have an edit page (for a car model) which loops through a list of images and display the description associated with each image in a text field where user can edit it.

My problem is that for each image, instead of displaying its associated description, all the descriptions associated with the car (and not that particular image) are displayed for each particular image. For e.g, if i have am editing a car details and this car has 3 images, each having a description. All 3 descriptions are displayed for each image, resulting in 9 descriptions field in all on my edit page.

```<code><% @car.images.each do | image | %>
<div class="car_photos">
  <%= image_tag(image.data.url(:thumb), :alt => '') %>
     <% f.fields_for :images do |builder| %>
       <%= render "imageEdit", :f => builder %>
     <% end %>
</div>
<% end unless @car.images.first.new_record? rescue nil %>
</code>```

_imageEdit.html.erb:

```<code><% f.fields_for :descriptions do |builder| %>
<p>Description:<%= builder.text_area :desc %></p>
<% end %>
</code>```

Any suggesion on how to solve this prob? Thanks

答:
Either do </p>

```<code><% f.fields_for :images, image do |builder| %>
</code>```

<p>or </p>

```<code><% f.fields_for image do |builder| %>
</code>```

Body:
I have an edit page (for a car model) which loops through a list of images and display the description associated with each image in a text field where user can edit it.

My problem is that for each image, instead of displaying its associated description, all the descriptions associated with the car (and not that particular image) are displayed for each particular image. For e.g, if i have am editing a car details and this car has 3 images, each having a description. All 3 descriptions are displayed for each image, resulting in 9 descriptions field in all on my edit page.

<% @car.images.each do | image | %>

  <%= image_tag(image.data.url(:thumb), :alt => '') %>
     <% f.fields_for :images do |builder| %>
       <%= render "imageEdit", :f => builder %>
     <% end %>

<% end unless @car.images.first.new_record? rescue nil %>

_imageEdit.html.erb:

<% f.fields_for :descriptions do |builder| %>

Description:<%= builder.text_area :desc %>

<% end %>

Any suggesion on how to solve this prob? Thanks

Body:
Either do

<% f.fields_for :images, image do |builder| %>

or

<% f.fields_for image do |builder| %>


问:
Plotting xscale with negative powers of 10 in matplotlib
Thanks in advance for taking the time to read my question. I'm having trouble plotting an array of negative powers of 10 in matplotlib

I have read through all of the log xscale options in the matplotlib documentation but to no avail. I have also read the following questions and some others which seemed similar but they did not end up helping me out:

Matplotlib: disable powers of ten in log plot

Plot Axis in Python with Log Scale for Negative Exponents of 10

Logscale plots with zero values in matplotlib *with negative exponents*

Logscale plots with zero values in matplotlib

This is more or less in simple form what my code looks like.

x = np array with 100 values of 0.99999, 0.9999, 0.999, 0.99

y = np array with corresponding evaluation outputs to be plotted.

```<code>plt.plot(x, y, 'o')
plt.xticks([0.99999,0.9999,0.999,0.99])
plt.gca().set_xscale('log')
</code>```

What I'm trying to attain is a plot with just the values 0.99999, 0.9999, 0.999, 0.99 evenly spaced on the x axis plotted against their corresponding y values.

Once again I would like to thank you so much for taking the time to read this question, and I sincerely hope you can help me out!

答:
You could easily "fake" this kind of plot, by plotting y against [0,1,2,3,...] and then replacing the xtickslabel with [0.9999,0.999,0.99,...]

```<code>x = [0.99999,0.9999,0.999,0.99]
y = [1,2,3,4]
fig, ax = plt.subplots()
ax.plot(range(len(x)),y, 'o-')
ax.set_xticks(range(len(x)))
ax.set_xticklabels(x)
</code>```

Body:
Thanks in advance for taking the time to read my question. I'm having trouble plotting an array of negative powers of 10 in matplotlib

I have read through all of the log xscale options in the matplotlib documentation but to no avail. I have also read the following questions and some others which seemed similar but they did not end up helping me out:

Matplotlib: disable powers of ten in log plot

Plot Axis in Python with Log Scale for Negative Exponents of 10

Logscale plots with zero values in matplotlib *with negative exponents*

Logscale plots with zero values in matplotlib

This is more or less in simple form what my code looks like.

x = np array with 100 values of 0.99999, 0.9999, 0.999, 0.99

y = np array with corresponding evaluation outputs to be plotted.

plt.plot(x, y, 'o')
plt.xticks([0.99999,0.9999,0.999,0.99])
plt.gca().set_xscale('log')

What I'm trying to attain is a plot with just the values 0.99999, 0.9999, 0.999, 0.99 evenly spaced on the x axis plotted against their corresponding y values.

Once again I would like to thank you so much for taking the time to read this question, and I sincerely hope you can help me out!

Body:
You could easily "fake" this kind of plot, by plotting y against [0,1,2,3,...] and then replacing the xtickslabel with [0.9999,0.999,0.99,...]

x = [0.99999,0.9999,0.999,0.99]
y = [1,2,3,4]
fig, ax = plt.subplots()
ax.plot(range(len(x)),y, 'o-')
ax.set_xticks(range(len(x)))
ax.set_xticklabels(x)