问:
FP alternative to polymorphism in JavaScript/ReactJS
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content"></div>
<div id="message"></div></code>```

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

答:
EDIT:

This is post is out of date. Hooks are better for most use cases.

Original Answer:

The answer regarding your example code is in the middle/bottom of this post.

A good way to go about React composition is the render-callback pattern, aka function-as-child. The main advantage it has over HOC's is that it allows you to compose components dynamically at runtime (e.g. in render) instead of statically at author time.

Regardless of whether you use render-callback or HOC's, the goal in component composition is to delegate reusable behavior to other components, and then pass those components in as props to the component that needs them.

Abstract example:

The following Delegator component uses the render-callback pattern to delegate implementation logic to an ImplementationComponent that is passed in as a prop:

```<code>const App = () => <Delegator ImplementationComponent={ImplementationB} />;

class Delegator extends React.Component {
  render() {
    const { ImplementationComponent } = this.props;

    return (
      <div>
        <ImplementationComponent>
          { ({ doLogic }) => {
            /* ... do/render things based on doLogic ... */
          } }
        </ImplementationComponent>
      </div>
    );
  }
}
</code>```

The various implementation components would look like:

```<code>class ImplementationA extends React.Component {

  doSomeLogic() { /* ... variation A ... */ }

  render() {
    this.props.children({ doLogic: this.doSomeLogic })
  }
}

class ImplementationB extends React.Component {

  doSomeLogic() { /* ... variation B ... */ }

  render() {
    this.props.children({ doLogic: this.doSomeLogic })
  }
}
</code>```

Later down the line, you could nest more child components in the Delegator component following the same compositional pattern:

```<code>class Delegator extends React.Component {
  render() {
    const { ImplementationComponent, AnotherImplementation, SomethingElse } = this.props;

    return (
      <div>
        <ImplementationComponent>
          { ({ doLogic }) => { /* ... */} }
        </ImplementationComponent>

        <AnotherImplementation>
          { ({ doThings, moreThings }) => { /* ... */} }
        </AnotherImplementation>

        <SomethingElse>
          { ({ foo, bar }) => { /* ... */} }
        </SomethingElse>
      </div>
    );
  }
}
</code>```

Now nested child component allows for multiple concrete implementations:

```<code>const App = () => (
  <div>
    <Delegator
      ImplementationComponent={ImplementationB}
      AnotherImplementation={AnotherImplementation1}
      SomethingElse={SomethingVariationY}
    />

    <Delegator
      ImplementationComponent={ImplementationC}
      AnotherImplementation={AnotherImplementation2}
      SomethingElse={SomethingVariationZ}
    />
  </div>
);
</code>```

Answer (your example):

Applying the above composition pattern to your example, the solution restructures your code but assumes that it needs to do the following:

allow variations of inputs and their validation logic

when user submits valid input, then do some ajax

Firstly, to make things easier I changed the DOM to:

```<code><div id="content-inputs"></div>
<div id="content-button"></div>
</code>```

Now, the TransferComponent knows only how to display a button and do something when the button is pressed and the data is valid. It doesn't know what inputs to display or how to validate the data. It delegates that logic to the nested VaryingComponent.

```<code>export default class TransferComponent extends React.Component {
  constructor() {
    super();
    this.displayDOMButton = this.displayDOMButton.bind(this);
    this.onButtonPress = this.onButtonPress.bind(this);
  }

  ajax(){
    console.log('doing some ajax')
  }

  onButtonPress({ isValid }) {
    if (isValid()) {
      this.ajax();
    }
  }

  displayDOMButton({ isValid }) {
    document.getElementById('content-button').innerHTML = (
      '<button id="button" type="button">Validate</button>'
    );

    document.getElementById('button')
      .addEventListener('click', () => this.onButtonPress({ isValid }));
  }

  render() {
    const { VaryingComponent } = this.props;
    const { displayDOMButton } = this;

    return (
      <div>
        <VaryingComponent>
          {({ isValid, displayDOMInputs }) => {
            displayDOMInputs();
            displayDOMButton({ isValid });
            return null;
          }}
        </VaryingComponent>
      </div>
    )
  }
};
</code>```

Now we create concrete implementations of the VaryingComponent to flesh out various input display and validation logics.

The username-only implementation:

```<code>export default class UsernameComponent extends React.Component {
  isValid(){
    return document.getElementById('username').value !== '';
  }

  displayDOMInputs() {
    document.getElementById('content-inputs').innerHTML = (
      '<input type="text" id="username" value="username"/>'
    );
  }

  render() {
    const { isValid, displayDOMInputs } = this;

    return this.props.children({ isValid, displayDOMInputs });
  }
}
</code>```

The username-and-password implementation:

```<code>export default class UsernamePasswordComponent extends React.Component {
  isValid(){
    return (
      document.getElementById('username').value !== '' &&
      document.getElementById('password').value !== ''
    );
  }

  displayDOMInputs() {
    document.getElementById('content-inputs').innerHTML = (
      '<input type="text" id="username" value="username"/>\n\
      <input type="text" id="password" value="password"/>\n'
    );
  }

  render() {
    const { isValid, displayDOMInputs } = this;

    return this.props.children({ isValid, displayDOMInputs });
  }
}
</code>```

Finally, composing instances of the TansferComponent would look like:

```<code><TransferComponent VaryingComponent={UsernameComponent} />
<TransferComponent VaryingComponent={UsernamePasswordComponent} />
</code>```

Body:
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

Body:
EDIT:

This is post is out of date. Hooks are better for most use cases.

Original Answer:

The answer regarding your example code is in the middle/bottom of this post.

A good way to go about React composition is the render-callback pattern, aka function-as-child. The main advantage it has over HOC's is that it allows you to compose components dynamically at runtime (e.g. in render) instead of statically at author time.

Regardless of whether you use render-callback or HOC's, the goal in component composition is to delegate reusable behavior to other components, and then pass those components in as props to the component that needs them.

Abstract example:

The following Delegator component uses the render-callback pattern to delegate implementation logic to an ImplementationComponent that is passed in as a prop:

const App = () => <Delegator ImplementationComponent={ImplementationB} />;

class Delegator extends React.Component {
  render() {
    const { ImplementationComponent } = this.props;

    return (
      <div>
        <ImplementationComponent>
          { ({ doLogic }) => {
            /* ... do/render things based on doLogic ... */
          } }
        </ImplementationComponent>
      </div>
    );
  }
}

The various implementation components would look like:

class ImplementationA extends React.Component {

  doSomeLogic() { /* ... variation A ... */ }

  render() {
    this.props.children({ doLogic: this.doSomeLogic })
  }
}

class ImplementationB extends React.Component {

  doSomeLogic() { /* ... variation B ... */ }

  render() {
    this.props.children({ doLogic: this.doSomeLogic })
  }
}

Later down the line, you could nest more child components in the Delegator component following the same compositional pattern:

class Delegator extends React.Component {
  render() {
    const { ImplementationComponent, AnotherImplementation, SomethingElse } = this.props;

    return (
      <div>
        <ImplementationComponent>
          { ({ doLogic }) => { /* ... */} }
        </ImplementationComponent>

        <AnotherImplementation>
          { ({ doThings, moreThings }) => { /* ... */} }
        </AnotherImplementation>

        <SomethingElse>
          { ({ foo, bar }) => { /* ... */} }
        </SomethingElse>
      </div>
    );
  }
}

Now nested child component allows for multiple concrete implementations:

const App = () => (
  <div>
    <Delegator
      ImplementationComponent={ImplementationB}
      AnotherImplementation={AnotherImplementation1}
      SomethingElse={SomethingVariationY}
    />

    <Delegator
      ImplementationComponent={ImplementationC}
      AnotherImplementation={AnotherImplementation2}
      SomethingElse={SomethingVariationZ}
    />
  </div>
);

Answer (your example):

Applying the above composition pattern to your example, the solution restructures your code but assumes that it needs to do the following:

allow variations of inputs and their validation logic

when user submits valid input, then do some ajax

Firstly, to make things easier I changed the DOM to:

<div id="content-inputs"></div>
<div id="content-button"></div>

Now, the TransferComponent knows only how to display a button and do something when the button is pressed and the data is valid. It doesn't know what inputs to display or how to validate the data. It delegates that logic to the nested VaryingComponent.

export default class TransferComponent extends React.Component {
  constructor() {
    super();
    this.displayDOMButton = this.displayDOMButton.bind(this);
    this.onButtonPress = this.onButtonPress.bind(this);
  }

  ajax(){
    console.log('doing some ajax')
  }

  onButtonPress({ isValid }) {
    if (isValid()) {
      this.ajax();
    }
  }

  displayDOMButton({ isValid }) {
    document.getElementById('content-button').innerHTML = (
      '<button id="button" type="button">Validate</button>'
    );

    document.getElementById('button')
      .addEventListener('click', () => this.onButtonPress({ isValid }));
  }

  render() {
    const { VaryingComponent } = this.props;
    const { displayDOMButton } = this;

    return (
      <div>
        <VaryingComponent>
          {({ isValid, displayDOMInputs }) => {
            displayDOMInputs();
            displayDOMButton({ isValid });
            return null;
          }}
        </VaryingComponent>
      </div>
    )
  }
};

Now we create concrete implementations of the VaryingComponent to flesh out various input display and validation logics.

The username-only implementation:

export default class UsernameComponent extends React.Component {
  isValid(){
    return document.getElementById('username').value !== '';
  }

  displayDOMInputs() {
    document.getElementById('content-inputs').innerHTML = (
      '<input type="text" id="username" value="username"/>'
    );
  }

  render() {
    const { isValid, displayDOMInputs } = this;

    return this.props.children({ isValid, displayDOMInputs });
  }
}

The username-and-password implementation:

export default class UsernamePasswordComponent extends React.Component {
  isValid(){
    return (
      document.getElementById('username').value !== '' &&
      document.getElementById('password').value !== ''
    );
  }

  displayDOMInputs() {
    document.getElementById('content-inputs').innerHTML = (
      '<input type="text" id="username" value="username"/>\n\
      <input type="text" id="password" value="password"/>\n'
    );
  }

  render() {
    const { isValid, displayDOMInputs } = this;

    return this.props.children({ isValid, displayDOMInputs });
  }
}

Finally, composing instances of the TansferComponent would look like:

<TransferComponent VaryingComponent={UsernameComponent} />
<TransferComponent VaryingComponent={UsernamePasswordComponent} />


来源: stackexchange

问:
Implementing security on the chip level
With Intel's recent purchase of a well known security company, I'm starting to think about what software w/could be more secure on a chip level. Examples I've come up with are:

Random number generation

Encryption

Memory protection

But is hardware level security any more secure than software based security? ( I would assume garbage in garbage out no matter what level you operate at) What are the design considerations for embedded security? What are the limitations? Finally, do you have any good resources for learning more about the topic?

答:
Although this thread is pretty old, I came across a paper about Intel Secure Key that describes its random number generation, security, and performance aspects.  The full paper is here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120), but the non-paywalled version is here (https://arxiv.org/abs/1707.02212).

In short, the best technology we have for random number generation is Intel Secure Key, which uses the RdRand and RdSeed instruction sets.  It is a cryptographically-secure pseudorandom number generator that uses an on-chip entropy source to randomly seed the number generator.  Its fully compliant with up-to-date security specs such as NIST SP800-90Ar1/B/C, FIPS-140-2, and ANSI X9.82.

ContentLicense: CC BY-SA 2.5

Title: Implementing security on the chip level

ContentLicense: CC BY-SA 3.0


问:
Error out of Package If Not Following Specific Design
So I've encountered an interesting situation with importing a flat text file (using commas as a delimiter) into a table in my DB

The file is really very simple and the only reason I caught this strange situation was because I wanted to test out some error logging tid bits if the package failed.

When trying to purposely crash my package, I took my text file and started putting in random commas in places they shouldn't be and creating random headers that weren't initially defined.  Strangely enough they all imported without issue!

The approved file that should be going through and importing into the system looks something like this

```<code>Col1, Col2, Col3
Data1, Data2, Data3
...
</code>```

The agreed upon file should ALWAYS be 3 columns with all columns currently being Strings.

When I tried to break my package by doing some of the following

```<code>Col1, Col2, Col3, TESTBREAKHDR
Data1, Data2, Data3
...

