问:
Bash: Spurious "command not found" messages (I think)
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

```<code>inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}
</code>```

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

```<code>$ inDir "/tmp" "touch hi"
</code>```

correctly creates the file /tmp/hi, but also gives the error:

```<code>[2: command not found
</code>```

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

答:
This may help you with handling more complex arguments

```<code>inDir() {
    if [ $# -gt 1 ]; then
        local dir="$1"
        shift

        if [ -d "$dir" ]; then
            cd "$dir"
            "$@"
            cd -
        fi
    fi
}
</code>```

So now you can do something like:

```<code>inDir /foo touch "file name with spaces"
</code>```

Body:
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

$ inDir "/tmp" "touch hi"

correctly creates the file /tmp/hi, but also gives the error:

[2: command not found

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

Body:
This may help you with handling more complex arguments

inDir() {
    if [ $# -gt 1 ]; then
        local dir="$1"
        shift

        if [ -d "$dir" ]; then
            cd "$dir"
            "$@"
            cd -
        fi
    fi
}

So now you can do something like:

inDir /foo touch "file name with spaces"


来源: stackexchange

问:
Family polymorphism with ScalaTest
I'm trying to achieve something with ScalaTest and based on C. Hosrtmann's "Scala for the impatient" I think this is related to "Family polymorphism". Apparently I don't understand something about Scala's type system, so I fail.

To cut the long story short, this is what I'm trying to do.

I have a base (production) trait:

```<code>trait MaxPQ[Key] {

  implicit protected val cmp: Ordering[_ >: Key]

  ...

  def insert(v: Key): Unit

  def max(): Key

  def delMax(): Key

  ...
}
</code>```

then there is a number of implementations (that use either a backing tree or an array).

In tests I want to create an abstract structure which would allow to test any implementation for three Ordered Keys: Char, Int, Double.

First I've written two behaviors (for empty and non-empty priority queues). Here's a snippet:

```<code>trait MaxPQBehaviours {
  // underlying tests spec
  self: BaseSpec =>

  def nonEmptyMaxPQ[T <: Ordered[T], ImplLà <: MaxPQ[T]](instanceSupplier: () => ImplLà, sortedInput: List[T]): Unit = {

    ...

    behavior of "size"

    it should s"be equal to ${sortedInput.size}" in {
      val instance = instanceSupplier()
      instance.size() shouldEqual sortedInput.size
    }

    behavior of "max"

    it should s"return the expected $max" in {
      val instance = instanceSupplier()
      instance.max() shouldEqual max
    }
    ...

</code>```

Finally to add a last layer of abstraction I'm adding a BaseMaxPQSpec that mixes-in the above MaxPQBehaviours and calls its behaviors for three abstract MaxPQ types. Here I'only provide example for Char:

```<code>trait BaseMaxPQSpec extends BaseSpec with MaxPQBehaviours {

  type CharMaXPQ <: MaxPQ[Char]

  def charMaxPQ: CharMaXPQ
  val sortedCharsList: List[Char] = List[Char]('C', 'b', 'd', 'a', 'z').sorted

  it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
}
</code>```

And this is where compiler spits this at me:

```<code>[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:25: inferred type arguments [Char,BaseMaxPQSpec.this.CharMaXPQ] do not conform to method nonEmptyMaxPQ's type parameter bounds [T <: Ordered[T],ImplLà <: ca.vgorcinschi.algorithms2_4.MaxPQ[T]]
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                         ^
[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:42: type mismatch;
[error]  found   : () => BaseMaxPQSpec.this.CharMaXPQ
[error]  required: () => ImplLà
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                                          ^
[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:56: type mismatch;
[error]  found   : List[Char]
[error]  required: List[T]
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                                                        ^
[error] three errors found
[error] (Test / compileIncremental) Compilation failed
[error] Total time: 12 s, completed Feb 15, 2020 6:21:35 PM
</code>```

What is the correct way to set-up my testing framework? Please don't hesitate to ask for details, clarifications.

答:
Given

```<code>nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
</code>```

type inference deduces type T = Char because the type of charMaxPQ is MaxPQ[Char], thus

```<code>T <: Ordered[T]
</code>```

becomes Char <: Ordered[Char]

which certainly is not true. Perhaps try specifying Ordering like so

```<code>def nonEmptyMaxPQ[T: Ordering, Impl <: MaxPQ[T]](instanceSupplier: () => Impl, sortedInput: List[T])
</code>```

Note the difference between upper bound T <: Ordered[T] and context bound T: Ordering.

ContentLicense: CC BY-SA 4.0

Title: Family polymorphism with ScalaTest

Body:
I'm trying to achieve something with ScalaTest and based on C. Hosrtmann's "Scala for the impatient" I think this is related to "Family polymorphism". Apparently I don't understand something about Scala's type system, so I fail.

To cut the long story short, this is what I'm trying to do.

I have a base (production) trait:

trait MaxPQ[Key] {

  implicit protected val cmp: Ordering[_ >: Key]

  ...

  def insert(v: Key): Unit

  def max(): Key

  def delMax(): Key

  ...
}

then there is a number of implementations (that use either a backing tree or an array).

In tests I want to create an abstract structure which would allow to test any implementation for three Ordered Keys: Char, Int, Double.

First I've written two behaviors (for empty and non-empty priority queues). Here's a snippet:

trait MaxPQBehaviours {
  // underlying tests spec
  self: BaseSpec =>

  def nonEmptyMaxPQ[T <: Ordered[T], ImplLà <: MaxPQ[T]](instanceSupplier: () => ImplLà, sortedInput: List[T]): Unit = {

    ...

    behavior of "size"

    it should s"be equal to ${sortedInput.size}" in {
      val instance = instanceSupplier()
      instance.size() shouldEqual sortedInput.size
    }

    behavior of "max"

    it should s"return the expected $max" in {
      val instance = instanceSupplier()
      instance.max() shouldEqual max
    }
    ...

Finally to add a last layer of abstraction I'm adding a BaseMaxPQSpec that mixes-in the above MaxPQBehaviours and calls its behaviors for three abstract MaxPQ types. Here I'only provide example for Char:

trait BaseMaxPQSpec extends BaseSpec with MaxPQBehaviours {

  type CharMaXPQ <: MaxPQ[Char]

  def charMaxPQ: CharMaXPQ
  val sortedCharsList: List[Char] = List[Char]('C', 'b', 'd', 'a', 'z').sorted

  it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
}

And this is where compiler spits this at me:

[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:25: inferred type arguments [Char,BaseMaxPQSpec.this.CharMaXPQ] do not conform to method nonEmptyMaxPQ's type parameter bounds [T <: Ordered[T],ImplLà <: ca.vgorcinschi.algorithms2_4.MaxPQ[T]]
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                         ^
[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:42: type mismatch;
[error]  found   : () => BaseMaxPQSpec.this.CharMaXPQ
[error]  required: () => ImplLà
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                                          ^
[error] ~/Algorithms/Chapter 2 Sorting/algorithms2_1/src/test/scala/ca/vgorcinschi/algorithms2_4/BaseMaxPQSpec.scala:18:56: type mismatch;
[error]  found   : List[Char]
[error]  required: List[T]
[error]   it should behave like nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)
[error]                                                        ^
[error] three errors found
[error] (Test / compileIncremental) Compilation failed
[error] Total time: 12 s, completed Feb 15, 2020 6:21:35 PM

What is the correct way to set-up my testing framework? Please don't hesitate to ask for details, clarifications.

Body:
Given

nonEmptyMaxPQ(() => charMaxPQ, sortedCharsList)

type inference deduces type T = Char because the type of charMaxPQ is MaxPQ[Char], thus

T <: Ordered[T]

becomes Char <: Ordered[Char]

which certainly is not true. Perhaps try specifying Ordering like so

def nonEmptyMaxPQ[T: Ordering, Impl <: MaxPQ[T]](instanceSupplier: () => Impl, sortedInput: List[T])

Note the difference between upper bound T <: Ordered[T] and context bound T: Ordering.


问:
How to re-render a component based on state changing
I'm trying to redirect to login page if not logged when trying to access any components that require authentication.
While trying to use firebase auth, the auth object is not always initialised and there is a small delay so according to documentation, I have to use onAuthStateChanged() event listener which all works ok with the Nav bar which shows the signed in user.
However, when trying to to do the redirection for loggedin users, it's not working as the initial login dialog is being shown always as the state for authuser initially is not set and the routing seems to have already taken place. I seen a similar question (Firebase, Avoid Logged-in user to visit login page) here but don't really understand how I can use the suggestion cookies/querystrings from one of the comments when going directly to the url as there will still be small delay initially between the session value being set and rendering so don't see how it will work first time using that way. Totally new to React so hope this question makes sense.

PrivateRoute.js :

```<code>    // This is used to determine if a user is authenticated and
// if they are allowed to visit the page they navigated to.

// If they are: they proceed to the page
// If not: they are redirected to the login page.
import React, {useState} from 'react'
import { Redirect, Route } from 'react-router-dom'

const PrivateRoute = ({ loggedInUser, component: Component, ...rest }) => {
  console.log("Private Route, Logged User:"+JSON.stringify(loggedInUser))
  return (
    <Route
      {...rest}
      render={props =>
        (loggedInUser) ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
      }
    />
  )
}
export default PrivateRoute;
</code>```

答:
I have never worked with firebase, but I am doing something like this.

Let's say I have custom hooks, where I am getting my token, login, logout functions.

Here is my app.js looks like. I am getting token if user authorized to access. If access granted it gets the token, then sets the routes and redirects to admin dashboard.

```<code>function App() {
  const { token, login, logout } = useAuth();
  let routes;

  if (token) {
    routes = (
      <Switch>
        <Redirect to="/dashboard" />
      </Switch>
    );
  } else {
    routes = (
      <Switch>
        <Redirect to="/login" />
        <Route path="/" exact component={Layout} />
      </Switch>
    )
  }

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: !!token,
        token: token,
        login: login,
        logout: logout,
      }}
    >
      <Navigation />
      <Router>
        <main>
          {routes}
        </main>
      </Router>
    </AuthContext.Provider>
  );
}
</code>```

And this how my nav looks like

```<code>const Navigation = () => {
  const auth = useContext(AuthContext);

  return (
    <>
      { auth.isLoggedIn && (<AdminNavigation />) }
      { !auth.isLoggedIn && (<UserNavigation />) }
    </>
  );
};
</code>```

This is how my SignIn component looks like

```<code>const SignIn = () => {
  const auth = useContext(AuthContext);
  const classes = useStyles();

  const {
    // eslint-disable-next-line no-unused-vars
    isLoading, error, sendRequest, clearError,
  } = useHttpClient();

  const [password, setPassword] = useState('');
  const [email, setEmail] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(true);

  const updateInput = (event) => {
    if (event.target.id.toLowerCase() === 'email') {
      setEmail(event.target.value);
    } else {
      setPassword(event.target.value);
    }
  };

  const handleSwitchMode = () => {
    setIsLoggedIn((prevMode) => !prevMode);
  };

  const authSubmitHandler = async (event) => {
    event.preventDefault();

    setIsLoggedIn(true);
    // auth.login();

    if (isLoggedIn) {
      try {
        const responseData = await sendRequest(
          `${API_URL}/admin/login`,
          'POST',
          JSON.stringify({
            email,
            password,
          }),
          {
            'Content-Type': 'application/json',
          },
        );
        setIsLoggedIn(false);
        auth.login(responseData.token);
      } catch (err) {
        setIsLoggedIn(false);
      }
    } else {
      try {
        const responseData = await sendRequest(
          `${API_URL}/admin/signup`,
          'POST',
          JSON.stringify({
          // name,
            email,
            password,
          }),
          {
            'Content-Type': 'application/json',
          },
        );
        auth.login(responseData.token);
      } catch (err) {
        clearError();
      }
    }
  };

return (
    <Container component="main" maxWidth="xs">
      <div className={classes.paper}>
        <Typography component="h1" variant="h5">
          {isLoggedIn ? 'Login' : 'Sign up'}
        </Typography>
        <form className={classes.form} noValidate>
          {!isLoggedIn && (
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="name"
              label="Your name"
              autoFocus
              onChange={updateInput}
            />
          )}

          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            value={email}
            onChange={updateInput}
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            value={password}
            autoComplete="current-password"
            onChange={updateInput}
          />
          <FormControlLabel
            control={<Checkbox value="remember" color="primary" />}
            label="Remember me"
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={authSubmitHandler}
          >
            {isLoggedIn ? 'Login' : 'Sign up'}
          </Button>
          <Grid container>
            <Grid item xs>
              <Link href="/" variant="body2">
                Forgot password?
              </Link>
            </Grid>
            <Grid item>
              <Button
                onClick={handleSwitchMode}
              >
                Dont have an account? Sign Up
              </Button>
            </Grid>
          </Grid>
        </form>
      </div>
    </Container>
  );
</code>```

Hope this helps.

Body:
I'm trying to redirect to login page if not logged when trying to access any components that require authentication.
While trying to use firebase auth, the auth object is not always initialised and there is a small delay so according to documentation, I have to use onAuthStateChanged() event listener which all works ok with the Nav bar which shows the signed in user.
However, when trying to to do the redirection for loggedin users, it's not working as the initial login dialog is being shown always as the state for authuser initially is not set and the routing seems to have already taken place. I seen a similar question (Firebase, Avoid Logged-in user to visit login page) here but don't really understand how I can use the suggestion cookies/querystrings from one of the comments when going directly to the url as there will still be small delay initially between the session value being set and rendering so don't see how it will work first time using that way. Totally new to React so hope this question makes sense.

PrivateRoute.js :

    // This is used to determine if a user is authenticated and
// if they are allowed to visit the page they navigated to.

// If they are: they proceed to the page
// If not: they are redirected to the login page.
import React, {useState} from 'react'
import { Redirect, Route } from 'react-router-dom'

const PrivateRoute = ({ loggedInUser, component: Component, ...rest }) => {
  console.log("Private Route, Logged User:"+JSON.stringify(loggedInUser))
  return (
    <Route
      {...rest}
      render={props =>
        (loggedInUser) ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
      }
    />
  )
}
export default PrivateRoute;

Body:
I have never worked with firebase, but I am doing something like this.

Let's say I have custom hooks, where I am getting my token, login, logout functions.

Here is my app.js looks like. I am getting token if user authorized to access. If access granted it gets the token, then sets the routes and redirects to admin dashboard.

function App() {
  const { token, login, logout } = useAuth();
  let routes;

  if (token) {
    routes = (
      <Switch>
        <Redirect to="/dashboard" />
      </Switch>
    );
  } else {
    routes = (
      <Switch>
        <Redirect to="/login" />
        <Route path="/" exact component={Layout} />
      </Switch>
    )
  }

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: !!token,
        token: token,
        login: login,
        logout: logout,
      }}
    >
      <Navigation />
      <Router>
        <main>
          {routes}
        </main>
      </Router>
    </AuthContext.Provider>
  );
}

And this how my nav looks like

const Navigation = () => {
  const auth = useContext(AuthContext);

  return (
    <>
      { auth.isLoggedIn && (<AdminNavigation />) }
      { !auth.isLoggedIn && (<UserNavigation />) }
    </>
  );
};

This is how my SignIn component looks like

const SignIn = () => {
  const auth = useContext(AuthContext);
  const classes = useStyles();

  const {
    // eslint-disable-next-line no-unused-vars
    isLoading, error, sendRequest, clearError,
  } = useHttpClient();

  const [password, setPassword] = useState('');
  const [email, setEmail] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(true);

  const updateInput = (event) => {
    if (event.target.id.toLowerCase() === 'email') {
      setEmail(event.target.value);
    } else {
      setPassword(event.target.value);
    }
  };

  const handleSwitchMode = () => {
    setIsLoggedIn((prevMode) => !prevMode);
  };

  const authSubmitHandler = async (event) => {
    event.preventDefault();

    setIsLoggedIn(true);
    // auth.login();

    if (isLoggedIn) {
      try {
        const responseData = await sendRequest(
          `${API_URL}/admin/login`,
          'POST',
          JSON.stringify({
            email,
            password,
          }),
          {
            'Content-Type': 'application/json',
          },
        );
        setIsLoggedIn(false);
        auth.login(responseData.token);
      } catch (err) {
        setIsLoggedIn(false);
      }
    } else {
      try {
        const responseData = await sendRequest(
          `${API_URL}/admin/signup`,
          'POST',
          JSON.stringify({
          // name,
            email,
            password,
          }),
          {
            'Content-Type': 'application/json',
          },
        );
        auth.login(responseData.token);
      } catch (err) {
        clearError();
      }
    }
  };

return (
    <Container component="main" maxWidth="xs">
      <div className={classes.paper}>
        <Typography component="h1" variant="h5">
          {isLoggedIn ? 'Login' : 'Sign up'}
        </Typography>
        <form className={classes.form} noValidate>
          {!isLoggedIn && (
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="name"
              label="Your name"
              autoFocus
              onChange={updateInput}
            />
          )}

          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            value={email}
            onChange={updateInput}
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            value={password}
            autoComplete="current-password"
            onChange={updateInput}
          />
          <FormControlLabel
            control={<Checkbox value="remember" color="primary" />}
            label="Remember me"
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={authSubmitHandler}
          >
            {isLoggedIn ? 'Login' : 'Sign up'}
          </Button>
          <Grid container>
            <Grid item xs>
              <Link href="/" variant="body2">
                Forgot password?
              </Link>
            </Grid>
            <Grid item>
              <Button
                onClick={handleSwitchMode}
              >
                Dont have an account? Sign Up
              </Button>
            </Grid>
          </Grid>
        </form>
      </div>
    </Container>
  );

Hope this helps.


问:
Looping a Dice-Roll Simulation in Python
I've been assigned an example as part of my homework in which a red and a blue die are rolled, and their totals summed, as per the below code calling on both the NumPy and pandas libraries:

```<code>red = np.repeat(np.arange(1,7),6)
blue = np.tile(np.arange(1,7),6)
dice_roll = pd.DataFrame({'Red':(red),'Blue':(blue),'Total':red+blue})
</code>```

We're told that choosing at random from 'Total' is the equivalent to a single roll of both dice, which appears to hold true, but the exercise hinges on making multiple rolls of these dice.

From here, how would I simulate rolling the dice a specified number of times? I've a feeling that implementing a loop would be my best bet, but I'm not quite sure how to go about it...

答:
This will return a list of the values of each roll

```<code>import random

def roll_dice(number):
    return [random.randint(1, 6) for x in range(number)]

def main():
    print(roll_dice(20))

if __name__ == '__main__':
    main()
</code>```

Obviously this doesnt use numpy or pandas. But it performs the same function. This key part is the roll_dice function.

Body:
I've been assigned an example as part of my homework in which a red and a blue die are rolled, and their totals summed, as per the below code calling on both the NumPy and pandas libraries:

red = np.repeat(np.arange(1,7),6)
blue = np.tile(np.arange(1,7),6)
dice_roll = pd.DataFrame({'Red':(red),'Blue':(blue),'Total':red+blue})

We're told that choosing at random from 'Total' is the equivalent to a single roll of both dice, which appears to hold true, but the exercise hinges on making multiple rolls of these dice.

From here, how would I simulate rolling the dice a specified number of times? I've a feeling that implementing a loop would be my best bet, but I'm not quite sure how to go about it...

Body:
This will return a list of the values of each roll

import random

def roll_dice(number):
    return [random.randint(1, 6) for x in range(number)]

def main():
    print(roll_dice(20))

if __name__ == '__main__':
    main()

Obviously this doesnt use numpy or pandas. But it performs the same function. This key part is the roll_dice function.


问:
C thread pool efficiency

Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

```<code>pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}
</code>```

答: If you aren't blocking the threads to do disk or network I/O then the most efficient number of threads in the pool is one per-processor (assuming all the work is being done on the thread pool threads). The rest of the work items should be queued up and pulled off as they are completed.</p>

ContentLicense: CC BY-SA 3.0

Title: C thread pool efficiency

Body:
Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}


问:
I want to run multiple threads in python after I input anthing from the keyboard and I am getting this error - Exception in thread Thread-4:
I want to run multiple threads in python after I input anthing from the keyboard and I am getting this error - Exception in thread Thread-4:

import threading
import os
import cv2

def task():
    user_input = input()
    print(user_input)
    print("Task assigned to thread: {}".format(threading.current_thread().name))
    print("ID of process running task : {}".format(os.getpid()))
    print("Thread started now")

if __name__ == "__main__":
    for i in range(1, 5):
         # Instantiates the thread
        t = threading.Thread(target=task, args=(i,))
        t.start()
        t.join()
```

答:
You should post the whole traceback.  Here is what I get in all 4 threads:

```<code>Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: task() takes 0 positional arguments but 1 was given
</code>```

It says the function task() was passed an argument when it didn't require any, so don't pass an argument when creating the thread:

```<code>t = threading.Thread(target=task, args=())
</code>```

or make task() take an argument:

```<code>def task(i):
</code>```

Asking for input in the thread doesn't really make sense either.  No prompting and you won't know which thread is taking input.

Since using threading and not multiprocessing module, os.getpid() is going to return the same value in all threads.

Also, if you start and join the thread in the same loop, you aren't getting any parallelism.  Start all the threads in one loop, then join (wait for completion) in another loop.

Here's a solution that demonstrates parallelism:

```<code>import threading
import os
import time

def task(i):
    print(f'Task#{i} started in {threading.current_thread().name}')
    time.sleep(5) # do some "work"
    print(f'Task#{i} done')

threads = [threading.Thread(target=task,args=(i,)) for i in range(1,5)]
print(f'Start: {time.ctime()}')
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f'End:   {time.ctime()}')
</code>```

Output (note start and end times are 5 seconds apart):

```<code>Start: Sat Feb 15 16:22:59 2020
Task#1 started in Thread-1
Task#2 started in Thread-2
Task#3 started in Thread-3
Task#4 started in Thread-4
Task#1 done
Task#2 done
Task#4 done
Task#3 done
End:   Sat Feb 15 16:23:04 2020
</code>```

A final note:  A process can only run Python code in one thread at a time due to CPython's global interpreter lock (GIL) implementation, so the threading module won't save time for Python-intensive work, but is useful when Python is waiting on I/O or calling into native C modules that release the GIL.  The multiprocessing module can be used to create multiple Python processes that aren't limited by the GIL, but has longer process initialization time and arguments are passed through inter-process methods.

```<code>import multiprocessing as mp
import os
import time

def task(i):
    print(f'Task#{i} started in {mp.current_process().name}')
    time.sleep(5)
    print(f'Task#{i} done')

if __name__ == '__main__':
    processes = [mp.Process(target=task,args=(i,)) for i in range(1,5)]
    print(f'Start: {time.ctime()}')
    for p in processes:
        p.start()
    for p in processes:
        p.join()
    print(f'End:   {time.ctime()}')
</code>```

Output:

```<code>Start: Sat Feb 15 16:32:26 2020
Task#4 started in Process-4
Task#3 started in Process-3
Task#1 started in Process-1
Task#2 started in Process-2
Task#1 done
Task#4 done
Task#3 done
Task#2 done
End:   Sat Feb 15 16:32:31 2020
</code>```

Body:
You should post the whole traceback.  Here is what I get in all 4 threads:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: task() takes 0 positional arguments but 1 was given

It says the function task() was passed an argument when it didn't require any, so don't pass an argument when creating the thread:

t = threading.Thread(target=task, args=())

or make task() take an argument:

def task(i):

Asking for input in the thread doesn't really make sense either.  No prompting and you won't know which thread is taking input.

Since using threading and not multiprocessing module, os.getpid() is going to return the same value in all threads.

Also, if you start and join the thread in the same loop, you aren't getting any parallelism.  Start all the threads in one loop, then join (wait for completion) in another loop.

Here's a solution that demonstrates parallelism:

import threading
import os
import time

def task(i):
    print(f'Task#{i} started in {threading.current_thread().name}')
    time.sleep(5) # do some "work"
    print(f'Task#{i} done')

threads = [threading.Thread(target=task,args=(i,)) for i in range(1,5)]
print(f'Start: {time.ctime()}')
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f'End:   {time.ctime()}')

Output (note start and end times are 5 seconds apart):

Start: Sat Feb 15 16:22:59 2020
Task#1 started in Thread-1
Task#2 started in Thread-2
Task#3 started in Thread-3
Task#4 started in Thread-4
Task#1 done
Task#2 done
Task#4 done
Task#3 done
End:   Sat Feb 15 16:23:04 2020

A final note:  A process can only run Python code in one thread at a time due to CPython's global interpreter lock (GIL) implementation, so the threading module won't save time for Python-intensive work, but is useful when Python is waiting on I/O or calling into native C modules that release the GIL.  The multiprocessing module can be used to create multiple Python processes that aren't limited by the GIL, but has longer process initialization time and arguments are passed through inter-process methods.

import multiprocessing as mp
import os
import time

def task(i):
    print(f'Task#{i} started in {mp.current_process().name}')
    time.sleep(5)
    print(f'Task#{i} done')

if __name__ == '__main__':
    processes = [mp.Process(target=task,args=(i,)) for i in range(1,5)]
    print(f'Start: {time.ctime()}')
    for p in processes:
        p.start()
    for p in processes:
        p.join()
    print(f'End:   {time.ctime()}')

Output:

Start: Sat Feb 15 16:32:26 2020
Task#4 started in Process-4
Task#3 started in Process-3
Task#1 started in Process-1
Task#2 started in Process-2
Task#1 done
Task#4 done
Task#3 done
Task#2 done
End:   Sat Feb 15 16:32:31 2020


问:
Mock dependency in Jest with TypeScript
When testing a module that has a dependency in a different file and assigning that module to be a jest.mock, TypeScript gives an error that the method mockReturnThisOnce (or any other jest.mock method) does not exist on the dependency, this is because it is previously typed.

What is the proper way to get TypeScript to inherit the types from jest.mock?

Here is a quick example.

Dependency

```<code>const myDep = (name: string) => name;
export default myDep;
</code>```

test.ts

```<code>import * as dep from '../depenendency';
jest.mock('../dependency');

it('should do what I need', () => {
  //this throws ts error
  // Property mockReturnValueOnce does not exist on type (name: string)....
  dep.default.mockReturnValueOnce('return')
}
</code>```

I feel like this is a very common use case and not sure how to properly type this.

答:
A recent library solves this problem with a babel plugin: https://github.com/userlike/joke

Example:

import { mock, mockSome } from 'userlike/joke';

const dep = mock(import('./dependency'));

// You can partially mock a module too, completely typesafe!
// thisIsAMock has mock related methods
// thisIsReal does not have mock related methods
const { thisIsAMock, thisIsReal } = mockSome(import('./dependency2'), () => ({
  thisIsAMock: jest.fn()
}));

it('should do what I need', () => {
  dep.mockReturnValueOnce('return');
}
```

Be aware that dep and mockReturnValueOnce are fully type safe. On top, tsserver is aware that depencency was imported and was assigned to dep so all automatic refactorings that tsserver supports will work too.

Note: I maintain the library.

Title: Mock dependency in Jest with TypeScript

Body:
When testing a module that has a dependency in a different file and assigning that module to be a jest.mock, TypeScript gives an error that the method mockReturnThisOnce (or any other jest.mock method) does not exist on the dependency, this is because it is previously typed.

What is the proper way to get TypeScript to inherit the types from jest.mock?

Here is a quick example.

Dependency

const myDep = (name: string) => name;
export default myDep;

test.ts

import * as dep from '../depenendency';
jest.mock('../dependency');

it('should do what I need', () => {
  //this throws ts error
  // Property mockReturnValueOnce does not exist on type (name: string)....
  dep.default.mockReturnValueOnce('return')
}

I feel like this is a very common use case and not sure how to properly type this.

Body:
A recent library solves this problem with a babel plugin: https://github.com/userlike/joke

Example:

import { mock, mockSome } from 'userlike/joke';

const dep = mock(import('./dependency'));

// You can partially mock a module too, completely typesafe!
// thisIsAMock has mock related methods
// thisIsReal does not have mock related methods
const { thisIsAMock, thisIsReal } = mockSome(import('./dependency2'), () => ({
  thisIsAMock: jest.fn()
}));

it('should do what I need', () => {
  dep.mockReturnValueOnce('return');
}

Be aware that dep and mockReturnValueOnce are fully type safe. On top, tsserver is aware that depencency was imported and was assigned to dep so all automatic refactorings that tsserver supports will work too.

Note: I maintain the library.


问:
C#: Populating combobox from stored procedure only displays first item
I am trying to populate a combobox at initialization by executing a stored procedure. When I run the procedure on my DB, there are 3 rows that come out:

But once I execute the procedure in my code:

```<code>public partial class AddInstitutionStart : Window
    {
        public AddInstitutionStart()
        {
            InitializeComponent();
            ComboBoxInstitutionCategory.Items.Add(FillCombo.fillInstCategory());
        }
    }

    public static class FillCombo
    {
        public static string fillInstCategory()
        {
            string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
            SqlConnection Connect = null;
            SqlCommand Command;
            using (Connect = new SqlConnection(connstr))
            {
                Connect.Open();
                using (Command = new SqlCommand("[dbo].[spMetadataTb_GetCategory]", Connect))
                {
                    Command.CommandType = CommandType.StoredProcedure;
                    SqlDataReader dr = Command.ExecuteReader();
                    while (dr.Read())
                    {
                        string categoryInst = dr.GetString(0);
                        return categoryInst;
                    }
                }

                Command.Dispose();
                Connect.Close();
                return "-2";
            }
        }
    }
</code>```

Only the first row is displayed:

I have used the same logic to fill another combobox (not at initialization) and it works perfectly and displays multiple item. Any idea on what I might be doing wrong here?

答:
Something like this...only dispose of your reader also.</p>

```<code>public static List<string> fillInstCategory()
{
    string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
    SqlConnection Connect = null;
    SqlCommand Command;
    List<string> categories = new List<string>();
    using (Connect = new SqlConnection(connstr))
    {
        Connect.Open();
        using (Command = new SqlCommand("[dbo].[spMetadataTb_GetCategory]", Connect))
        {
            Command.CommandType = CommandType.StoredProcedure;
            SqlDataReader dr = Command.ExecuteReader();
            while (dr.Read())
            {
                string categoryInst = dr.GetString(0);
                categories.Add(categoryInst);
            }
        }

        Command.Dispose();
        Connect.Close();
        return categories;
    }
}
</code>```

Body:
I am trying to populate a combobox at initialization by executing a stored procedure. When I run the procedure on my DB, there are 3 rows that come out:

But once I execute the procedure in my code:

public partial class AddInstitutionStart : Window
    {
        public AddInstitutionStart()
        {
            InitializeComponent();
            ComboBoxInstitutionCategory.Items.Add(FillCombo.fillInstCategory());
        }
    }

    public static class FillCombo
    {
        public static string fillInstCategory()
        {
            string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
            SqlConnection Connect = null;
            SqlCommand Command;
            using (Connect = new SqlConnection(connstr))
            {
                Connect.Open();
                using (Command = new SqlCommand("[dbo].[spMetadataTb_GetCategory]", Connect))
                {
                    Command.CommandType = CommandType.StoredProcedure;
                    SqlDataReader dr = Command.ExecuteReader();
                    while (dr.Read())
                    {
                        string categoryInst = dr.GetString(0);
                        return categoryInst;
                    }
                }

                Command.Dispose();
                Connect.Close();
                return "-2";
            }
        }
    }

Only the first row is displayed:

I have used the same logic to fill another combobox (not at initialization) and it works perfectly and displays multiple item. Any idea on what I might be doing wrong here?

Body:
Something like this...only dispose of your reader also.

public static List<string> fillInstCategory()
{
    string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
    SqlConnection Connect = null;
    SqlCommand Command;
    List<string> categories = new List<string>();
    using (Connect = new SqlConnection(connstr))
    {
        Connect.Open();
        using (Command = new SqlCommand("[dbo].[spMetadataTb_GetCategory]", Connect))
        {
            Command.CommandType = CommandType.StoredProcedure;
            SqlDataReader dr = Command.ExecuteReader();
            while (dr.Read())
            {
                string categoryInst = dr.GetString(0);
                categories.Add(categoryInst);
            }
        }

        Command.Dispose();
        Connect.Close();
        return categories;
    }
}


问:
Spinner won't display string entries
My program should use a spinner to show a list of color names, and have the background color of it. For example in the image shown, the color red should have a black text displayed saying "Red" to specify it.
https://i.stack.imgur.com/BT0dW.jpg

I have android:entries="@array/myStrings" that shows the first color's text (without color, plain white background) on design mode, but once I run the program, the text does not display for any of the colors.

strings.xml

```<code><resources>
    <string name="app_name">Color Activity</string>
    <string-array name="myStrings">
        <item>Silver</item>
        <item>Pink</item>
        <item>Red</item>
        <item>Orange</item>
        <item>Yellow</item>
        <item>Green</item>
        <item>Blue</item>
        <item>Indigo</item>
        <item>Violet</item>
        <item>Brown</item>
    </string-array>
</resources>
</code>```

colors.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>

    <color name="silver" type="color">#c0c0c0</color>
    <color name="pink" type="color">#ffc0cb</color>
    <color name="red" type="color">#ff0000</color>
    <color name="orange" type="color">#ffa500</color>
    <color name="yellow" type="color">#ffff00</color>
    <color name="green" type="color">#00ff00</color>
    <color name="blue" type="color">#0000ff</color>
    <color name="indigo" type="color">#4b0082</color>
    <color name="violet" type="color">#7f00ff</color>
    <color name="brown" type="color">#654321</color>
    <color name="white" type="color">#FFFFFF</color>
    <integer-array name="myColors">
        <item>@color/silver</item>
        <item>@color/pink</item>
        <item>@color/red</item>
        <item>@color/orange</item>
        <item>@color/yellow</item>
        <item>@color/green</item>
        <item>@color/blue</item>
        <item>@color/indigo</item>
        <item>@color/violet</item>
        <item>@color/brown</item>
    </integer-array>

</resources>
</code>```

MainActivity

```<code>import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final View newBackground;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(new ColorAdapter(this));
        newBackground = this.getWindow().getDecorView();

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Integer> colors;
                colors = new ArrayList<Integer>();
                int retrieve []= getResources().getIntArray(R.array.myColors);
                for(int i:retrieve)
                {
                    colors.add(i);
                }

                if(position == 0){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.silver);
                }else if(position == 1){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.pink);
                }else if(position == 2){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.red);

                }else if(position == 3){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.orange);
                }else if(position == 4){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.yellow);
                }else if(position == 5){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.green);
                }else if(position == 6){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.blue);
                }else if(position == 7){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.indigo);
                }else if(position == 8){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.violet);
                }else if(position == 9){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.brown);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

}
</code>```

Color Adapter:

```<code>import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorAdapter extends BaseAdapter {
    ArrayList<Integer> colors;
    Context context;

    public ColorAdapter(Context context){

        this.context=context;
        colors = new ArrayList<Integer>();
        int retrieve []=context.getResources().getIntArray(R.array.myColors);

        for(int i:retrieve)
        {
            colors.add(i);
        }
    }
    @Override
    public int getCount() {
        return colors.size();
    }

    @Override
    public Object getItem(int args) {
        return colors.get(args);
    }

    @Override
    public long getItemId(int args) {
        return args;
    }

    public String getElementFromColors(int position){
        String retrieve []=context.getResources().getStringArray(R.array.myColors);
        return retrieve[position];
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        convertView=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        TextView txv=(TextView)convertView.findViewById(android.R.id.text1);
        txv.setBackgroundColor(colors.get(position));
        txv.setTextSize(20f);
        txv.setText(getElementFromColors(position));
        return convertView;
    }

}
</code>```

答:
In ColorActivity you passed the wrong array to your ArrayAdapter.

```<code>ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);
</code>```

R.array.myColors -
this is an array of colors id.

You should use R.array.myStrings instead.

Like this

```<code>ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myStrings, android.R.layout.simple_spinner_item);
</code>```

Title: Spinner won't display string entries

Body:
My program should use a spinner to show a list of color names, and have the background color of it. For example in the image shown, the color red should have a black text displayed saying "Red" to specify it.
https://i.stack.imgur.com/BT0dW.jpg

I have android:entries="@array/myStrings" that shows the first color's text (without color, plain white background) on design mode, but once I run the program, the text does not display for any of the colors.

strings.xml

<resources>
    <string name="app_name">Color Activity</string>
    <string-array name="myStrings">
        <item>Silver</item>
        <item>Pink</item>
        <item>Red</item>
        <item>Orange</item>
        <item>Yellow</item>
        <item>Green</item>
        <item>Blue</item>
        <item>Indigo</item>
        <item>Violet</item>
        <item>Brown</item>
    </string-array>
</resources>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>

    <color name="silver" type="color">#c0c0c0</color>
    <color name="pink" type="color">#ffc0cb</color>
    <color name="red" type="color">#ff0000</color>
    <color name="orange" type="color">#ffa500</color>
    <color name="yellow" type="color">#ffff00</color>
    <color name="green" type="color">#00ff00</color>
    <color name="blue" type="color">#0000ff</color>
    <color name="indigo" type="color">#4b0082</color>
    <color name="violet" type="color">#7f00ff</color>
    <color name="brown" type="color">#654321</color>
    <color name="white" type="color">#FFFFFF</color>
    <integer-array name="myColors">
        <item>@color/silver</item>
        <item>@color/pink</item>
        <item>@color/red</item>
        <item>@color/orange</item>
        <item>@color/yellow</item>
        <item>@color/green</item>
        <item>@color/blue</item>
        <item>@color/indigo</item>
        <item>@color/violet</item>
        <item>@color/brown</item>
    </integer-array>

</resources>

MainActivity

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final View newBackground;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(new ColorAdapter(this));
        newBackground = this.getWindow().getDecorView();

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Integer> colors;
                colors = new ArrayList<Integer>();
                int retrieve []= getResources().getIntArray(R.array.myColors);
                for(int i:retrieve)
                {
                    colors.add(i);
                }

                if(position == 0){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.silver);
                }else if(position == 1){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.pink);
                }else if(position == 2){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.red);

                }else if(position == 3){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.orange);
                }else if(position == 4){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.yellow);
                }else if(position == 5){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.green);
                }else if(position == 6){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.blue);
                }else if(position == 7){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.indigo);
                }else if(position == 8){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.violet);
                }else if(position == 9){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.brown);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

}

Color Adapter:

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorAdapter extends BaseAdapter {
    ArrayList<Integer> colors;
    Context context;

    public ColorAdapter(Context context){

        this.context=context;
        colors = new ArrayList<Integer>();
        int retrieve []=context.getResources().getIntArray(R.array.myColors);

        for(int i:retrieve)
        {
            colors.add(i);
        }
    }
    @Override
    public int getCount() {
        return colors.size();
    }

    @Override
    public Object getItem(int args) {
        return colors.get(args);
    }

    @Override
    public long getItemId(int args) {
        return args;
    }

    public String getElementFromColors(int position){
        String retrieve []=context.getResources().getStringArray(R.array.myColors);
        return retrieve[position];
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        convertView=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        TextView txv=(TextView)convertView.findViewById(android.R.id.text1);
        txv.setBackgroundColor(colors.get(position));
        txv.setTextSize(20f);
        txv.setText(getElementFromColors(position));
        return convertView;
    }

}

Body:
In ColorActivity you passed the wrong array to your ArrayAdapter.

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);

R.array.myColors -
this is an array of colors id.

You should use R.array.myStrings instead.

Like this

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myStrings, android.R.layout.simple_spinner_item);


问:
WebBrowser control from Console app using F#
I have a .netcoreapp3.1 Console App

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWpf>true</UseWpf>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>
</Project>
</code>```