Col1, Col2, Col3
Data1, Data2, Data3, TESTBREAKDATA
...
</code>```

The header was simply disregarded and the data shifted over and was concatenated into the last row.

To me these are errors I want to catch and NOT proceed to do any kind of import.  Since these files are being generated somewhere else and just being picked up by my package for consumption - rather than trying to fix the file before hand (since some investigative work will need to be done prior to fixing) - I want it to simply error out and not proceed with any importing.

Any helpful tips or pointers would be greatly appreciated!

答:
When adding extra columns in the header, if you are using a Flat File Source to read from the Flat File Connection Manager, when package is executed. The Flat File Source will throw an exception, alerting you that metadata needs to be updated and that validation is failed.

When extra columns are found in data rows. you can Add a script component in the Data Flow Task, and for each row check if Col3  contains commas ,. If so throw exception.

The extra information in rows will not throw error on validation only if the data length of column is exceeded.

Note: as you said, the flat file connection manager doesn't detect extra columns in data rows, it will concatenate them in the last column

Body:
So I've encountered an interesting situation with importing a flat text file (using commas as a delimiter) into a table in my DB

The file is really very simple and the only reason I caught this strange situation was because I wanted to test out some error logging tid bits if the package failed.

When trying to purposely crash my package, I took my text file and started putting in random commas in places they shouldn't be and creating random headers that weren't initially defined.  Strangely enough they all imported without issue!

The approved file that should be going through and importing into the system looks something like this

Col1, Col2, Col3
Data1, Data2, Data3
...

The agreed upon file should ALWAYS be 3 columns with all columns currently being Strings.

When I tried to break my package by doing some of the following

Col1, Col2, Col3, TESTBREAKHDR
Data1, Data2, Data3
...

Col1, Col2, Col3
Data1, Data2, Data3, TESTBREAKDATA
...

The header was simply disregarded and the data shifted over and was concatenated into the last row.

To me these are errors I want to catch and NOT proceed to do any kind of import.  Since these files are being generated somewhere else and just being picked up by my package for consumption - rather than trying to fix the file before hand (since some investigative work will need to be done prior to fixing) - I want it to simply error out and not proceed with any importing.

Any helpful tips or pointers would be greatly appreciated!


问:
Can't get my Google Maps supportMapFragment to have layout width/height to "match_parent"
I can't seem to get my Google Maps to stay at "match_parent" in layout width/height.

The following is how I want it to stay:

```<code>xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myname.myapp.MapsActivity" >

<fragment

    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

 </android.support.constraint.ConstraintLayout>
</code>```

As soon as I click "preview" or "design" in Android Studio text, the following happens:

```<code><fragment

    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="395dp"
    android:layout_height="643dp"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"
</code>```

The code just transforms into the above, and I don't need this. This above code doesn't fit the entire screen, there's a lot of white space on all corners left. It looks like the following:

Even if I constraint the view to the screen, this is as big as it gets, so there will still be this white space on all sides.

How do I make it "match_parent" on layout_width and layout_height without it "fixing" itself?

答:
Try giving the following layout:</p>

```<code><android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.myname.myapp.MapsActivity" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I can't seem to get my Google Maps to stay at "match_parent" in layout width/height.

The following is how I want it to stay:

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myname.myapp.MapsActivity" >

<fragment

    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

 </android.support.constraint.ConstraintLayout>

As soon as I click "preview" or "design" in Android Studio text, the following happens:

<fragment

    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="395dp"
    android:layout_height="643dp"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"

The code just transforms into the above, and I don't need this. This above code doesn't fit the entire screen, there's a lot of white space on all corners left. It looks like the following:

Even if I constraint the view to the screen, this is as big as it gets, so there will still be this white space on all sides.

How do I make it "match_parent" on layout_width and layout_height without it "fixing" itself?

Body:
Try giving the following layout:

<android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.myname.myapp.MapsActivity" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>


问:
Why doesn't perfect forwarding (catch-all) work to implement a copy-assignment?
In a class with a series of ctors (most of which have exactly one argument), I want all one-argument ctors to also be mirrored by a corresponding assignment operator. The ctors include, but are not limited to a copy-ctor and a move-ctor. So this, should satisfy the rule-of-five.

```<code>  template <typename T>
  object& operator=(T&& from) {
    // ...
    return *this;
  }
</code>```

Here is a minimal example: https://ideone.com/OKprcr (thanks to @Daniel H for pointing out constness).

The error I get is

```<code>error: object of type 'object' cannot be assigned because its copy assignment operator is implicitly deleted
...
note: copy assignment operator is implicitly deleted because 'object' has a user-declared move constructor
</code>```

Why doesn't the function template implement the copy-assignment operator?

答:
Why doesn't the function template implement the copy-assignment operator?

Because the standard says so ([class.copy.assign]/1):

A user-declared copy assignment operator X::operator= is a non-static non-template member function of
  class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.

Note there's no X&& in there either.

Body:
In a class with a series of ctors (most of which have exactly one argument), I want all one-argument ctors to also be mirrored by a corresponding assignment operator. The ctors include, but are not limited to a copy-ctor and a move-ctor. So this, should satisfy the rule-of-five.

  template <typename T>
  object& operator=(T&& from) {
    // ...
    return *this;
  }

Here is a minimal example: https://ideone.com/OKprcr (thanks to @Daniel H for pointing out constness).

The error I get is

error: object of type 'object' cannot be assigned because its copy assignment operator is implicitly deleted
...
note: copy assignment operator is implicitly deleted because 'object' has a user-declared move constructor

Why doesn't the function template implement the copy-assignment operator?


问:
Testing for a deadlock with nUnit
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

答:
Take a look at the Microsoft Project called "Chess".
It is designed to find concurred bugs http://research.microsoft.com/en-us/projects/chess/</p>

OwnerDisplayName: frou

Title: Testing for a deadlock with nUnit

OwnerDisplayName: Martin Moser


问:
how to know uiwebview's progress
I have a webview which hits a website with 3 or 4 frames. I am not able to find the real end of the page loading. Is there is way to find out the progress of the webpage downloading precisely ?</p>

答: Have a look at the UIWebViewDelegate documentation. You can find out when the UIWebView finishes loading with -webViewDidFinishLoad: Other than that, I think you're pretty limited to the API's available in UIWebView and UIWebViewDelegate.

Title: how to know uiwebview's progress


问:
system("foo.exe") requires to close foo in order to continue my program
I don't know if my question is clear, let me explain.

I call this in my main() function:

```<code>system("foo.exe")
</code>```

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

```<code>system("taskkill /F /im foo.exe")
</code>```

But it doesn't work.

Does anyone have an idea what to do?

答:
If you are hoping for this to work:

```<code> system("foo.exe");
 system("taskkill /F /im foo.exe");
</code>```

it can't because the second call will only take place once the first execution of foo.exe terminates. If for some reason you need to start a process, and then later kill it before it would naturally terminate (and you probably really don't want to do that), you need to look at the more sophisticated Windows process control APIs, beginning with CreateProcess.

Body:
I don't know if my question is clear, let me explain.

I call this in my main() function:

system("foo.exe")

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

system("taskkill /F /im foo.exe")

But it doesn't work.

Does anyone have an idea what to do?

Body:
If you are hoping for this to work:

 system("foo.exe");
 system("taskkill /F /im foo.exe");

it can't because the second call will only take place once the first execution of foo.exe terminates. If for some reason you need to start a process, and then later kill it before it would naturally terminate (and you probably really don't want to do that), you need to look at the more sophisticated Windows process control APIs, beginning with CreateProcess.


问:
Difference between Boolean(x) and !!x
Using JavaScript, is there any difference between

```<code>Boolean(x)
</code>```

and

```<code>!!x
</code>```

?

答:
What's also an interesting difference between them is that you are able to explicitly pass Boolean as an callback inside Array#filter function, while if you would like to use !!, you'd would firstly have to set a callback function and then return it.

.filter(Boolean) ✓

.filter(!!) ✕

.filter((x) => !!x) ✓ (can be simplified, though - .filter((x) => x))

Title: Difference between Boolean(x) and !!x

Body:
Using JavaScript, is there any difference between

Boolean(x)

and

!!x

?


问:
How to pause a for loop and waiting for user input matplotlib
Sorry  my question title is not very easy to read through.

This is my problem.

I am trying to take a picture file and loop through every pixel.

On each pixel I want to display a matplotlib figure of the image of the pixel file (done.)

Once the figure is displayed I need my loop to pause while the user classifies the color of the pixel by either pressing 'b' or 'c' and then closes the figure with the space bar.

Once this operation is done I want it to load the next pixel.  However the issue I am having is the for loop doesn't pause.  If I put a while loop inside the for loop the figure doesn't ever finish loading (stays as a white screen and the mouse turns to the loading circle when scrolling over it).

I am new to event handling so maybe I am missing some way to do this there.

I also cannot get anything with matplotlibs interactive mode to work.

Below is my code, it is very rough I have only been working on it since this morning.  The only method in the class being used is init().

```<code>from scipy.misc import imread
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

class images(object):

def __init__(self,img,flat=False,mod='RGB',show=True):
    'File types to compare to'
    file_type_list =['.jpg','.bmp','.gif','.png']
    'Create assertion error if not right fiel type'
    assert(any(img[-4:] for x in file_type_list)),"Wrong file formate please use: JPEG, BMP, GIF, or PNG"
    'Read image file to numpy array'
    self.img=imread(img,flatten=flat,mode=mod)
    'Show image in matplotlib plot if selected by user'
    if show == True:
        fig, ax = plt.subplots()
        ax.imshow(self.img)

def arr_to_vector(self):
    'Convert 3D image array into 2D vector [no. pixels,3(RGB)]'
    self.img_vector = self.img.reshape(-1,self.img.shape[2])
    return self.img_vector

def gray_vector(self):
    'Convert 3D image array into 1D vector [no. pixels in grayscale]'
    img_vector = self.img.reshape(-1,self.img.shape[2])
    self.g_img_vector = np.mean(img_vector,axis=1)
    return self.g_img_vector

def plotter(self):
    self.fig = plt.figure()
    plt.imshow(self.img)

def disp_pixel(i):
    tmp = allsamecolor(Img.img,i)
    fig = plt.figure()
    plt.imshow(tmp)
    plt.show()
    cid = fig.canvas.mpl_connect('key_press_event',on_key)
    return fig.number, fig

def on_key(event):
    if event.key == ' ':
        plt.close(event.canvas.figure)
        return event.key
    else:
        if event.key == 'b':
            print(event.key)
            labels.append('black')
        elif event.key == 'c':
            print(event.key)
            labels.append('copper')

def assign(x,i):
    x = i
    return x

def allsamecolor(img, i):
    fv = np.vectorize(assign)
    ret = fv(img,i)
    return ret

img = 'C:/Temp/test.jpg'

Img = images(img,show=False)

v = Img.arr_to_vector()

labels = []

n = 0
for i in v:
    x, fig = disp_pixel(i)
    print(x)
    input("Press <ENTER> to continue")
</code>```

答:
The following would be an example of an updating figure, where new images are shown each time the user presses Space. The user then needs to press either b or r depending on whether he sees more blue or more red in the picture. The user input is stored, as well as the mean values of the image. After completion of N images, the result is visualized as a graph.

The idea behind this is to show that the complete code can run inside the plotting window's event loop.

```<code>import numpy as np
import matplotlib.pyplot as plt

class Quest():
    def __init__(self, N = 5, bias=0):
        self.bias = bias
        self.N = N
        self.resImage = np.zeros(self.N)
        self.resUser  = np.zeros(self.N)
        self.mapping = {"b" : -1,"r" : 1}

    def start(self):
        self.fig, self.ax = plt.subplots()
        self.i = 0
        self.im = self.ax.imshow(np.zeros((3,3)), norm=plt.Normalize(-1,1),cmap="bwr")
        self.cid = self.fig.canvas.mpl_connect("key_press_event", self.user_input)
        self.next_image()
        plt.show()

    def next_image(self):
        im = self.generate_image()
        self.resImage[self.i] = im.mean()
        self.im.set_data(im)
        self.fig.canvas.draw_idle()

    def user_input(self, event=None):
        if event.key == ' ':
            if self.i < self.N-1:
                self.i += 1
                self.next_image()
            else:
                self.show_result()
        elif event.key in self.mapping.keys():
            self.resUser[self.i] = self.mapping[event.key.lower()]
        else:
            return

    def show_result(self):
        self.ax.clear()
        self.ax.scatter(range(self.N), self.resImage, label="images")
        self.ax.scatter(range(self.N), self.resUser, label="user")
        self.ax.axhline(self.bias, color="k")
        self.ax.legend()
        self.fig.canvas.draw_idle()

    def generate_image(self):
        return np.random.normal(self.bias,0.7, size=(3,3))

q = Quest()
q.start()
</code>```

Body:
Sorry  my question title is not very easy to read through.

This is my problem.

I am trying to take a picture file and loop through every pixel.

On each pixel I want to display a matplotlib figure of the image of the pixel file (done.)

Once the figure is displayed I need my loop to pause while the user classifies the color of the pixel by either pressing 'b' or 'c' and then closes the figure with the space bar.

Once this operation is done I want it to load the next pixel.  However the issue I am having is the for loop doesn't pause.  If I put a while loop inside the for loop the figure doesn't ever finish loading (stays as a white screen and the mouse turns to the loading circle when scrolling over it).

I am new to event handling so maybe I am missing some way to do this there.

I also cannot get anything with matplotlibs interactive mode to work.

Below is my code, it is very rough I have only been working on it since this morning.  The only method in the class being used is init().

from scipy.misc import imread
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

class images(object):

def __init__(self,img,flat=False,mod='RGB',show=True):
    'File types to compare to'
    file_type_list =['.jpg','.bmp','.gif','.png']
    'Create assertion error if not right fiel type'
    assert(any(img[-4:] for x in file_type_list)),"Wrong file formate please use: JPEG, BMP, GIF, or PNG"
    'Read image file to numpy array'
    self.img=imread(img,flatten=flat,mode=mod)
    'Show image in matplotlib plot if selected by user'
    if show == True:
        fig, ax = plt.subplots()
        ax.imshow(self.img)

def arr_to_vector(self):
    'Convert 3D image array into 2D vector [no. pixels,3(RGB)]'
    self.img_vector = self.img.reshape(-1,self.img.shape[2])
    return self.img_vector

def gray_vector(self):
    'Convert 3D image array into 1D vector [no. pixels in grayscale]'
    img_vector = self.img.reshape(-1,self.img.shape[2])
    self.g_img_vector = np.mean(img_vector,axis=1)
    return self.g_img_vector

def plotter(self):
    self.fig = plt.figure()
    plt.imshow(self.img)

def disp_pixel(i):
    tmp = allsamecolor(Img.img,i)
    fig = plt.figure()
    plt.imshow(tmp)
    plt.show()
    cid = fig.canvas.mpl_connect('key_press_event',on_key)
    return fig.number, fig

def on_key(event):
    if event.key == ' ':
        plt.close(event.canvas.figure)
        return event.key
    else:
        if event.key == 'b':
            print(event.key)
            labels.append('black')
        elif event.key == 'c':
            print(event.key)
            labels.append('copper')

def assign(x,i):
    x = i
    return x

def allsamecolor(img, i):
    fv = np.vectorize(assign)
    ret = fv(img,i)
    return ret

img = 'C:/Temp/test.jpg'

Img = images(img,show=False)

v = Img.arr_to_vector()

labels = []

n = 0
for i in v:
    x, fig = disp_pixel(i)
    print(x)
    input("Press <ENTER> to continue")

Body:
The following would be an example of an updating figure, where new images are shown each time the user presses Space. The user then needs to press either b or r depending on whether he sees more blue or more red in the picture. The user input is stored, as well as the mean values of the image. After completion of N images, the result is visualized as a graph.

The idea behind this is to show that the complete code can run inside the plotting window's event loop.

import numpy as np
import matplotlib.pyplot as plt