In Program.fs, I am instantiating a WebBrowser control and handling the DocumentCompleted event

```<code>let run() =
    let uri = "https://www.microsoft.com"
    let browser = new WebBrowser()
    browser.DocumentCompleted.Add(fun _ -> handlePage browser uris)
    browser.Navigate(uri)

[<STAThread>]
[<EntryPoint>]
let main argv =
    run()
    Console.ReadKey() |> ignore
    0
</code>```

When I run it, the DocumentCompleted event is never fired or handled - the program runs through to the end.

Am I missing?

Thanks in advance.

答:
Am I missing?

The message pump. You need a Dispatcher to run a WPF app.

On another note, you're using the WinForms WebBrowser, that one exposes the DocumentCompleted event. The WPF variant has the LoadCompleted event, ref this post.

In WPF, however, the concept of Loaded is related to the visual tree. As you're not rendering the control, the event will never be raised. If we instead use the Navigated event, we can get there with minimal fuss.

open System
open System.Windows
open System.Windows.Controls

type BrowserApplication() =
   inherit Application()

   let run() =
       let uri = "https://www.microsoft.com"
       let browser = new WebBrowser()
       browser.Navigated.Add(fun _ -> Console.WriteLine("Done navigating"))
       browser.Navigate(uri)

   do run();