class Quest():
    def __init__(self, N = 5, bias=0):
        self.bias = bias
        self.N = N
        self.resImage = np.zeros(self.N)
        self.resUser  = np.zeros(self.N)
        self.mapping = {"b" : -1,"r" : 1}

    def start(self):
        self.fig, self.ax = plt.subplots()
        self.i = 0
        self.im = self.ax.imshow(np.zeros((3,3)), norm=plt.Normalize(-1,1),cmap="bwr")
        self.cid = self.fig.canvas.mpl_connect("key_press_event", self.user_input)
        self.next_image()
        plt.show()

    def next_image(self):
        im = self.generate_image()
        self.resImage[self.i] = im.mean()
        self.im.set_data(im)
        self.fig.canvas.draw_idle()

    def user_input(self, event=None):
        if event.key == ' ':
            if self.i < self.N-1:
                self.i += 1
                self.next_image()
            else:
                self.show_result()
        elif event.key in self.mapping.keys():
            self.resUser[self.i] = self.mapping[event.key.lower()]
        else:
            return

    def show_result(self):
        self.ax.clear()
        self.ax.scatter(range(self.N), self.resImage, label="images")
        self.ax.scatter(range(self.N), self.resUser, label="user")
        self.ax.axhline(self.bias, color="k")
        self.ax.legend()
        self.fig.canvas.draw_idle()

    def generate_image(self):
        return np.random.normal(self.bias,0.7, size=(3,3))

q = Quest()
q.start()


问:
C#: How can I use a string to specify the Type (T) for a generic method?
I have some ugly code that looks something like this:

```<code>    switch (f.TypeName)
    {
        case "TypeOne":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeOne>), args);
            break;
        case "TypeTwo":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwo>), args);
            break;

        ...

        case "TypeTwenty":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwenty>), args);
            break;
    }
</code>```

I would really like to get rid of the switch statement and do something along these lines:

```<code>    var myTypeDescriptor = Type.GetType(f.TypeName); //<== clearly not this, but similar
    ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<myTypeDescriptor>), args);
</code>```

where MyMethod looks like this:

```<code>    protected void MyMethod<T>(object args)
    {
        ...
    }
</code>```

I've poked around some and have found a number of examples where the generic is a generic class, but no examples where it is a generic method.  And definitely not any examples where it is being passed to a delegate.

While this appears, at first glance, to be a duplicate of How do I use reflection to call a generic method?, I am not simply trying to call the method.  It is being passed to the WaitCallback delegate.  Perhaps this is a two part question:  1) how do I retrieve the generic method via reflection and 2) having obtained a handle to the method, how do I pass it as an argument to the WaitCallback delegate?

Anyone have any ideas?  Is this even possible?

答:
Hope this Helps. Instead of a string Just build a decorator to take in the Type that Queues the Item.

```<code>class Program
{
    static void Main(string[] args)
    {
        var arguments = new object();

        Execute<ObjectA>(args);
        Execute<ObjectB>(args);
        Execute<ObjectC>(args);
        Execute<ObjectA>(args);

        Console.ReadLine();
    }

    static void Execute<T>(object args) where T:BaseObject
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<T>), args);
    }

    static void MyMethod<T>(object args) where T:BaseObject
    {
        Console.WriteLine(typeof(T).FullName);
    }
}

public class BaseObject
{
}

public class ObjectA : BaseObject
{
}

public class ObjectB : BaseObject
{
}

public class ObjectC : BaseObject
{
}
</code>```

Body:
I have some ugly code that looks something like this:

    switch (f.TypeName)
    {
        case "TypeOne":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeOne>), args);
            break;
        case "TypeTwo":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwo>), args);
            break;

        ...

        case "TypeTwenty":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwenty>), args);
            break;
    }

I would really like to get rid of the switch statement and do something along these lines:

    var myTypeDescriptor = Type.GetType(f.TypeName); //<== clearly not this, but similar
    ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<myTypeDescriptor>), args);

where MyMethod looks like this:

    protected void MyMethod<T>(object args)
    {
        ...
    }

I've poked around some and have found a number of examples where the generic is a generic class, but no examples where it is a generic method.  And definitely not any examples where it is being passed to a delegate.

While this appears, at first glance, to be a duplicate of How do I use reflection to call a generic method?, I am not simply trying to call the method.  It is being passed to the WaitCallback delegate.  Perhaps this is a two part question:  1) how do I retrieve the generic method via reflection and 2) having obtained a handle to the method, how do I pass it as an argument to the WaitCallback delegate?

Anyone have any ideas?  Is this even possible?

Body:
Hope this Helps. Instead of a string Just build a decorator to take in the Type that Queues the Item.

class Program
{
    static void Main(string[] args)
    {
        var arguments = new object();

        Execute<ObjectA>(args);
        Execute<ObjectB>(args);
        Execute<ObjectC>(args);
        Execute<ObjectA>(args);

        Console.ReadLine();
    }

    static void Execute<T>(object args) where T:BaseObject
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<T>), args);
    }

    static void MyMethod<T>(object args) where T:BaseObject
    {
        Console.WriteLine(typeof(T).FullName);
    }
}

public class BaseObject
{
}

public class ObjectA : BaseObject
{
}

public class ObjectB : BaseObject
{
}

public class ObjectC : BaseObject
{
}


问:
Code generation in software development
First broader view : I got assignment for school project that states "Design and implement tool for rapid development of IS by code generation of core of business and data layer. (paraphrased). Its specific for .NET and C#, but anything is fine in this case.

I dont have that extensive knowledge of code generation or development of information systems. I was looking around some code generation framewroks and tools. More specificaly T4 and CodeSmith Generator. One thing that hit my eye is .netTiers set of templates, that have some interesting ones, that can be used in software development. But I dont know how much usefull in actual development they can be.

Well my question : Is there a way to develop an information system based mostly on code-generation? Or some way to make bigger use of code generation tools and templates in general? If I have this, I can work on more specific things.

I also tried to look at some questions here, that concert code-generation, but most of them are about if it is good or bad, or general experience with them. What I want is specific experience with specific tools and templates and how much profit in development they have.

Thanks a lot for answers.

答:
Code generation has its place, and its cost.

The C Preprocessor is a form of code generation. Most large C projects eventually develop into their own dialect of C, based on preproccessor macros.

And macros in assembly language are incredibly useful.

It's perfectly common to have parts of a project be generated, perhaps a Perl script creating a fast Sin/Cos lookup table expressed as an initialized C array, for an embedded system. Or some measured performance data file gets "built in" to the application to help estimate some cost or another.

In Java, it's common to use JAXB and such to generate classes based on an XML schema. (I suspect this is the closest to your question's intent, @Euphoric...)

Also various mechanisms to save the trouble of implementing a zillion getters and setters. (Poor, poor, Java.)

The cost is complexity. You have to manage the difference between "source code" and "generated code". If you see someone checking "generated code" into the "source code control system"... think hard if that's really the right thing!

Hopefully your Make or build system knows how to build the appropriate generated files & use them.

And certainly, some server systems even write and compile code on-the-fly, as they run. Me: I am scared of that! But I've never had to use it.

Title: Code generation in software development


问:
i made a function what is meant to check if the format of the date of birth the user enters is correct but i can't get it to work
```<code>def checkdob():
    while True:
        dob = input("Date of Birth")
        try:
            dob == datetime.datetime.strptime(dob, '%d-%m-%y')
            break
        except:
            print("Incorrect data format, should be DD-MM-YYYY")
checkdob()
</code>```

答:
You can try like this:</p>

```<code>def checkdob(dob):
    try:
        return datetime.datetime.strptime(dob, '%d-%m-%Y')
    except ValueError:
        print("Incorrect data format, should be DD-MM-YYYY")
        return None

while not checkdob(input("Date of Birth")):
    pass
</code>```

Body:
You can try like this:

def checkdob(dob):
    try:
        return datetime.datetime.strptime(dob, '%d-%m-%Y')
    except ValueError:
        print("Incorrect data format, should be DD-MM-YYYY")
        return None

while not checkdob(input("Date of Birth")):
    pass


问:
Cannot deduce template arguments for basic_string
I have this function definition in my code:

```<code>template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes)
{
     // do work ...
}
</code>```

And when I try to call the function like this:

```<code>int main()
{
    Bytes bytes{'H', 'e', 'l', 'l', 'o'};

    std::string str = bytes2string(bytes); // error

    return 0;
}
</code>```

I am met with the following error:

```<code>error:
      no matching function for call to 'bytes2string'

note:
  candidate template ignored: couldn't infer template argument 'CharT'
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes)
</code>```

I'm pretty sure it should work but alas, it doesn't. Also Bytes is just a std::vector<char> in case anyone wanted to know.

答:
Look closely at your signature:

```<code>template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes);
</code>```

There's nothing that allows CharT to be deduced - it needs to be explicitly supplied by the user.

```<code>std::string str = bytes2string(bytes);
</code>```

Unfortunately C++ doesn't have Hindley-Milner type inference - it is not possible to deduce template parameters of a return type in this way. Function template parameters can only be deduced via arguments passed to the function.

If you change your signature  to:

```<code>template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> void bytes2string(std::basic_string<CharT, Traits, Allocator>& out, const Bytes& bytes);
</code>```

And invoke:

```<code>std::string str;
bytes2string(str, bytes);
</code>```

Your template parameters will be deduced.

live example on wandbox

Body:
I have this function definition in my code:

template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes)
{
     // do work ...
}

And when I try to call the function like this:

int main()
{
    Bytes bytes{'H', 'e', 'l', 'l', 'o'};

    std::string str = bytes2string(bytes); // error

    return 0;
}

I am met with the following error:

error:
      no matching function for call to 'bytes2string'