[<EntryPoint;STAThread>]
let main argv =
    BrowserApplication().Run()
```

Body:
I have a .netcoreapp3.1 Console App

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWpf>true</UseWpf>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>
</Project>

In Program.fs, I am instantiating a WebBrowser control and handling the DocumentCompleted event

let run() =
    let uri = "https://www.microsoft.com"
    let browser = new WebBrowser()
    browser.DocumentCompleted.Add(fun _ -> handlePage browser uris)
    browser.Navigate(uri)

[<STAThread>]
[<EntryPoint>]
let main argv =
    run()
    Console.ReadKey() |> ignore
    0

When I run it, the DocumentCompleted event is never fired or handled - the program runs through to the end.

Am I missing?

Thanks in advance.


问:
Ninject MVC3 - bootstrapper throwing "Already Initialized" exception
I've created an empty Asp.Net MVC3 project, and used nuget install-package Ninject.MVC3

Without doing anything else (no services registered and not even a controller created) I run the application.

The Project breaks on line 22 in NinjectMVC3.cs with the following exception:

[InvalidOperationException: Already Initialized!]
     Ninject.Web.Mvc.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Maintenance2.2\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\Bootstrapper.cs> :58
     Mvc.App_Start.NinjectMVC3.Start() in c:\Projects\Events\Events\App_Start\NinjectMVC3.cs:22

[TargetInvocationException: Exception
  has been thrown by the target of an
  invocation.]

  System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo
  method, Object target, Object[]
  arguments, SignatureStruct& sig,
  MethodAttributes methodAttributes,
  RuntimeType typeOwner) +0

  System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo
  method, Object target, Object[]
  arguments, Signature sig,
  MethodAttributes methodAttributes,
  RuntimeType typeOwner) +72

  System.Reflection.RuntimeMethodInfo.Invoke(Object
  obj, BindingFlags invokeAttr, Binder
  binder, Object[] parameters,
  CultureInfo culture, Boolean
  skipVisibilityChecks) +335

  System.Reflection.RuntimeMethodInfo.Invoke(Object
  obj, BindingFlags invokeAttr, Binder
  binder, Object[] parameters,
  CultureInfo culture) +28

  System.Reflection.MethodBase.Invoke(Object
  obj, Object[] parameters) +19

  WebActivator.BaseActivationMethodAttribute.InvokeMethod()
  +199    WebActivator.ActivationManager.RunActivationMethods()
  +330    WebActivator.ActivationManager.RunPreStartMethods()
  +27    WebActivator.ActivationManager.Run()
  +39

The line in NinjectMVC3.cs is:

```<code>public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
            bootstrapper.Initialize(CreateKernel); // <- this one right here...
        }