note:
  candidate template ignored: couldn't infer template argument 'CharT'
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes)

I'm pretty sure it should work but alas, it doesn't. Also Bytes is just a std::vector<char> in case anyone wanted to know.

Body:
Look closely at your signature:

template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> std::basic_string<CharT, Traits, Allocator> bytes2string(const Bytes& bytes);

There's nothing that allows CharT to be deduced - it needs to be explicitly supplied by the user.

std::string str = bytes2string(bytes);

Unfortunately C++ doesn't have Hindley-Milner type inference - it is not possible to deduce template parameters of a return type in this way. Function template parameters can only be deduced via arguments passed to the function.

If you change your signature  to:

template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> void bytes2string(std::basic_string<CharT, Traits, Allocator>& out, const Bytes& bytes);

And invoke:

std::string str;
bytes2string(str, bytes);

Your template parameters will be deduced.

live example on wandbox


问:
How to retrieve each value from string and add them to the list
This is my code so far in C#

```<code>string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
var tuple = new List<Tuple<int, int>>();
foreach (var value in myString)
{
    int startPos = myString.IndexOf("value:") + "value:".Length;
    int length = myString.LastIndexOf(", data") - startPos;
    string valuesX = myString.Substring(startPos, length);
    int values = int.Parse(valuesX);
    int startPos2 = myString.IndexOf("data:") + "data:".Length;
    int length2 = myString.LastIndexOf(", end") - startPos2;
    string dataX = myString.Substring(startPos2, length2);
    int data = int.Parse(dataX);
    tuple.Add(Tuple.Create(values, data));
}
</code>```

I want to retrieve the value number and data number from string and put them into a list using integer data type

this picture demonstrates what I want to achieve:

The code simply does not work and I would appreciate any help, thank you

答:
1st you can't just loop through a string like that, you will need to split it.

Under the following assumptions:

The structure Value:#, Data:#, end never changes

The number for value and data are always integers

then the following will work.

```<code>string myString             = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
List<Tuple<int, int>> tuple = new List<Tuple<int, int>>();

// first split the string on commas so we have a collection to loop through
string[] splitString = myString.Split(',');

// Assuming the Value:#, Data:#, end structure, we can loop by 3 each time
for (int i = 0; i < splitString.Length; i = i+3)
{
    /* Assuming the above structure, we can be sure that
    * i = Value
    * i+1 = Data
    * i+2 = end - which we can ignore
    * all will be integers by assumption so no need to check, just parse
    * Always in string:# pattern so we split on : and take the second item
    */
    int value = Int32.Parse(splitString[i].Split(':')[1]);
    int data  = Int32.Parse(splitString[i + 1].Split(':')[1]);

    tuple.Add(Tuple.Create(value, data));
}
</code>```

Body:
This is my code so far in C#

string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
var tuple = new List<Tuple<int, int>>();
foreach (var value in myString)
{
    int startPos = myString.IndexOf("value:") + "value:".Length;
    int length = myString.LastIndexOf(", data") - startPos;
    string valuesX = myString.Substring(startPos, length);
    int values = int.Parse(valuesX);
    int startPos2 = myString.IndexOf("data:") + "data:".Length;
    int length2 = myString.LastIndexOf(", end") - startPos2;
    string dataX = myString.Substring(startPos2, length2);
    int data = int.Parse(dataX);
    tuple.Add(Tuple.Create(values, data));
}

I want to retrieve the value number and data number from string and put them into a list using integer data type

this picture demonstrates what I want to achieve:

The code simply does not work and I would appreciate any help, thank you

Body:
1st you can't just loop through a string like that, you will need to split it.

Under the following assumptions:

The structure Value:#, Data:#, end never changes

The number for value and data are always integers

then the following will work.

string myString             = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
List<Tuple<int, int>> tuple = new List<Tuple<int, int>>();

// first split the string on commas so we have a collection to loop through
string[] splitString = myString.Split(',');

// Assuming the Value:#, Data:#, end structure, we can loop by 3 each time
for (int i = 0; i < splitString.Length; i = i+3)
{
    /* Assuming the above structure, we can be sure that
    * i = Value
    * i+1 = Data
    * i+2 = end - which we can ignore
    * all will be integers by assumption so no need to check, just parse
    * Always in string:# pattern so we split on : and take the second item
    */
    int value = Int32.Parse(splitString[i].Split(':')[1]);
    int data  = Int32.Parse(splitString[i + 1].Split(':')[1]);

    tuple.Add(Tuple.Create(value, data));
}


问:
Why do you need functions such as these (*>) or (<*) if they discard the first or second argument?
The type signature of the function (*>) is such:

```<code>(*>) :: f a -> f b -> f b
</code>```

Sequence actions, discarding the value of the first argument.

Can someone please explain why this is useful?  Seems counter-intuitive if the first argument is discarded.

Please illustrate with examples.  Thanks.

答:
The "shape" of the discarded argument is still used.  Think of an Applicative f => f a value as having some values of type a arranged in some sort of shape made possible by the applicative functor f.  The operator <*> :: Applicative f => f (a -> b) -> f a -> f b combines the shapes of its first two arguments to come up with a third shape.  pure x always has a simple 'idenitity' shape that doesn't alter another shape.

The definitions for the two operators in question are equivalent to:

```<code>a <* b = pure (\x y -> x) <*> a <*> b
a *> b = pure (\x y -> y) <*> a <*> b
</code>```

pure expressions have an identity shape, which can be inferred from the first applicative law, pure id <*> v = v.  So when pure (\x y -> ...) <*> a is evaluated, its result has the same shape as a.  It's equivalent to fmap (\...) a, whose result also has the same shape as a.

Then when (pure (\x y -> ...) <*> a) <*> b is evaluated, its result will have the shape of a combined with b.

There are only two shapes values of Maybe a and Either a b can take.  They're not that interesting.

```<code>Prelude> :set +t
Prelude> Just 'x' <* Just (1::Int)
Just 'x'
it :: Maybe Char
Prelude> Just 'x' <* (Nothing :: Maybe Int)
Nothing
it :: Maybe Char
Prelude> (Nothing :: Maybe Char) <* Just (1::Int)
Nothing
it :: Maybe Char
Prelude> (Nothing :: Maybe Char) <* (Nothing :: Maybe Char)
Nothing
it :: Maybe Char
</code>```

For lists, the shape combination is easy to visualize.

```<code>Prelude> "ab" *> "123"
"123123"
Prelude> "ab" <* "123"
"aaabbb"
</code>```

Body:
The type signature of the function (*>) is such:

(*>) :: f a -> f b -> f b

Sequence actions, discarding the value of the first argument.

Can someone please explain why this is useful?  Seems counter-intuitive if the first argument is discarded.

Please illustrate with examples.  Thanks.

Body:
The "shape" of the discarded argument is still used.  Think of an Applicative f => f a value as having some values of type a arranged in some sort of shape made possible by the applicative functor f.  The operator <*> :: Applicative f => f (a -> b) -> f a -> f b combines the shapes of its first two arguments to come up with a third shape.  pure x always has a simple 'idenitity' shape that doesn't alter another shape.

The definitions for the two operators in question are equivalent to:

a <* b = pure (\x y -> x) <*> a <*> b
a *> b = pure (\x y -> y) <*> a <*> b

pure expressions have an identity shape, which can be inferred from the first applicative law, pure id <*> v = v.  So when pure (\x y -> ...) <*> a is evaluated, its result has the same shape as a.  It's equivalent to fmap (\...) a, whose result also has the same shape as a.

Then when (pure (\x y -> ...) <*> a) <*> b is evaluated, its result will have the shape of a combined with b.

There are only two shapes values of Maybe a and Either a b can take.  They're not that interesting.

Prelude> :set +t
Prelude> Just 'x' <* Just (1::Int)
Just 'x'
it :: Maybe Char
Prelude> Just 'x' <* (Nothing :: Maybe Int)
Nothing
it :: Maybe Char
Prelude> (Nothing :: Maybe Char) <* Just (1::Int)
Nothing
it :: Maybe Char
Prelude> (Nothing :: Maybe Char) <* (Nothing :: Maybe Char)
Nothing
it :: Maybe Char

For lists, the shape combination is easy to visualize.

Prelude> "ab" *> "123"
"123123"
Prelude> "ab" <* "123"
"aaabbb"


问:
Google App Engine Errors not showing up in StackDriver Error Reporting using Flask
I'm using Google App Engine standard environment to host a python-flask-application and I'm having issues to get the errors to show up in StackDriver Error Reporting. By default Google App Engine should log errors to StackDriver Error Reporting, but it doesn't.

I've had errors before that showed up in StackDriver Error Reporting, but I can't reproduce that. The errors seem to go straight to the Server-Errors section and not to the Application-Errors. But it seems logical to me that both are logged in StackDriver Error Reporting.

I did some debugging in order to get it working using routes /error and /500. The result was the following:

The errors show up in the Google App Engine overview:

Both are visible in the logs:

But nothing shows up in StackDriver Error Reporting:

Would anyone have an idea why this is the case?

UPDATE: I found that using the flask.logger seems to be the problem. Using logging works ok and ends up in StackDriver Error Reporting (except for some formatting issues). Both do end up in the logger though. I am using a logging.StreamHandler to register to flask.logger using addHandler. My best guess is that there is something wrong with the formatting of the logging.StreamHandler. Investigating further.

答:
After some digging and debugging using the Google App Engine SDK I found that there is a logging-handler for GAE:

```<code>google.appengine.api.app_logging.AppLogsHandler
</code>```

Google App Engine registers one to logging, but not to flask.logger. So if you use app.logger.error(my_error) for example, it won't register to StackDriver Error Reporting.

Now I register one manually which fixes the issue:

```<code>from google.appengine.api.app_logging import AppLogsHandler
app.logger.addHandler(AppLogsHandler())

app.logger.error(my_error)
</code>```

Body:
After some digging and debugging using the Google App Engine SDK I found that there is a logging-handler for GAE:

google.appengine.api.app_logging.AppLogsHandler

Google App Engine registers one to logging, but not to flask.logger. So if you use app.logger.error(my_error) for example, it won't register to StackDriver Error Reporting.

Now I register one manually which fixes the issue:

from google.appengine.api.app_logging import AppLogsHandler
app.logger.addHandler(AppLogsHandler())

app.logger.error(my_error)


答:
If the function is supposed to return std::string, then write it that way:

```<code>std::string bytes2string(const Bytes& bytes);
</code>```

If it's supposed to be able to produce arbitrary instantiations of std::basic_string then you need to supply the appropriate template arguments. Often that's done by passing in a string of the appropriate type. That doesn't seem appropriate here, since there is no obvious use for passing in a string other than to provide template arguments.

The alternative is to name the appropriate types at the point of the call:

```<code>std::string str = bytes2string<char>(bytes);
</code>```

Title: Cannot deduce template arguments for basic_string

Body:
If the function is supposed to return std::string, then write it that way:

std::string bytes2string(const Bytes& bytes);

If it's supposed to be able to produce arbitrary instantiations of std::basic_string then you need to supply the appropriate template arguments. Often that's done by passing in a string of the appropriate type. That doesn't seem appropriate here, since there is no obvious use for passing in a string other than to provide template arguments.

The alternative is to name the appropriate types at the point of the call:

std::string str = bytes2string<char>(bytes);


问:
Force Landscape when orientation is locked
I am building a video app. When a user rotates the device to landscape, the video takes over all of the screen and the UI changes. </p>

<p>Is there a way to 'force' landscape layout when the device is in portrait? For example, if the user has orientation lock we want to add a button to enter the landscape mode. The YouTube app has a button that does this. </p>

答:
Yes you can force it using this 2 lines of code, in your viewDidAppear

```<code>    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
</code>```

Body:
I am building a video app. When a user rotates the device to landscape, the video takes over all of the screen and the UI changes.

Is there a way to 'force' landscape layout when the device is in portrait? For example, if the user has orientation lock we want to add a button to enter the landscape mode. The YouTube app has a button that does this.

Body:
Yes you can force it using this 2 lines of code, in your viewDidAppear

    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")


问:
Transform rows of sequential dates into column of date range
I must turn observations that meet a condition, a binary flag, on certain dates into a table of observations with the date range that they meet the flag.

Sample data look like this:

```<code>id <- c(1001, 1001, 1001, 1002, 1002, 1002, 1003, 1003, 1003)
date <- c("2016-06-20", "2016-06-21", "2016-06-22", "2016-06-20",
          "2016-06-21", "2016-06-22", "2016-06-20", "2016-06-21",
          "2016-06-22")
flag <- c(1, 0, 0, 1, 1, 0, 1, 0, 1)
mydata <- data.frame(id, date, flag)

  id       date flag
1001 2016-06-20    1
1001 2016-06-21    0
1001 2016-06-22    0
1002 2016-06-20    1
1002 2016-06-21    1
1002 2016-06-22    0
1003 2016-06-20    1
1003 2016-06-21    0
1003 2016-06-22    1
</code>```

I am thinking of this as a two step process.

Step 1: determine whether the flag occurs on consecutive days.

This is similar to this question - R, find, dates, consecutive - but with a condition, if flag > 0. I try to apply the solution, although it doesn't quite work the same way.

```<code>mydata$flag_consecutive <- mydata$flag > 0 & c(NA, diff(as.Date(mydata$date)) == 1)

  id       date flag flag_consecutive
1001 2016-06-20    1               NA
1001 2016-06-21    0            FALSE
1001 2016-06-22    0            FALSE
1002 2016-06-20    1            FALSE
1002 2016-06-21    1             TRUE
1002 2016-06-22    0            FALSE
1003 2016-06-20    1            FALSE
1003 2016-06-21    0            FALSE
1003 2016-06-22    1             TRUE
</code>```

Step 2: create date range columns

I'm not sure how to approach this part with vectorization in R.
If the flag occurs on one day only, the start and end date are the same.
If the flag occurs on consecutive days, I want to put the first day in the sequence as date_start and the last day as date_end. If there is no flag occurring, drop that from the dataset.

What I'd like to generate is the data formatted this way:

```<code>  id flag  date_start     date_end
1001    1  2016-06-20   2016-06-20
1002    1  2016-06-20   2016-06-21
1003    1  2016-06-20   2016-06-20
1003    1  2016-06-22   2016-06-22
</code>```

If you can provide any guidance on step 1 or step 2, I am very thankful. I am thinking in circles and am not sure whether step 1 is even needed.

答:
A possible solution using the data.table-package:

```<code>library(data.table)
setDT(mydata)[, rl := rleid(flag)
              ][flag == 1
                , .(date_start = first(date), date_end = last(date))
                , by = .(id, rl, flag)
                ][, rl := NULL][]
</code>```

which gives:

```<code>     id flag date_start   date_end
1: 1001    1 2016-06-20 2016-06-20
2: 1002    1 2016-06-20 2016-06-21
3: 1003    1 2016-06-20 2016-06-20
4: 1003    1 2016-06-22 2016-06-22
</code>```

What this does:

rl := rleid(flag) creates a grouping variable rl for each consecutive rows of flags

Filter with flag == 1

Group with `by = .(id, rl, flag)

Select the first and last observation for each group with .(date_start = first(date), date_end = last(date)); when there is only one value, first and last will select that value.

An equivalent approach with dplyr:

```<code>library(dplyr)
mydata %>%
  mutate(rl = cumsum(flag != lag(flag, default = 1))) %>%
  filter(flag == 1) %>%
  group_by(id, flag, rl) %>%
  summarise(date_start = first(date),
            date_end = last(date)) %>%
  select(-rl)
</code>```

Body:
I must turn observations that meet a condition, a binary flag, on certain dates into a table of observations with the date range that they meet the flag.

Sample data look like this:

id <- c(1001, 1001, 1001, 1002, 1002, 1002, 1003, 1003, 1003)
date <- c("2016-06-20", "2016-06-21", "2016-06-22", "2016-06-20",
          "2016-06-21", "2016-06-22", "2016-06-20", "2016-06-21",
          "2016-06-22")
flag <- c(1, 0, 0, 1, 1, 0, 1, 0, 1)
mydata <- data.frame(id, date, flag)

  id       date flag
1001 2016-06-20    1
1001 2016-06-21    0
1001 2016-06-22    0
1002 2016-06-20    1
1002 2016-06-21    1
1002 2016-06-22    0
1003 2016-06-20    1
1003 2016-06-21    0
1003 2016-06-22    1

I am thinking of this as a two step process.

Step 1: determine whether the flag occurs on consecutive days.

This is similar to this question - R, find, dates, consecutive - but with a condition, if flag > 0. I try to apply the solution, although it doesn't quite work the same way.

mydata$flag_consecutive <- mydata$flag > 0 & c(NA, diff(as.Date(mydata$date)) == 1)

  id       date flag flag_consecutive
1001 2016-06-20    1               NA
1001 2016-06-21    0            FALSE
1001 2016-06-22    0            FALSE
1002 2016-06-20    1            FALSE
1002 2016-06-21    1             TRUE
1002 2016-06-22    0            FALSE
1003 2016-06-20    1            FALSE
1003 2016-06-21    0            FALSE
1003 2016-06-22    1             TRUE

Step 2: create date range columns

I'm not sure how to approach this part with vectorization in R.
If the flag occurs on one day only, the start and end date are the same.
If the flag occurs on consecutive days, I want to put the first day in the sequence as date_start and the last day as date_end. If there is no flag occurring, drop that from the dataset.

What I'd like to generate is the data formatted this way:

  id flag  date_start     date_end
1001    1  2016-06-20   2016-06-20
1002    1  2016-06-20   2016-06-21
1003    1  2016-06-20   2016-06-20
1003    1  2016-06-22   2016-06-22

If you can provide any guidance on step 1 or step 2, I am very thankful. I am thinking in circles and am not sure whether step 1 is even needed.

Body:
A possible solution using the data.table-package:

library(data.table)
setDT(mydata)[, rl := rleid(flag)
              ][flag == 1
                , .(date_start = first(date), date_end = last(date))
                , by = .(id, rl, flag)
                ][, rl := NULL][]

which gives:

     id flag date_start   date_end
1: 1001    1 2016-06-20 2016-06-20
2: 1002    1 2016-06-20 2016-06-21
3: 1003    1 2016-06-20 2016-06-20
4: 1003    1 2016-06-22 2016-06-22

What this does:

rl := rleid(flag) creates a grouping variable rl for each consecutive rows of flags

Filter with flag == 1

Group with `by = .(id, rl, flag)

Select the first and last observation for each group with .(date_start = first(date), date_end = last(date)); when there is only one value, first and last will select that value.

An equivalent approach with dplyr:

library(dplyr)
mydata %>%
  mutate(rl = cumsum(flag != lag(flag, default = 1))) %>%
  filter(flag == 1) %>%
  group_by(id, flag, rl) %>%
  summarise(date_start = first(date),
            date_end = last(date)) %>%
  select(-rl)