</code>```

What is going on with this? I've used Ninject for MVC3 in other projects without problems at all. I do notice that the second line in the Start() method is not included in older (weeks) packages of Ninject.MVC3, so maybe something else has been broken in a recent update also?

Please help!

Edit to address answer from Remo

This is from my global.asax.cs

```<code> public class MvcApplication : System.Web.HttpApplication
 {
</code>```

The global.asax is 100% standard aswell. No adjustments done.

EDIT - Problem is gone...

I honestly have no idea what caused this, but after a few restarts of Visual Studio, and a full reboot, the project is working as it should. Neither can I recreate the problem in new projects.

Sorry for wasting your time :)

答:
I had the same issue with some slight differences I was inheriting from NinjectHttpApplication and overriding OnApplicationStarted.
I resolved the issue by downloading from https://github.com/ninject/ninject.web.mvc instead of using the nuget package.

I didn't have to do anything after I added the references.

Body:
I've created an empty Asp.Net MVC3 project, and used nuget install-package Ninject.MVC3

Without doing anything else (no services registered and not even a controller created) I run the application.

The Project breaks on line 22 in NinjectMVC3.cs with the following exception:

[InvalidOperationException: Already Initialized!]
     Ninject.Web.Mvc.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Maintenance2.2\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\Bootstrapper.cs> :58
     Mvc.App_Start.NinjectMVC3.Start() in c:\Projects\Events\Events\App_Start\NinjectMVC3.cs:22

[TargetInvocationException: Exception
  has been thrown by the target of an
  invocation.]

  System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo
  method, Object target, Object[]
  arguments, SignatureStruct& sig,
  MethodAttributes methodAttributes,
  RuntimeType typeOwner) +0

  System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo
  method, Object target, Object[]
  arguments, Signature sig,
  MethodAttributes methodAttributes,
  RuntimeType typeOwner) +72

  System.Reflection.RuntimeMethodInfo.Invoke(Object
  obj, BindingFlags invokeAttr, Binder
  binder, Object[] parameters,
  CultureInfo culture, Boolean
  skipVisibilityChecks) +335

  System.Reflection.RuntimeMethodInfo.Invoke(Object
  obj, BindingFlags invokeAttr, Binder
  binder, Object[] parameters,
  CultureInfo culture) +28

  System.Reflection.MethodBase.Invoke(Object
  obj, Object[] parameters) +19

  WebActivator.BaseActivationMethodAttribute.InvokeMethod()
  +199    WebActivator.ActivationManager.RunActivationMethods()
  +330    WebActivator.ActivationManager.RunPreStartMethods()
  +27    WebActivator.ActivationManager.Run()
  +39

The line in NinjectMVC3.cs is:

public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
            bootstrapper.Initialize(CreateKernel); // <- this one right here...
        }

What is going on with this? I've used Ninject for MVC3 in other projects without problems at all. I do notice that the second line in the Start() method is not included in older (weeks) packages of Ninject.MVC3, so maybe something else has been broken in a recent update also?

Please help!

Edit to address answer from Remo

This is from my global.asax.cs

 public class MvcApplication : System.Web.HttpApplication
 {

The global.asax is 100% standard aswell. No adjustments done.

EDIT - Problem is gone...

I honestly have no idea what caused this, but after a few restarts of Visual Studio, and a full reboot, the project is working as it should. Neither can I recreate the problem in new projects.

Sorry for wasting your time :)


问:
Color Bar - Bar Color: How to mix colour-logic from different Indicators?
I try to set barcolor and other ways to paint the bars in TV.

A WaveMaster indicator paints bars Green if above an MA and Red if below, as shown in :
https://www.tradingview.com/script/fn1iJVeQ-Wave-Master/

Another indicator paints the bar, where the RSI is above/below some fixed horizontal levels, otherwise it paints them of another color.

The script is below:

```<code>//@version=4
study("RSI", overlay=true)

len   = input( 14, minval = 1, title = "RSI Length" )
src   = input( close, title = "RSI Source" )
up    = rma(  max( change( src ), 0 ), len )
down  = rma( -min( change( src ), 0 ), len )
rsi   = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
panic = ( rsi < 35 or rsi > 80 )

barcolor( panic ? #DC143C : #FFA07A, offset = 0 )
</code>```

If I put both indicators on, it happens that ( of course ) the last to be added will override the colouring of the candles and hide the other one, I don't know how to do it but I saw someone that has his charts with multiple colors on its candles ( 3 I'm sure );

I'd like to ask if you can help to have the first indicator ( the Wave Master ) as is, but also add another colouring, if the RSI conditions are met, that overrides the colouring of Red/Green and paints the candles in another color.

Pretty much merging the two indicators into one.

Also, if possible, in the Wave Master, since I have the condition if price above MA green else Red, what happens is that for newly listed assets since there's no moving avg yet, it automatically paints everything red, is there the possibility to rewrite the colouring in another way so that if there's no SMA yet, it won't apply any color, if it's not too complex maybe just paints the bars if the RSI condition is met.

```<code>//@version=1
study(title="Wave Master", shorttitle="Wave Master", overlay=true)
len = input(60, minval=1, title="MA Periods")
src = close
out = sma(src, len)
up = out > out[1]
down = out < out[1]
mycolor = up ? #0ea95a : down ? red : blue
plot(out  ? out :na , title="MA", color=mycolor, linewidth=3)

len1 = input(200, minval=1, title="Macro MA Periods")
src1 = close
out1 = sma(src1, len1)
up1 = out1 > out1[1]
down1 = out1 < out1[1]
mycolor1 = up1 ? #0ea95a : down1 ? #ef5350 : blue
plot(out1  ? out1 :na , title="Macro MA", color=mycolor1, linewidth=1)
barcolor(close > sma(close, len) ? #46B698 : #ED5454)
</code>```

答:
Replace the last line of the RSI script with:

```<code>barcolor(panic ? #DC143C : na)
</code>```

This will only color bars when RSI is OS or OB.

As for the other indicator, its source is not available, so it can't be modified.

Body:
I try to set barcolor and other ways to paint the bars in TV.

A WaveMaster indicator paints bars Green if above an MA and Red if below, as shown in :
https://www.tradingview.com/script/fn1iJVeQ-Wave-Master/

Another indicator paints the bar, where the RSI is above/below some fixed horizontal levels, otherwise it paints them of another color.

The script is below:

//@version=4
study("RSI", overlay=true)

len   = input( 14, minval = 1, title = "RSI Length" )
src   = input( close, title = "RSI Source" )
up    = rma(  max( change( src ), 0 ), len )
down  = rma( -min( change( src ), 0 ), len )
rsi   = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
panic = ( rsi < 35 or rsi > 80 )

barcolor( panic ? #DC143C : #FFA07A, offset = 0 )

If I put both indicators on, it happens that ( of course ) the last to be added will override the colouring of the candles and hide the other one, I don't know how to do it but I saw someone that has his charts with multiple colors on its candles ( 3 I'm sure );

I'd like to ask if you can help to have the first indicator ( the Wave Master ) as is, but also add another colouring, if the RSI conditions are met, that overrides the colouring of Red/Green and paints the candles in another color.

Pretty much merging the two indicators into one.

Also, if possible, in the Wave Master, since I have the condition if price above MA green else Red, what happens is that for newly listed assets since there's no moving avg yet, it automatically paints everything red, is there the possibility to rewrite the colouring in another way so that if there's no SMA yet, it won't apply any color, if it's not too complex maybe just paints the bars if the RSI condition is met.

//@version=1
study(title="Wave Master", shorttitle="Wave Master", overlay=true)
len = input(60, minval=1, title="MA Periods")
src = close
out = sma(src, len)
up = out > out[1]
down = out < out[1]
mycolor = up ? #0ea95a : down ? red : blue
plot(out  ? out :na , title="MA", color=mycolor, linewidth=3)

len1 = input(200, minval=1, title="Macro MA Periods")
src1 = close
out1 = sma(src1, len1)
up1 = out1 > out1[1]
down1 = out1 < out1[1]
mycolor1 = up1 ? #0ea95a : down1 ? #ef5350 : blue
plot(out1  ? out1 :na , title="Macro MA", color=mycolor1, linewidth=1)
barcolor(close > sma(close, len) ? #46B698 : #ED5454)

Body:
Replace the last line of the RSI script with:

barcolor(panic ? #DC143C : na)

This will only color bars when RSI is OS or OB.

As for the other indicator, its source is not available, so it can't be modified.


问:
How to apply assert condition to change list?
For this method I am supposed to duplicate the elements of a list that satisfy the condition that is expressed in the assert statement. Here is the skeleton:

```<code>let rec cond_dup l f =
  (* YOUR CODE HERE *)
   raise (Failure "Not implemented")
assert (cond_dup [3;4;5] (fun x -> x mod 2 = 1) = [3;3;4;5;5])
</code>```

For some reason my code keeps failing, but i don't understand why. I am currently learning OCaml but I am having  difficult time understanding it especially when there are one or more assert statements. Here is the code that I wrote so far:

```<code>let rec cond_dup l f =
  (* YOUR CODE HERE *)
  match l with
  | [] -> []
  |h::[] ->
    if f h then h::h::[]
    else h::[]
  |h::t ->
    if f h then h::h::(cond_dup t f)
    else (cond_dup t f)

  let f()= raise (Failure "Not implemented1")

let f() = assert (cond_dup [3;4;5] (fun x -> x mod 2 = 1) = [3;3;4;5;5])
;;

Please if you can tell me what I am doing wrong that would be great.
</code>```

答:
Your code duplicates the elements that satisfy the predicate. But it's also supposed to leave unchanged the elements that don't satisfy the predictate. You are deleting those elements instead. Think about the last line of your function. That's where the deletion (effectively) is happening.

(Since your code is effectively copying the list with modifications, the way to delete an element is simply not to include it in the copy. That's what you're doing.)

As a side comment, there's nothing fancy or mysterious going on with the assert. It's just a line of code that tests whether your function works for one particular input. If the assert fails, your function has an error.

Body:
For this method I am supposed to duplicate the elements of a list that satisfy the condition that is expressed in the assert statement. Here is the skeleton:

let rec cond_dup l f =
  (* YOUR CODE HERE *)
   raise (Failure "Not implemented")
assert (cond_dup [3;4;5] (fun x -> x mod 2 = 1) = [3;3;4;5;5])

For some reason my code keeps failing, but i don't understand why. I am currently learning OCaml but I am having  difficult time understanding it especially when there are one or more assert statements. Here is the code that I wrote so far:

let rec cond_dup l f =
  (* YOUR CODE HERE *)
  match l with
  | [] -> []
  |h::[] ->
    if f h then h::h::[]
    else h::[]
  |h::t ->
    if f h then h::h::(cond_dup t f)
    else (cond_dup t f)

  let f()= raise (Failure "Not implemented1")

let f() = assert (cond_dup [3;4;5] (fun x -> x mod 2 = 1) = [3;3;4;5;5])
;;

Please if you can tell me what I am doing wrong that would be great.


问:
Understanding how scoped arrays are stored
I'm confused how arrays are stored in the executable when they're within functions and the like.

With the code below I believe space for the value of the three ints to be stored is made in the executable.

```<code>#include <stdlib.h>

int main() {
    int arr[] = {rand(), rand(), rand()};
}
</code>```

I was thinking for an array in a function, each call would use the same space as the other calls to store their array. But then I thought recursive calls would overwrite each others arrays. I don't get how space for them is left aside, especially with recursion and an unknown number of calls are made. I tried to make an example:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool myfunc(unsigned val) {
    int arr[] = {rand() % 10, rand() % 10};

    if (val == 0)
        return true;

    myfunc(val - 1);

    printf("%d %d\n", arr[0], arr[1]);
    return false;
}

int main() {
    myfunc(rand() % 50);
}
</code>```

I get arrays elements are stored one after the other. But how is there space for them (in the stack?) when it's unkown how many there will be?

答:
Objects defined with local scope in a function body with automatic storage (without a static keyword) are stored in temporary storage and reclaimed automatically upon exiting the corresponding scope.

Typical modern architectures use the runtime stack for this: the stack pointer register is decremented upon entering the scope by a fixed amount if the size is known at compile time, as is the case for your examples: int arr[] = {rand() % 10, rand() % 10}; defines an array of 2 int, usually 8 bytes.

If the size is only known at runtime, the stack pointer is decremented by a value computed at runtime, possibly causing undefined behavior if this size is too large. The stack pointer is restored to its original value upon leaving the function.

Body:
I'm confused how arrays are stored in the executable when they're within functions and the like.

With the code below I believe space for the value of the three ints to be stored is made in the executable.

#include <stdlib.h>

int main() {
    int arr[] = {rand(), rand(), rand()};
}

I was thinking for an array in a function, each call would use the same space as the other calls to store their array. But then I thought recursive calls would overwrite each others arrays. I don't get how space for them is left aside, especially with recursion and an unknown number of calls are made. I tried to make an example:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool myfunc(unsigned val) {
    int arr[] = {rand() % 10, rand() % 10};

    if (val == 0)
        return true;

    myfunc(val - 1);

    printf("%d %d\n", arr[0], arr[1]);
    return false;
}

int main() {
    myfunc(rand() % 50);
}

I get arrays elements are stored one after the other. But how is there space for them (in the stack?) when it's unkown how many there will be?


问:
Problem when linking c++ program with lpsolve api
I'm facing some issues when linking my c++ program, here is what I do :
g++ tp.cpp -llpsolve55 -lcolamd -ldl -o MyExe
and the command-line return me this :

/usr/bin/ld: cannot find -llpsolve
collect2: error: ld returned 1 exit status

But I've already installed lpsolve, it appear in Synapatic as installed and I even installed it via the terminal

答:
If /usr/lib/lp_solve is not in the normal search path for libraries, you can add that path to your executeable when linking. Also note that libraries should typically come last:

```<code>g++ -o MyExe tp.cpp -L /usr/lib/lp_solve  -Wl,-rpath,/usr/lib/lp_solve -llpsolve55 -lcolamd
</code>```

The -L argument adds the directory to the list of directories to look for libraries in when doing the linking.

-Wl tells the compiler to pass on what follows to the linker.

The linkers -rpath,<path> argument tells it to add <path> to MyExe so it can find the library when you later run the program.

Body:
If /usr/lib/lp_solve is not in the normal search path for libraries, you can add that path to your executeable when linking. Also note that libraries should typically come last:

g++ -o MyExe tp.cpp -L /usr/lib/lp_solve  -Wl,-rpath,/usr/lib/lp_solve -llpsolve55 -lcolamd

The -L argument adds the directory to the list of directories to look for libraries in when doing the linking.

-Wl tells the compiler to pass on what follows to the linker.

The linkers -rpath,<path> argument tells it to add <path> to MyExe so it can find the library when you later run the program.


问:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.

I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others can benefit from that, but I'm curious if there's any preferred way in the Open Source community to deal with this problem.

I have been reading here and there in the python.org site and in some other websites, but I haven't found anything conclusive.  The only thing that I found is that this is a chicken-and-egg problem.

It's out of the question (unless there's no other option) that I ship a dump of a library with my own modifications just to make it 3.x compliant.

Should I...

prepare all the code with __future imports and change here and there appropriately and leave it ready to work with both 2.x and 3.x?  Am I going to find any problem with this, other than the natural resistance of upstream to integrate such amount of changes?

create another branch of the code?  That, to me, should be quite useless, as nobody will maintain that branch except me, probably, and it's a huge duplication effort.

use some type of wrapper that I am not aware of to use those libraries as-is (like using some intermediate bindings in another language) and just create the glue in my code?

Many thanks!

答:
The approach I've been using is to maintain the code in version 2 format, use the 2to3 converter, and test the output in version 3. If there are errors with the generated version 3 code, I work with the version 2 code to get a better conversion until it works. The Python wiki has some good advice on this: http://wiki.python.org/moin/Python2orPython3

PEP 3000 also has some good advice on maintaining a dual-version codebase.

When your library is finally 3.x-ready, (maybe doing it yourself) then you have a 3.x codebase ready to go.


问:
Can't convert time strings from csv to datetime
I have a csv file with 2 timestamps per row consisting of date, time and a value:

```<code>02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456
</code>```

When I try to convert date and time string to datetime:

```<code>with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)
</code>```

I got:

```<code>Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'
</code>```

Why is that? When I try something like

```<code>date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')
</code>```

it works fine.

EDIT:
I swapped format and time string and used some other data:

```<code>02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994
</code>```

Error is still:

```<code>Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'
</code>```

Seems to be the 00:25:03. But %I is the 24hour format.

答:
I think the reason the reason this works for an example like 02.04.2019 01:30:30 but not 03.04.2019 00:25:03 is because the hour number should be between 0 and 23 for %H and 1 to 12 for %I, you can find a table of this here. This is because %H represents an hour in 24-hour format while %I represents the hour in 12-hour format.

To fix this, you should set your format string to '%d.%m.%Y %H:%M:%S' instead of '%d.%m.%Y %I:%M:%S'.

By the way, if you're the one recording these timestamps and therefore have control over how they are recorded, I recommend using Unix Timestamps instead. This is because they are much easier to convert back and forth and leave no ambiguity about the time zone of these timestamps. If you decide to do this however, be sure to localize your datetime objects before you actually save them to the CSV file as unix timestamps. This question has a lot of wonderful examples of how you can do this.

Body:
I have a csv file with 2 timestamps per row consisting of date, time and a value:

02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456

When I try to convert date and time string to datetime:

with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)

I got:

Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'

Why is that? When I try something like

date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')

it works fine.

EDIT:
I swapped format and time string and used some other data:

02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994

Error is still:

Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'

Seems to be the 00:25:03. But %I is the 24hour format.


问:
Flask: problem with returning binary file to the client
I'm loading an archive from Github and want to return it to the browser to download.
I successfully get the file and can save it to the local disc (I can open the archive and it's normal - size and content):

```<code>headers = {'Authorization': 'token ' + github_token}
zip_response = requests.get(github_url, headers = headers)

output = open("archive.zip", "wb")
output.write(zip_response.content)
output.close()
</code>```

But when I return it to the client, it's bigger almost twice and archive is corrupted:

```<code>zip_content = io.BytesIO(zip_response.content)
return send_file(zip_content,
                 mimetype='application/zip',
                 attachment_filename = 'archive.zip')
</code>```

Javascript:

```<code>var url = window.URL.createObjectURL(new Blob([response.data]), {type: 'application/zip'});
var link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'archive.zip');
document.body.appendChild(link);
link.click();
</code>```

I was trying to use other solutions from this problem: Download File from Bytes in JavaScript

but nothing works.

This just returns 0 bytes:

```<code>var bytes = new Uint8Array(response.data)
</code>```

This throws the exeption "Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.":

```<code>var binaryString = window.atob(response.data);
</code>```

Upd: I found response.data has the normal length but when I create a new Blob object it's 2 times more, I don't know why.

答:
You're not showing us how you're getting your response.data,  but my guess is that you're not setting the responseType property of your xhr object (or you're relying on an old XMLHttpRequest).

Here's a full working example (tested in latest Firefox and Chrome) based on your code:

```<code>import io
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/')
def home():
    return  """
<!doctype html>
<html>
<head>
<script>
function getZip() {
       var xhr = new XMLHttpRequest();
       xhr.responseType = 'blob'
       xhr.open('GET', '/sampleZip');
       xhr.onload = function(e) {
           if (this.status == 200) {
              var blob = new Blob([this.response], {type: 'application/zip'});
              var url = window.URL.createObjectURL(blob);
              var link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', 'archive.zip');
              document.body.appendChild(link);
              link.click();
           }
       };
       xhr.send();
       return false;
}
</script>
</head>
<body>
  <button id="btn" onclick="getZip();">Click Me</button>
</body>
</html>"""

@app.route('/sampleZip')
def sampleZip():
    with open("sample.zip", "rb") as f:
        bytes = io.BytesIO(f.read())
    return send_file(bytes, mimetype='application/zip')
</code>```

If you're stuck relying on an old XMLHttpRequest object then you might want to have a look here (https://www.html5rocks.com/en/tutorials/file/xhr2/) for a hack on getting an old school XHR to treat data as binary and leave it untouched.

Body:
I'm loading an archive from Github and want to return it to the browser to download.
I successfully get the file and can save it to the local disc (I can open the archive and it's normal - size and content):

headers = {'Authorization': 'token ' + github_token}
zip_response = requests.get(github_url, headers = headers)

output = open("archive.zip", "wb")
output.write(zip_response.content)
output.close()

But when I return it to the client, it's bigger almost twice and archive is corrupted:

zip_content = io.BytesIO(zip_response.content)
return send_file(zip_content,
                 mimetype='application/zip',
                 attachment_filename = 'archive.zip')

Javascript:

var url = window.URL.createObjectURL(new Blob([response.data]), {type: 'application/zip'});
var link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'archive.zip');
document.body.appendChild(link);
link.click();

I was trying to use other solutions from this problem: Download File from Bytes in JavaScript

but nothing works.

This just returns 0 bytes:

var bytes = new Uint8Array(response.data)

This throws the exeption "Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.":

var binaryString = window.atob(response.data);

Upd: I found response.data has the normal length but when I create a new Blob object it's 2 times more, I don't know why.

Body:
You're not showing us how you're getting your response.data,  but my guess is that you're not setting the responseType property of your xhr object (or you're relying on an old XMLHttpRequest).