问:
MVC model design for entities
I'm trying to keep track of Employees in my database.

I have an entity class:

```<code>[Table(Name = "Employees")]
public class Employee
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int EmployeeID { get; set; }

    [Column]
    [Required]
    public string FirstName { get; set; }

    [Column]
    [Required]
    public string LastName { get; set; }

    [Column]
    [Required]
    public string Email { get; set; }
}
</code>```

I'm trying to create a page to add an employee to the database. So I created a ViewModel:

```<code>public class EmployeesAddViewModel
{
    public Employee employee { get; set; }
}
</code>```

I created the ViewModel like this because I plan on adding other things to the model later that aren't in the Employees table. I just wanted to start out with this to see if everything worked correctly.

And I have my page:

```<code><%@ Page Inherits="System.Web.Mvc.ViewPage<EmployeesAddViewModel>" ... %>

<% using (Html.BeginForm("Add", "Employees", FormMethod.Post)) { %>
    <%: Html.EditorForModel() %>
    <input type="submit" value="Save" />
<% } %>
</code>```

But when I view my page, it doesn't show any form fields for my model, it doesn't show anything.

Do I need to have fields in my model for each entity field instead of just having the entire Employee class in my model? I don't know what I'm doing wrong here.

答:
You can call Html.EditorFor(m => m.Employee)

The default editor template doesn't consider complex type properties.

Title: MVC model design for entities

Body:
I'm trying to keep track of Employees in my database.

I have an entity class:

[Table(Name = "Employees")]
public class Employee
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int EmployeeID { get; set; }

    [Column]
    [Required]
    public string FirstName { get; set; }

    [Column]
    [Required]
    public string LastName { get; set; }

    [Column]
    [Required]
    public string Email { get; set; }
}

I'm trying to create a page to add an employee to the database. So I created a ViewModel:

public class EmployeesAddViewModel
{
    public Employee employee { get; set; }
}

I created the ViewModel like this because I plan on adding other things to the model later that aren't in the Employees table. I just wanted to start out with this to see if everything worked correctly.

And I have my page:

<%@ Page Inherits="System.Web.Mvc.ViewPage<EmployeesAddViewModel>" ... %>

<% using (Html.BeginForm("Add", "Employees", FormMethod.Post)) { %>
    <%: Html.EditorForModel() %>
    <input type="submit" value="Save" />
<% } %>

But when I view my page, it doesn't show any form fields for my model, it doesn't show anything.

Do I need to have fields in my model for each entity field instead of just having the entire Employee class in my model? I don't know what I'm doing wrong here.


问:
Zapier: How to send data to my Node.js web app from ScheduleOnce using Zapier
Here is my workflow:

Person clicks on my ScheduleOnce link and schedules a meeting

Upon completing the ScheduleOnce booking form, the person clicks the done button

When this done button is clicked the person is redirected to a Node JS web app that displays an application page. This application page needs to be auto-populated with the information from the ScheduleOnce page.

Between step 2 and 3 is where Zapier comes in. I am trying to use Zapier to capture the data from the ScheduleOnce booking, which it is. Then I am trying to use a Zap to send that data to the page the person is redirected to, to auto-populate some of the fields.

I thought using the Code Javascript functionality would work but it does not. So then I was thinking about using the StoreClient option or the API. I am just confused on how to get the flow to work to access the data and auto-populate the fields on the next redirected page.

Some help would be greatly appreciated.

Here is the code I have for the Javascript option:

```<code>    var store = StoreClient("Secret");
    store
        .setMany({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite})
        .then(function() {
            return store.getMany('firstName', 'lastName', 'email', 'mobilePhone', 'otherPhone', 'businessWebsite');
        })
        .then(function() {
            callback();
        })
        .catch(callback);
</code>```

答:
David here, from the Zapier Platform team. This is a cool use case and is probably possible. Something you need to remember is that Zapier is running totally separately from the user, so interaction will have to be indirect. Zapier can't redirect your user anywhere, it can just store data in response to a button push.

In your case you can skip everything after the setMany, since you're not trying to use the values in the zap; you just need to store them (and verify that action completed without errors).

```<code>var store = StoreClient("Secret");
    store
        .setMany({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite})
        .catch(callback);
</code>```

You'll need to solve a couple of problems:

Speed. the user will reach your landing page before the zap completes (as it has to make a couple of HTTP round trips and execute code). You'll want to play them a 3 second loading gif, or put a waiting message and allow them to refresh the destination

Populating the page. I'm not sure what the nature of the destination is (best case scenario is that it's a server you control), but something will need to make an http request to store.zapier.com to retrieve the stored data and surface it in the view. This is easy if

Identifying the user. You'll need some way to identify the user getting redirected to the data you stored in StoreClient. If two users fill out the form in quick succession, the second one will currently overwrite the first. Plus, it seems to be semi-sensitive data that you don't just want available to anyone on your site. To that end, you'll probably want to store all of the data as a JSON string keyed by the user's email (or something else unique). That way, when I (the user) finish the form, I'm redirected to yoursite.com/landing?email=david@zapier.com, the backend knows to look for (the david@zapier.com key in store) and can render a view with the correct info.

To that end, I'd tweak the code to the following:

```<code>var store = StoreClient("Secret");
    store
        .set(inputData.email, JSON.stringify({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite}))
        .catch(callback);
</code>```

Hope that points you in the right direction. You're working with a pretty complicated workflow, but I bet you can do it!

Body:
Here is my workflow:

Person clicks on my ScheduleOnce link and schedules a meeting

Upon completing the ScheduleOnce booking form, the person clicks the done button

When this done button is clicked the person is redirected to a Node JS web app that displays an application page. This application page needs to be auto-populated with the information from the ScheduleOnce page.

Between step 2 and 3 is where Zapier comes in. I am trying to use Zapier to capture the data from the ScheduleOnce booking, which it is. Then I am trying to use a Zap to send that data to the page the person is redirected to, to auto-populate some of the fields.

I thought using the Code Javascript functionality would work but it does not. So then I was thinking about using the StoreClient option or the API. I am just confused on how to get the flow to work to access the data and auto-populate the fields on the next redirected page.

Some help would be greatly appreciated.

Here is the code I have for the Javascript option:

    var store = StoreClient("Secret");
    store
        .setMany({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite})
        .then(function() {
            return store.getMany('firstName', 'lastName', 'email', 'mobilePhone', 'otherPhone', 'businessWebsite');
        })
        .then(function() {
            callback();
        })
        .catch(callback);

Body:
David here, from the Zapier Platform team. This is a cool use case and is probably possible. Something you need to remember is that Zapier is running totally separately from the user, so interaction will have to be indirect. Zapier can't redirect your user anywhere, it can just store data in response to a button push.

In your case you can skip everything after the setMany, since you're not trying to use the values in the zap; you just need to store them (and verify that action completed without errors).

var store = StoreClient("Secret");
    store
        .setMany({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite})
        .catch(callback);

You'll need to solve a couple of problems:

Speed. the user will reach your landing page before the zap completes (as it has to make a couple of HTTP round trips and execute code). You'll want to play them a 3 second loading gif, or put a waiting message and allow them to refresh the destination

Populating the page. I'm not sure what the nature of the destination is (best case scenario is that it's a server you control), but something will need to make an http request to store.zapier.com to retrieve the stored data and surface it in the view. This is easy if

Identifying the user. You'll need some way to identify the user getting redirected to the data you stored in StoreClient. If two users fill out the form in quick succession, the second one will currently overwrite the first. Plus, it seems to be semi-sensitive data that you don't just want available to anyone on your site. To that end, you'll probably want to store all of the data as a JSON string keyed by the user's email (or something else unique). That way, when I (the user) finish the form, I'm redirected to yoursite.com/landing?email=david@zapier.com, the backend knows to look for (the david@zapier.com key in store) and can render a view with the correct info.

To that end, I'd tweak the code to the following:

var store = StoreClient("Secret");
    store
        .set(inputData.email, JSON.stringify({firstName: inputData.firstName, lastName: inputData.lastName, email: inputData.email, mobilePhone: inputData.mobilePhone, otherPhone: inputData.otherPhone, businessWebsite: inputData.businessWebsite}))
        .catch(callback);

Hope that points you in the right direction. You're working with a pretty complicated workflow, but I bet you can do it!


问:
Force image dimensions when empty
I am creating a grid with images. I have the problem of the empty images:

.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
}

.imgWrapper {
    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="myForm">
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form></code>```

I would like to force the empty images to have the same size as the others. —I don't know if this can be done with flexbox, but I prefer to avoid it—. I think I can do this adding another wrapper, but I would prefer to avoid it.

Thanks in advance!

答:
.myForm {
    position: relative;
    font-size: 0;
    display: block;
}

.imgWrapper {
    width: 33%;
    display : inline-block;
    float:left;
     background: tomato;
    min-height : 135px;
    max-height : 135px;
}

img {
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="myForm">
    <div class="imgWrapper">

        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form></code>```

you just need to add some min-height and min-width and float to your css :

for example :

```<code>.myForm {
    position: relative;
    font-size: 0;
    display: block;
}

.imgWrapper {
    width: 33%;
    display : inline-block;
    float:left;
     background: tomato;
    min-height : 135px;
    max-height : 135px;
}

img {
    width: 100%;
    height: 100%;
}
</code>```

Title: Force image dimensions when empty

Body:
I am creating a grid with images. I have the problem of the empty images:

.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
}

.imgWrapper {
    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}

<form class="myForm">

</form>

I would like to force the empty images to have the same size as the others. —I don't know if this can be done with flexbox, but I prefer to avoid it—. I think I can do this adding another wrapper, but I would prefer to avoid it.

Thanks in advance!

Body:
.myForm {
    position: relative;
    font-size: 0;
    display: block;
}

.imgWrapper {
    width: 33%;
    display : inline-block;
    float:left;
     background: tomato;
    min-height : 135px;
    max-height : 135px;
}

img {
    width: 100%;
    height: 100%;
}

<form class="myForm">
    <div class="imgWrapper">

        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form>

you just need to add some min-height and min-width and float to your css :

for example :

.myForm {
    position: relative;
    font-size: 0;
    display: block;
}

.imgWrapper {
    width: 33%;
    display : inline-block;
    float:left;
     background: tomato;
    min-height : 135px;
    max-height : 135px;
}

img {
    width: 100%;
    height: 100%;
}


问:
can single gcc generate executable for multiple targets like x86,arm,ppc?
We want to use a single gcc for multiple targets. Is it possible to build from source for supporting multiple targets?</p>

答: I'll also add that to have a useful toolchain you also need to build other components besides GCC. Components like an assembler and linker (from binutils for example) and a C library (e.g. glibc, musl, newlib etc). Each such component needs to be configured for a specific target</p>


答:
You can use a regular expression. Here is my code below.</p>

```<code>string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";

var matches = Regex.Matches(myString, @"value[0-9]*\:([0-9]+) *, * data[0-9]*\:([0-9]+)");
var pairs = new List<(int key, int value)>();
foreach (Match match in matches)
{
    var a = int.Parse(match.Groups[1].ToString());
    var b = int.Parse(match.Groups[2].ToString());
    pairs.Add((a,b));
}
</code>```

Title: How to retrieve each value from string and add them to the list

Body:
You can use a regular expression. Here is my code below.

string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";

var matches = Regex.Matches(myString, @"value[0-9]*\:([0-9]+) *, * data[0-9]*\:([0-9]+)");
var pairs = new List<(int key, int value)>();
foreach (Match match in matches)
{
    var a = int.Parse(match.Groups[1].ToString());
    var b = int.Parse(match.Groups[2].ToString());
    pairs.Add((a,b));
}


问:
Octave packages unload themselves
I'm using the Octave io package but it keeps unloading itself before I run the script. I'm using the xlsread function provided by io but I keep getting the following error:

```<code>warning: Functions for spreadsheet style I/O (.xls .xlsx .sxc .ods .dbf .wk1 etc.) are
provided in the io package. See <http://octave.sf.net/io/>.
Please read <http://www.octave.org/missing.html> to learn how you can contribute missing
functionality.
error: 'xlsread' undefined near line 25 column 23
</code>```

The package shows up when I type pkg list and there is an asterisk next to it when I type pkg load io. I even edited the octaverc to load io on startup. But I get that error when I run my script and when I check pkg list after my script fails the package is unloaded.

答: Make sure you don't invoke clear all (or similar commands) somewhere in your script, as this might also remove loaded libraries from memory.

Title: Octave packages unload themselves

Body:
I'm using the Octave io package but it keeps unloading itself before I run the script. I'm using the xlsread function provided by io but I keep getting the following error:

warning: Functions for spreadsheet style I/O (.xls .xlsx .sxc .ods .dbf .wk1 etc.) are
provided in the io package. See <http://octave.sf.net/io/>.
Please read <http://www.octave.org/missing.html> to learn how you can contribute missing
functionality.
error: 'xlsread' undefined near line 25 column 23

The package shows up when I type pkg list and there is an asterisk next to it when I type pkg load io. I even edited the octaverc to load io on startup. But I get that error when I run my script and when I check pkg list after my script fails the package is unloaded.


问:
JavaScript class methods and their properties. Trouble with code - how to pass arrays into properties?
I've had trouble dealing with my exercise (I'm fairly new to this) and for some reason, I cannot transfer an array into my child class constructor using the parent's method + parameter. aaaannnd I probably have a whole bunch of other problems on my code, but I'll try debugging myself for now.

```<code>class School {
  constructor(name, level, numberOfStudents) {
    this._name = name;
    this._level = level;              //['primary', 'middle', 'high'];
    this._numberOfStudents = numberOfStudents;
  }
  get name() {
    return this._name;
  }
  get level() {
    return this._level;
  }
  get numberOfStudents() {
    return this._numberOfStudents;
  }
  set numberOfStudents(newNumberOfStudents) {
    if (typeof newNumberOfStudents === number) {
      this._numberOfStudents = newNumberOfStudents
    } else {
      console.log(`The number of students must be numerical`);
      // might have to return something here
    }
  }

  quickFacts() {
    console.log(`${this.name} educates ${this.numberOfStudents} students, typically between the ages of ${this.level}.`);
  }

  static pickSubstituteTeacher(substituteTeachers) {
    let teacher = Math.floor(Math.random() * substituteTeachers.length);
    return substituteTeachers[teacher];
  }
}

class PrimarySchool extends School {
  constructor(name, numberOfStudents, pickupPolicy){
    super(name, 'primary', numberOfStudents);

    this._pickupPolicy = pickupPolicy;
  }
  get pickupPolicy() {
    return this._pickupPolicy;
  }
}

const lorraineHansbury = new PrimarySchool('Lorraine Hansbury', 514, 'Students must be picked up by a parent, guardian, or a family member over the age of 13.')

lorraineHansbury.quickFacts();

School.pickSubstituteTeacher(['Jamal Crawford', 'Lou Williams', 'J. R. Smith', 'James Harden', 'Jason Terry', 'Manu Ginobli']);
console.log(School.pickSubstituteTeacher());
</code>```

I appreciate any input and also comments on what I did wrong here in terms of formatting the question itself.

答:
As you are calling console.log(School.pickSubstituteTeacher()); there is no parameters passed so it will not work on this line let teacher = Math.floor(Math.random() * substituteTeachers.length); as substituteTeachers its undefined.

I have fixed that and its working let me know if you have any other issues

class School {
  constructor(name, level, numberOfStudents) {
    this._name = name;
    this._level = level;              //['primary', 'middle', 'high'];
    this._numberOfStudents = numberOfStudents;
  }
  get name() {
    return this._name;
  }
  get level() {
    return this._level;
  }
  get numberOfStudents() {
    return this._numberOfStudents;
  }
  set numberOfStudents(newNumberOfStudents) {
    if (typeof newNumberOfStudents === typeof Number) {
      this._numberOfStudents = newNumberOfStudents
    } else {
      console.log(`The number of students must be numerical`);
      // might have to return something here
    }
  }

  quickFacts() {
    console.log(`${this.name} educates ${this.numberOfStudents} students, typically between the ages of ${this.level}.`);
  }

  static pickSubstituteTeacher(substituteTeachers) {

   let teacher = Math.floor(Math.random() * substituteTeachers.length);
    return substituteTeachers[teacher];
  }
}

class PrimarySchool extends School {
  constructor(name, numberOfStudents, pickupPolicy){
    super(name, 'primary', numberOfStudents);

    this._pickupPolicy = pickupPolicy;
  }
  get pickupPolicy() {
    return this._pickupPolicy;
  }
}

const lorraineHansbury = new PrimarySchool('Lorraine Hansbury', 514, 'Students must be picked up by a parent, guardian, or a family member over the age of 13.')

lorraineHansbury.quickFacts();

console.log(School.pickSubstituteTeacher(['Jamal Crawford', 'Lou Williams', 'J. R. Smith', 'James Harden', 'Jason Terry', 'Manu Ginobli']));
//console.log(School.pickSubstituteTeacher());```

Body:
I've had trouble dealing with my exercise (I'm fairly new to this) and for some reason, I cannot transfer an array into my child class constructor using the parent's method + parameter. aaaannnd I probably have a whole bunch of other problems on my code, but I'll try debugging myself for now.

class School {
  constructor(name, level, numberOfStudents) {
    this._name = name;
    this._level = level;              //['primary', 'middle', 'high'];
    this._numberOfStudents = numberOfStudents;
  }
  get name() {
    return this._name;
  }
  get level() {
    return this._level;
  }
  get numberOfStudents() {
    return this._numberOfStudents;
  }
  set numberOfStudents(newNumberOfStudents) {
    if (typeof newNumberOfStudents === number) {
      this._numberOfStudents = newNumberOfStudents
    } else {
      console.log(`The number of students must be numerical`);
      // might have to return something here
    }
  }

  quickFacts() {
    console.log(`${this.name} educates ${this.numberOfStudents} students, typically between the ages of ${this.level}.`);
  }

  static pickSubstituteTeacher(substituteTeachers) {
    let teacher = Math.floor(Math.random() * substituteTeachers.length);
    return substituteTeachers[teacher];
  }
}

class PrimarySchool extends School {
  constructor(name, numberOfStudents, pickupPolicy){
    super(name, 'primary', numberOfStudents);

    this._pickupPolicy = pickupPolicy;
  }
  get pickupPolicy() {
    return this._pickupPolicy;
  }
}

const lorraineHansbury = new PrimarySchool('Lorraine Hansbury', 514, 'Students must be picked up by a parent, guardian, or a family member over the age of 13.')

lorraineHansbury.quickFacts();

School.pickSubstituteTeacher(['Jamal Crawford', 'Lou Williams', 'J. R. Smith', 'James Harden', 'Jason Terry', 'Manu Ginobli']);
console.log(School.pickSubstituteTeacher());

I appreciate any input and also comments on what I did wrong here in terms of formatting the question itself.