Here's a full working example (tested in latest Firefox and Chrome) based on your code:

import io
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/')
def home():
    return  """
<!doctype html>
<html>
<head>
<script>
function getZip() {
       var xhr = new XMLHttpRequest();
       xhr.responseType = 'blob'
       xhr.open('GET', '/sampleZip');
       xhr.onload = function(e) {
           if (this.status == 200) {
              var blob = new Blob([this.response], {type: 'application/zip'});
              var url = window.URL.createObjectURL(blob);
              var link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', 'archive.zip');
              document.body.appendChild(link);
              link.click();
           }
       };
       xhr.send();
       return false;
}
</script>
</head>
<body>
  <button id="btn" onclick="getZip();">Click Me</button>
</body>
</html>"""

@app.route('/sampleZip')
def sampleZip():
    with open("sample.zip", "rb") as f:
        bytes = io.BytesIO(f.read())
    return send_file(bytes, mimetype='application/zip')

If you're stuck relying on an old XMLHttpRequest object then you might want to have a look here (https://www.html5rocks.com/en/tutorials/file/xhr2/) for a hack on getting an old school XHR to treat data as binary and leave it untouched.


问:
Azure Blob Storage "Authorization Permission Mismatch" error for get request with AD token
I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.

When trying to read a file that I have inside the storage for test purposes, I'm getting: AuthorizationPermissionMismatch
<Message>This request is not authorized to perform this operation using this permission.

All in production environment (although developing)

Token acquired specifically for storage resource via Oauth

Postman has the token strategy as "bearer "

Application has "Azure Storage" delegated permissions granted.

Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM

My IP is added to CORS settings on the blob storage.

StorageV2 (general purpose v2)  - Standard - Hot

x-ms-version header used is: 2018-03-28 because that's the latest I could find and I just created the storage account.

答:
Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
https://github.com/Azure/azure-sdk-for-net/issues/8658
For further reading on V12 and V11 SDK

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet

```<code>using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;

[Fact]
public async Task TestStreamToContainer()
        {
            try
            {
                var accountName = "YourStorageAccountName";
                var containerName = "YourContainerName";
                var blobName = "File1";
                var provider = new AzureServiceTokenProvider();
                var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
                var tokenCredential = new TokenCredential(token);
                var storageCredentials = new StorageCredentials(tokenCredential);

                string containerEndpoint = $"https://{accountName}.blob.core.windows.net";

                var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
                var containerClient = blobClient.GetContainerReference(containerName);
                var cloudBlob = containerClient.GetBlockBlobReference(blobName);

                string blobContents = "This is a block blob contents.";
                byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    await cloudBlob.UploadFromStreamAsync(stream);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
</code>```

Body:
Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
https://github.com/Azure/azure-sdk-for-net/issues/8658
For further reading on V12 and V11 SDK

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet

using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;

[Fact]
public async Task TestStreamToContainer()
        {
            try
            {
                var accountName = "YourStorageAccountName";
                var containerName = "YourContainerName";
                var blobName = "File1";
                var provider = new AzureServiceTokenProvider();
                var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
                var tokenCredential = new TokenCredential(token);
                var storageCredentials = new StorageCredentials(tokenCredential);

                string containerEndpoint = $"https://{accountName}.blob.core.windows.net";

                var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
                var containerClient = blobClient.GetContainerReference(containerName);
                var cloudBlob = containerClient.GetBlockBlobReference(blobName);

                string blobContents = "This is a block blob contents.";
                byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    await cloudBlob.UploadFromStreamAsync(stream);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }