问:
In redux-observable - How can I dispatch an action "mid-stream" without returning the value of that action?
I have searched everywhere and cannot find an answer to the following...

In my addItemEpic I would like to dispatch a "loading" action before sending the ajax request - I DO NOT want the value of the action to be returned - I just want to DO the action then return the ajax response.
This can be achieved easily with store.dispatch() as below:

```<code>export const addItemsEpic = (action$, store) =>
  action$.ofType(ADD_ITEM)
    .do(() => store.dispatch({
        type: 'layout/UPDATE_LAYOUT',
        payload: { loading: true }
    }))
    .switchMap(action => api.addItem(action.payload))
    .map(item => loadItem(item))
    .do(() => store.dispatch({
       type: 'layout/UPDATE_LAYOUT',
       payload: { loading: false }
    }))
    .catch(error => Observable.of({
       type: 'AJAX_ERROR',
       payload: error,
       error: true
   }));
</code>```

However store.dispatch() is deprecated and discouraged in redux-observable.

I have attempted to use almost every plausible operator and still I cannot dispatch the action without disrupting the return value in the next chained function. I thought something like te following should do it:

```<code>action$.ofType(ADD_ITEM)
   .concatMap(action => Observable.of(
      updateLayout({loading: true}),
      api.addItem(action.payload)).last())
   .map(item => loadItem(item))
</code>```

But unfortunately 2 problems here:

no loading-action is dispatched (the value IS returned as an observable)

api request now returns a wrapped promise instead of a mappable value

I'd really appreciate some help or advice here as I can't find any way to get this working.

Thanks in advance

答:
Robert's answer is great and the correct one. Here are a few extra thoughts I had:

Reuse existing actions

Very often when you find yourself synchronously following one action after another this is a sign that your reducer should only need the first one.

e.g. instead of having layout/UPDATE_LAYOUT to set loading: true, your reducer could just know that whenever there's an ADD_ITEM and LOAD_ITEM that means it should be loading: true. If that implicitness isn't your bag, your could instead use extra metadata as the signal rather than the action type itself.

```<code>const layoutReducer = (state = { loading: false }, action) => {
  // instead of listening for an action type, we're looking for some other
  // metadata by convention. In this case the `layout` property.
  if (action.layout) {
    return { ...state, ...action.layout };
  } else {
    return state;
  }
};

// the schema you use (payload vs layout vs metadata, etc) is your call
store.dispatch({
  type: 'DOESNT_MATTER',
  payload: 'whatever',
  layout: { loading: true }
});
</code>```

All that said, your example may have been simplified to make it easier to ask on SO (a great idea). Sometimes it does indeed make sense to have them separate actions for clarity, separation of concerns, reusablity, or simply because you have to because you don't control the library that is listening for it. e.g. react-router-redux you need to dispatch special actions to do route transitions.

So think of this just as "keep it in mind" advice rather than doctrine :)

concat

concat supports any number of arguments, so you only need one of them:

```<code>const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action => {
    const apiCall$ = Observable.fromPromise(api.addItem(action.payload))
      .map(item => actions.loadItem(item))
      .catch(err => Observable.of(actions.ajaxError(err)));

    return Observable.concat(
      Observable.of(actions.updateLayout(true)),
      apiCall$,
      Observable.of(actions.updateLayout(false))
    );
  });

// or

const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action =>
    Observable.concat(
      Observable.of(actions.updateLayout(true))
      Observable.fromPromise(api.addItem(action.payload))
        .map(item => actions.loadItem(item))
        .catch(err => Observable.of(actions.ajaxError(err))),
      Observable.of(actions.updateLayout(false))
    )
  );
</code>```

Body:
I have searched everywhere and cannot find an answer to the following...

In my addItemEpic I would like to dispatch a "loading" action before sending the ajax request - I DO NOT want the value of the action to be returned - I just want to DO the action then return the ajax response.
This can be achieved easily with store.dispatch() as below:

export const addItemsEpic = (action$, store) =>
  action$.ofType(ADD_ITEM)
    .do(() => store.dispatch({
        type: 'layout/UPDATE_LAYOUT',
        payload: { loading: true }
    }))
    .switchMap(action => api.addItem(action.payload))
    .map(item => loadItem(item))
    .do(() => store.dispatch({
       type: 'layout/UPDATE_LAYOUT',
       payload: { loading: false }
    }))
    .catch(error => Observable.of({
       type: 'AJAX_ERROR',
       payload: error,
       error: true
   }));

However store.dispatch() is deprecated and discouraged in redux-observable.

I have attempted to use almost every plausible operator and still I cannot dispatch the action without disrupting the return value in the next chained function. I thought something like te following should do it:

action$.ofType(ADD_ITEM)
   .concatMap(action => Observable.of(
      updateLayout({loading: true}),
      api.addItem(action.payload)).last())
   .map(item => loadItem(item))

But unfortunately 2 problems here:

no loading-action is dispatched (the value IS returned as an observable)

api request now returns a wrapped promise instead of a mappable value

I'd really appreciate some help or advice here as I can't find any way to get this working.

Thanks in advance

Body:
Robert's answer is great and the correct one. Here are a few extra thoughts I had:

Reuse existing actions

Very often when you find yourself synchronously following one action after another this is a sign that your reducer should only need the first one.

e.g. instead of having layout/UPDATE_LAYOUT to set loading: true, your reducer could just know that whenever there's an ADD_ITEM and LOAD_ITEM that means it should be loading: true. If that implicitness isn't your bag, your could instead use extra metadata as the signal rather than the action type itself.

const layoutReducer = (state = { loading: false }, action) => {
  // instead of listening for an action type, we're looking for some other
  // metadata by convention. In this case the `layout` property.
  if (action.layout) {
    return { ...state, ...action.layout };
  } else {
    return state;
  }
};

// the schema you use (payload vs layout vs metadata, etc) is your call
store.dispatch({
  type: 'DOESNT_MATTER',
  payload: 'whatever',
  layout: { loading: true }
});

All that said, your example may have been simplified to make it easier to ask on SO (a great idea). Sometimes it does indeed make sense to have them separate actions for clarity, separation of concerns, reusablity, or simply because you have to because you don't control the library that is listening for it. e.g. react-router-redux you need to dispatch special actions to do route transitions.

So think of this just as "keep it in mind" advice rather than doctrine :)

concat

concat supports any number of arguments, so you only need one of them:

const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action => {
    const apiCall$ = Observable.fromPromise(api.addItem(action.payload))
      .map(item => actions.loadItem(item))
      .catch(err => Observable.of(actions.ajaxError(err)));

    return Observable.concat(
      Observable.of(actions.updateLayout(true)),
      apiCall$,
      Observable.of(actions.updateLayout(false))
    );
  });

// or

const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action =>
    Observable.concat(
      Observable.of(actions.updateLayout(true))
      Observable.fromPromise(api.addItem(action.payload))
        .map(item => actions.loadItem(item))
        .catch(err => Observable.of(actions.ajaxError(err))),
      Observable.of(actions.updateLayout(false))
    )
  );


来源: stackexchange

问:
Swap two values randomly in list
I have the following list:

```<code>a = [1, 2, 5, 4, 3, 6]
</code>```

And I want to know how I can swap any two values at a time randomly within a list regardless of position within the list. Below are a few example outputs on what I'm thinking about:

```<code>[1, 4, 5, 2, 3, 6]
[6, 2, 3, 4, 5, 1]
[1, 6, 5, 4, 3, 2]
[1, 3, 5, 4, 2, 6]
</code>```

Is there a way to do this in Python 2.7? My current code is like this:

```<code>import random
n = len(a)
if n:
    i = random.randint(0,n-1)
    j = random.randint(0,n-1)
    a[i] += a[j]
    a[j] = a[i] - a[j]
    a[i] -= a[j]
</code>```

The issue with the code I currently have, however, is that it starts setting all values to zero given enough swaps and iterations, which I do not want; I want the values to stay the same in the array, but do something like 2opt and only switch around two with each swap.

答:
You are over-complicating it, it seems. Just randomly sample two indices from the list, then swap the values at those indicies:

```<code>>>> def swap_random(seq):
...     idx = range(len(seq))
...     i1, i2 = random.sample(idx, 2)
...     seq[i1], seq[i2] = seq[i2], seq[i1]
...
>>> a
[1, 2, 5, 4, 3, 6]
>>> swap_random(a)
>>> a
[1, 2, 3, 4, 5, 6]
>>> swap_random(a)
>>> a
[1, 2, 6, 4, 5, 3]
>>> swap_random(a)
>>> a
[1, 2, 6, 5, 4, 3]
>>> swap_random(a)
>>> a
[6, 2, 1, 5, 4, 3]
</code>```

Note, I used the Python swap idiom, which doesn't require an intermediate variable. It is equivalent to:

```<code>temp = seq[i1]
seq[i1] = seq[i2]
seq[i2] = temp
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swap two values randomly in list

Body:
I have the following list:

a = [1, 2, 5, 4, 3, 6]

And I want to know how I can swap any two values at a time randomly within a list regardless of position within the list. Below are a few example outputs on what I'm thinking about:

[1, 4, 5, 2, 3, 6]
[6, 2, 3, 4, 5, 1]
[1, 6, 5, 4, 3, 2]
[1, 3, 5, 4, 2, 6]

Is there a way to do this in Python 2.7? My current code is like this:

import random
n = len(a)
if n:
    i = random.randint(0,n-1)
    j = random.randint(0,n-1)
    a[i] += a[j]
    a[j] = a[i] - a[j]
    a[i] -= a[j]

The issue with the code I currently have, however, is that it starts setting all values to zero given enough swaps and iterations, which I do not want; I want the values to stay the same in the array, but do something like 2opt and only switch around two with each swap.

Body:
You are over-complicating it, it seems. Just randomly sample two indices from the list, then swap the values at those indicies:

>>> def swap_random(seq):
...     idx = range(len(seq))
...     i1, i2 = random.sample(idx, 2)
...     seq[i1], seq[i2] = seq[i2], seq[i1]
...
>>> a
[1, 2, 5, 4, 3, 6]
>>> swap_random(a)
>>> a
[1, 2, 3, 4, 5, 6]
>>> swap_random(a)
>>> a
[1, 2, 6, 4, 5, 3]
>>> swap_random(a)
>>> a
[1, 2, 6, 5, 4, 3]
>>> swap_random(a)
>>> a
[6, 2, 1, 5, 4, 3]

Note, I used the Python swap idiom, which doesn't require an intermediate variable. It is equivalent to:

temp = seq[i1]
seq[i1] = seq[i2]
seq[i2] = temp


问:
Check time series incongruencies
Let's say that we have the following matrix:

```<code>x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")
</code>```

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

答:
The aggregate() approach is pretty concise.

Removing bad rows

```<code>good <- do.call(c, aggregate(Age ~ ID, x, function(z) c(z[1], diff(z)) > 0)$Age)

x[good,]
#    ID Visit Age
# 1   A     1  14
# 2   A     2  28
# 3   A     3  42
# 4   B     1  14
# 5   B     2  46
# 6   B     3  64
# 7   B     4  71
# 8   B     5  85
# 9   C     1  14
# 10  C     2  28
# 11  C     3  51
# 12  C     4  84
# 14  D     1  22
# 15  D     2  38
# 17  D     4  40
# 18  D     5  42
</code>```

This will only highlight which groups have an inconsistency:

```<code>aggregate(Age ~ ID, x, function(z) all(diff(z) > 0))
#   ID   Age
# 1  A  TRUE
# 2  B  TRUE
# 3  C FALSE
# 4  D FALSE
</code>```

Title: Check time series incongruencies

Body:
Let's say that we have the following matrix:

x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

Body:
The aggregate() approach is pretty concise.

Removing bad rows

good <- do.call(c, aggregate(Age ~ ID, x, function(z) c(z[1], diff(z)) > 0)$Age)

x[good,]
#    ID Visit Age
# 1   A     1  14
# 2   A     2  28
# 3   A     3  42
# 4   B     1  14
# 5   B     2  46
# 6   B     3  64
# 7   B     4  71
# 8   B     5  85
# 9   C     1  14
# 10  C     2  28
# 11  C     3  51
# 12  C     4  84
# 14  D     1  22
# 15  D     2  38
# 17  D     4  40
# 18  D     5  42

This will only highlight which groups have an inconsistency:

aggregate(Age ~ ID, x, function(z) all(diff(z) > 0))
#   ID   Age
# 1  A  TRUE
# 2  B  TRUE
# 3  C FALSE
# 4  D FALSE


问:
Distinguishing between same exception by where it was called
I have an unavoidable situation that looks like this (simplified):

```<code>FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
  FUNCTION_TO_CALL(args, kargs)

def y(foo, bar=None):
  if foo == bar: # actually not this stupid
    raise TypeError()
  else:
    pass

def z(foo, bar, baz=None):
  pass
</code>```

Horribly ugly, I know. :(

But, at any rate, I need to be able to distinguish between a TypeError being raised in y because *args doesn't have anything in it or having too much in it (thus not having enough arguments or too many)/bad kwargs or because foo == bar.

In the actually setting, there are many more functions that can be called than two, not all of which have the code open to them.

Thanks so much!

答:
Matt Billenstein's comment on Keith Morrow's answer is the right way to do this. But alternatively, if for some bizarre reason you can't even do that, you could also look at the inspect module.

```<code>try: ugly()
except TypeError as e:
    stack = inspect.stack()
    [...look at the stack...]
</code>```

Info about the inspect module.

To elaborate on the "wrapping" question: assuming you have control over what functions are available to be assigned to FUNCTION_TO_CALL, create y_better

```<code>def y_better(foo, bar=None):
    try: y(foo, bar)
    except TypeError:
        if foo == bar: # detect foobar condition
            raise FoobarError()
        else:          # not foobar, so re-raise the exception
            raise
</code>```

This means foo == bar is being tested twice, but given your restrictions, I don't see a better way to do it.

ContentLicense: CC BY-SA 2.5

Body:
I have an unavoidable situation that looks like this (simplified):

FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
  FUNCTION_TO_CALL(args, kargs)

def y(foo, bar=None):
  if foo == bar: # actually not this stupid
    raise TypeError()
  else:
    pass

def z(foo, bar, baz=None):
  pass

Horribly ugly, I know. :(

But, at any rate, I need to be able to distinguish between a TypeError being raised in y because *args doesn't have anything in it or having too much in it (thus not having enough arguments or too many)/bad kwargs or because foo == bar.

In the actually setting, there are many more functions that can be called than two, not all of which have the code open to them.

Thanks so much!

Body:
Matt Billenstein's comment on Keith Morrow's answer is the right way to do this. But alternatively, if for some bizarre reason you can't even do that, you could also look at the inspect module.

try: ugly()
except TypeError as e:
    stack = inspect.stack()
    [...look at the stack...]

Info about the inspect module.

To elaborate on the "wrapping" question: assuming you have control over what functions are available to be assigned to FUNCTION_TO_CALL, create y_better

def y_better(foo, bar=None):
    try: y(foo, bar)
    except TypeError:
        if foo == bar: # detect foobar condition
            raise FoobarError()
        else:          # not foobar, so re-raise the exception
            raise

This means foo == bar is being tested twice, but given your restrictions, I don't see a better way to do it.


问:
How to exit dbshell (SQLite 3) on the command line when using Django?
How do I exit dbshell (SQLite 3) on the command line when using Django?

It's my first time to use the command. I watch a book and am practicing Django at the same time. After I run this command, I have no idea how to leave the environment since I have never learned SQL before.

答: You can just hit the key combination Ctrl + C.

ContentLicense: CC BY-SA 4.0


问:
How to make multiplyList work? Haskell ref: https://en.wikibooks.org/wiki/Haskell/Lists_II
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)
</code>```

I get the following:

```<code>*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>
</code>```

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
</code>```

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:```<code>multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)</code>```

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).

答:
let's take a look at both functions definition

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
multiplyList :: Integer -> [Integer] -> [Integer]
</code>```

now the return type of functions are the some [Integer] . now

```<code>multiplyList m = applyToIntegers ((2*) m)
</code>```

starting from right to left we see that applyToIntegers require 2 argument but given 1 . the expression inside () is calculate and then returned as result.

```<code>multiplyList m = applyToIntegers (2*) m
</code>```

in this point we now the type m is [Integer] and multiplyList require one argument not 2 rewriting the definition for multiplyList

```<code>multiplyList ::[Integer] -> [Integer]
</code>```

result :

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns

multiplyList :: [Integer] -> [Integer]
multiplyList m = applyToIntegers ((2*) m)
</code>```

Body:
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)

I get the following:

*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:
multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).

Body:
let's take a look at both functions definition

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
multiplyList :: Integer -> [Integer] -> [Integer]

now the return type of functions are the some [Integer] . now

multiplyList m = applyToIntegers ((2*) m)

starting from right to left we see that applyToIntegers require 2 argument but given 1 . the expression inside () is calculate and then returned as result.

multiplyList m = applyToIntegers (2*) m

in this point we now the type m is [Integer] and multiplyList require one argument not 2 rewriting the definition for multiplyList

multiplyList ::[Integer] -> [Integer]

result :

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns

multiplyList :: [Integer] -> [Integer]
multiplyList m = applyToIntegers ((2*) m)


问:
Correct way to set checkbox default state using JSX
If HTML5 specifies that there is no value for the "checked" attribute that is reliably interpreted as the checkbox being unchecked*, is the behavior of the following JSX code potentially inconsistent between browsers? (It seems to work as expected for me in Chrome and IE.)

```<code><input type="checkbox" checked={node.props.checked} />
</code>```

If so, what is the standard way to accomplish this, considering that the following JSX is invalid?

```<code><input type="checkbox" {node.props.checked? "checked" : ""} />
</code>```

What values for checked and selected are false?

答:
You will need to conditionally add the entire checked attribute, not just the value of the attribute. That way, if you don't add the attribute at all, you will reliably get an unchecked checkbox.

If you are using ReactJS, then according to this answer:

React is intelligent enough to omit the attribute if the value you
  pass to it is not truthy.

Body:
If HTML5 specifies that there is no value for the "checked" attribute that is reliably interpreted as the checkbox being unchecked*, is the behavior of the following JSX code potentially inconsistent between browsers? (It seems to work as expected for me in Chrome and IE.)

<input type="checkbox" checked={node.props.checked} />

If so, what is the standard way to accomplish this, considering that the following JSX is invalid?

<input type="checkbox" {node.props.checked? "checked" : ""} />

What values for checked and selected are false?


问:
W3CSS: centering input field
Background: Ive done a few small websites using W3CSS, & get my knowledge from this website: https://www.w3schools.com/w3css/w3css_input.asp

Right now, I am starting on a brand new website & having a bit of difficulty centering an input field. (the form doesnt work as yet, i'm just trying to get it to look right).

http://clubs.kwister.com/login

Basically, you can see TWO forms asking for an email address. The first one, is CENTERED, with the input field at 50% width.  However the actual input field where a person enters their email address is flushed to the left.

The second form, I have taken out the width:50%  but now i see an input field taking the whole width of the screen.

Is there something i am missing, to make it look somewhat presentable & have the actual input field centered, but only 40-50% of the width ?

I see from the W3 website that theres no 'width' examples and all the input fields take up 100% of the available width.

i do want white-space on both sides (I may or may not add anything later on to fill the whitespace)

PS I could do the w3-third class (responsive section), and divide the screen into thirds, however i want the form to take up more than a third of the width of the screen.

答:
Ive found a working solution - using INLINE BLOCK.

width: 50%; text-align: center; display: inline-block;

Number 1 of my example is working, i'll edit out the others out.

Title: W3CSS: centering input field


问:
Age select select box without array?
Is there a way of creating an age select list like this:

```<code><?php
$Array = array('99','98','97','96');
?>
<select name="age">
<option value="" selected>Choose</option>
<?php foreach($Array as $value){ echo('<option value="' . $value . '">' . $value . '</option>');}?>
</select>
</code>```

but without a really long array as I want age range to be from say 18 upto 100 and that would take forever to writeout?

答:
Using a basic for loop:

```<code><?php
for($value = 18; $value <= 100; $value++){
    echo('<option value="' . $value . '">' . $value . '</option>');
}
?>
</code>```

Title: Age select select box without array?

Body:
Is there a way of creating an age select list like this:

<?php
$Array = array('99','98','97','96');
?>
<select name="age">
<option value="" selected>Choose</option>
<?php foreach($Array as $value){ echo('<option value="' . $value . '">' . $value . '</option>');}?>
</select>

but without a really long array as I want age range to be from say 18 upto 100 and that would take forever to writeout?

Body:
Using a basic for loop:

<?php
for($value = 18; $value <= 100; $value++){
    echo('<option value="' . $value . '">' . $value . '</option>');
}
?>


问:
Iframe hover opacity change not working in Microsoft Edge
I have a simple class defined in css for an iframe that holds a slideshow pulled from Smugmug.  The basic function is a 25% opacity when the user does not hover over the slideshow and a transition to 100% opacity when the user hovers over the iframe area.  This works in Chrome, Firefox and Safari, but not in Microsoft Edge.  In Edge, I get the 25% opacity and transitions, but the hover does not lift the opacity.

Does anyone know why Edge does not work?  Am I missing some directive for the Edge browser?

Here is an example of the iframe . . .

```<code><div id=avalon class="slide">
  <iframe src="https://johndoc1.smugmug.com/frame/slideshow?   key=M9jkGB&autoStart=1&captions=1&navigation=1&playButton=1&randomize=0&speed=4&transition=fade&transitionSpeed=2" width="1100" height="825" frameborder="no" scrolling="no"></iframe>
</div>
</code>```

Here is the css for the slide class . . .

```<code>/* Slideshow style */

.slide {
width:80%;
margin-left:auto;
margin-right:auto;
background: #2F4538;
   }

.slide iframe{
opacity:0.25;
transition: opacity 0.5s linear;
max-height: 100%;
max-width: 100%;
}

.slide iframe:hover{
    opacity:1.0;
}
</code>```

Thanks.
John Doc

答:
I know that this is actually not very clean, but I tried several things and I was not able to make it run just via css. Maybe Edge is missing some directive in render core ... who knows.

Anyway... I was able to run it via javascript, in this solution I use jQuery as it is closer to me, I will add pure JS solutions as soon as I find, why jsfiddle cannot see my declared functions...

So - here it is:
https://jsfiddle.net/f4y0uugc/2/

note that jQuery code has to be on document ready.

theese are the major changes:

```<code>  $(".slide iframe").on("mouseover", function(){

$(this).addClass("slideiframe");
});

$(".slide iframe").on("mouseout", function(){
$(this).removeClass("slideiframe");
});
</code>```

and css added just

```<code>    .slideiframe{
    opacity:1.0 !important;
}
</code>```

//EDIT - pure JS

Ok, here is a pure solution:
https://jsfiddle.net/f4y0uugc/4/

here you have your JS:

```<code>var slide;

function op025(){
slide = document.getElementsByClassName("slide")[0].getElementsByTagName("iframe")[0];
slide.style.opacity = 0.5;
}

function op1(){
slide = document.getElementsByClassName("slide")[0].getElementsByTagName("iframe")[0];
slide.style.opacity = 1;
}
</code>```

Note, that classes and elements are arrays, yo if you have more than one matches, you will have to add IDs, or iterate in cycle for each solution.

Next, you have to set up calls of functions, so in html:

```<code><div id=avalon class="slide">
  <iframe onmouseover="op1();" onmouseout="op025();" src="https://johndoc1.smugmug.com/frame/slideshow?   key=M9jkGB&autoStart=1&captions=1&navigation=1&playButton=1&randomize=0&speed=4&transition=fade&transitionSpeed=2" width="1100" height="825" frameborder="no" scrolling="no"></iframe>
</div>
</code>```

Also, for both solutions, as this is scripted soltion, I have reduced transition duration to 0.2s as if user quickly moves cursor over the edge, opacity behavior is not clean.

I will try something pure css more, and I will let you know if I find something.

Body:
I have a simple class defined in css for an iframe that holds a slideshow pulled from Smugmug.  The basic function is a 25% opacity when the user does not hover over the slideshow and a transition to 100% opacity when the user hovers over the iframe area.  This works in Chrome, Firefox and Safari, but not in Microsoft Edge.  In Edge, I get the 25% opacity and transitions, but the hover does not lift the opacity.

Does anyone know why Edge does not work?  Am I missing some directive for the Edge browser?

Here is an example of the iframe . . .

Here is the css for the slide class . . .

/* Slideshow style */

.slide {
width:80%;
margin-left:auto;
margin-right:auto;
background: #2F4538;
   }

.slide iframe{
opacity:0.25;
transition: opacity 0.5s linear;
max-height: 100%;
max-width: 100%;
}

.slide iframe:hover{
    opacity:1.0;
}

Thanks.
John Doc

Body:
I know that this is actually not very clean, but I tried several things and I was not able to make it run just via css. Maybe Edge is missing some directive in render core ... who knows.

Anyway... I was able to run it via javascript, in this solution I use jQuery as it is closer to me, I will add pure JS solutions as soon as I find, why jsfiddle cannot see my declared functions...

So - here it is:
https://jsfiddle.net/f4y0uugc/2/

note that jQuery code has to be on document ready.

theese are the major changes:

  $(".slide iframe").on("mouseover", function(){

$(this).addClass("slideiframe");
});

$(".slide iframe").on("mouseout", function(){
$(this).removeClass("slideiframe");
});

and css added just

    .slideiframe{
    opacity:1.0 !important;
}

//EDIT - pure JS

Ok, here is a pure solution:
https://jsfiddle.net/f4y0uugc/4/

here you have your JS:

var slide;

function op025(){
slide = document.getElementsByClassName("slide")[0].getElementsByTagName("iframe")[0];
slide.style.opacity = 0.5;
}

function op1(){
slide = document.getElementsByClassName("slide")[0].getElementsByTagName("iframe")[0];
slide.style.opacity = 1;
}

Note, that classes and elements are arrays, yo if you have more than one matches, you will have to add IDs, or iterate in cycle for each solution.

Next, you have to set up calls of functions, so in html:

<div id=avalon class="slide">
  <iframe onmouseover="op1();" onmouseout="op025();" src="https://johndoc1.smugmug.com/frame/slideshow?   key=M9jkGB&autoStart=1&captions=1&navigation=1&playButton=1&randomize=0&speed=4&transition=fade&transitionSpeed=2" width="1100" height="825" frameborder="no" scrolling="no"></iframe>
</div>

Also, for both solutions, as this is scripted soltion, I have reduced transition duration to 0.2s as if user quickly moves cursor over the edge, opacity behavior is not clean.

I will try something pure css more, and I will let you know if I find something.


问:
How To Convert Oracle SQL Inner Join Statement to Lambda Expression C#
I have been working with Oracle SQL for a while and am currently developing an MVC application in my spare time. At the moment I stuck on an INNER JOIN lambda expression, I have no idea how to convert the SQL statement to C# lambda expression, I've had a look at other answers similar to this question but none provide the answer and a detailed description of how to convert the statement.

Code:

```<code>SELECT
    t.name, t.description
FROM
    TOPICS t
INNER JOIN
    TOPIC_SUBSCRIPTIONS
        ON
    t.TOPICID = TOPIC_SUBSCRIPTIONS.TOPICID
WHERE
    TOPIC_SUBSCRIPTIONS.MEMBERID = 96;
</code>```

答:
Solution 1:

```<code>var q = db.Topics
          .SelectMany(t => t.TopicSubscriptions, (t, ts) => new { t, ts })
          .Where(sub => sub.ts.MemberId == 96)
          .Select(sub => new { sub.t.Name, sub.t.Description });
</code>```

or using LINQ style

```<code>var q = from t in db.Topics
        from ts in topic.Subscriptions
        where ts.MemberId == 96
        select new { t.Name, t.Description };
</code>```

Solution 2

```<code>var q = from t in db.Topics
        join ts in db.TopicSubscriptions on t.TopicId equals ts.TopicId
        into ij
        from tsub in ij
        where tsub.MemberId == 96
        select new { t.Name, t.Description};
</code>```

Body:
I have been working with Oracle SQL for a while and am currently developing an MVC application in my spare time. At the moment I stuck on an INNER JOIN lambda expression, I have no idea how to convert the SQL statement to C# lambda expression, I've had a look at other answers similar to this question but none provide the answer and a detailed description of how to convert the statement.

Code:

SELECT
    t.name, t.description
FROM
    TOPICS t
INNER JOIN
    TOPIC_SUBSCRIPTIONS
        ON
    t.TOPICID = TOPIC_SUBSCRIPTIONS.TOPICID
WHERE
    TOPIC_SUBSCRIPTIONS.MEMBERID = 96;

Body:
Solution 1:

var q = db.Topics
          .SelectMany(t => t.TopicSubscriptions, (t, ts) => new { t, ts })
          .Where(sub => sub.ts.MemberId == 96)
          .Select(sub => new { sub.t.Name, sub.t.Description });

or using LINQ style

var q = from t in db.Topics
        from ts in topic.Subscriptions
        where ts.MemberId == 96
        select new { t.Name, t.Description };

Solution 2

var q = from t in db.Topics
        join ts in db.TopicSubscriptions on t.TopicId equals ts.TopicId
        into ij
        from tsub in ij
        where tsub.MemberId == 96
        select new { t.Name, t.Description};


问:
I keep getting "Failed to load resource" when I try to start an React app
So I'm working on a React App using Webstorm for IDE. As far as I can tell everything seems to be configured properly, but somehow when I try to run the app it would throw an error "Failed to load resource: the server responded with a status of 404 (Not Found)".

Here is a sample of script in the index:

```
</div>
</div>
</p>

<p>...From server.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const renderIndex = function (req, res) {
  console.warn(__dirname + '/app/' + 'index.tpl.html');
  res.sendFile(path.join(__dirname, '/app/', 'index.tpl.html'));
};

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(path.join(__dirname, '/')));

app.listen(3000, function () {
  console.log('Your app listening on port 3000!')</code>```

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/lib/node_modules/npm/bin/npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'start',
1 verbose cli   '--scripts-prepend-node-path=auto' ]
2 info using npm@5.5.1
3 info using node@v9.2.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle webpack-react-redux@1.0.0~prestart: webpack-react-redux@1.0.0
6 info lifecycle webpack-react-redux@1.0.0~start: webpack-react-redux@1.0.0
7 verbose lifecycle webpack-react-redux@1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle webpack-react-redux@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
9 verbose lifecycle webpack-react-redux@1.0.0~start: CWD: /Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server
10 silly lifecycle webpack-react-redux@1.0.0~start: Args: [ '-c', 'node server' ]
11 silly lifecycle webpack-react-redux@1.0.0~start: Returned: code: 1  signal: null
12 info lifecycle webpack-react-redux@1.0.0~start: Failed to exec start script
13 verbose stack Error: webpack-react-redux@1.0.0 start: `node server`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
13 verbose stack     at EventEmitter.emit (events.js:159:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:159:13)
13 verbose stack     at maybeClose (internal/child_process.js:943:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
14 verbose pkgid webpack-react-redux@1.0.0
15 verbose cwd /Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server
16 verbose Darwin 14.5.0
17 verbose argv "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/bin/npm-cli.js" "run" "start" "--scripts-prepend-node-path=auto"
18 verbose node v9.2.0
19 verbose npm  v5.5.1

```

What I want to accomplish is to have the app run in the browser, but continue getting an error. A response will be very much appreciated. Thanks.

答: Are you able to confirm that the entry point path is indeed correct? "/dist/app.bundle.js" </p>

Body:
So I'm working on a React App using Webstorm for IDE. As far as I can tell everything seems to be configured properly, but somehow when I try to run the app it would throw an error "Failed to load resource: the server responded with a status of 404 (Not Found)".

Here is a sample of script in the index:

...From server.js

const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const renderIndex = function (req, res) {
  console.warn(__dirname + '/app/' + 'index.tpl.html');
  res.sendFile(path.join(__dirname, '/app/', 'index.tpl.html'));
};

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(path.join(__dirname, '/')));

app.listen(3000, function () {
  console.log('Your app listening on port 3000!')

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/lib/node_modules/npm/bin/npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'start',
1 verbose cli   '--scripts-prepend-node-path=auto' ]
2 info using npm@5.5.1
3 info using node@v9.2.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle webpack-react-redux@1.0.0~prestart: webpack-react-redux@1.0.0
6 info lifecycle webpack-react-redux@1.0.0~start: webpack-react-redux@1.0.0
7 verbose lifecycle webpack-react-redux@1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle webpack-react-redux@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
9 verbose lifecycle webpack-react-redux@1.0.0~start: CWD: /Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server
10 silly lifecycle webpack-react-redux@1.0.0~start: Args: [ '-c', 'node server' ]
11 silly lifecycle webpack-react-redux@1.0.0~start: Returned: code: 1  signal: null
12 info lifecycle webpack-react-redux@1.0.0~start: Failed to exec start script
13 verbose stack Error: webpack-react-redux@1.0.0 start: `node server`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
13 verbose stack     at EventEmitter.emit (events.js:159:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:159:13)
13 verbose stack     at maybeClose (internal/child_process.js:943:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
14 verbose pkgid webpack-react-redux@1.0.0
15 verbose cwd /Users/blkbox/Desktop/Chris'/Quantdir/quantum-express-server
16 verbose Darwin 14.5.0
17 verbose argv "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/bin/npm-cli.js" "run" "start" "--scripts-prepend-node-path=auto"
18 verbose node v9.2.0
19 verbose npm  v5.5.1

What I want to accomplish is to have the app run in the browser, but continue getting an error. A response will be very much appreciated. Thanks.


问:
Why does a range have to be mut in order to call `find` on it?
I  want to find the first even number that is not 0. I'm not interested in mutating it, so I thought that this code above would give me an immutable option back:

```<code>fn main() {
    let first_ten = 0..10;
    let val = first_ten.find(|&n| (n % 2 == 0) && n > 0);
    println!("{}", val.unwrap());
}
</code>```

Instead, I get the following error:

 --> src/main.rs:3:13
  |
2 |   let first_ten = 0..10;
  |       --------- consider changing this to `mut first_ten`
3 |   let val = first_ten.find(|&n| (n % 2 == 0) && n > 0);
  |             ^^^^^^^^^ cannot borrow mutably
```

<p>I found this documentation page and I see that the predicate is defined as: </p>

```P: FnMut(&Self::Item) -> bool,
```

If I change the definition of first_ten to be let mut first_ten = 0..10, then the code works. Why does first_ten need to have mut?

答:
find is Iterator::find, and that's defined as:

```<code>fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
</code>```

The definition of the predicate is irrelevant.  The important part is &mut self.

Why is it &mut self and not &self?  Because it's defined on Iterator, and the only base method on Iterator (i.e. that implementations must provide) is next, which is:

```<code> fn next(&mut self) -> Option<Self::Item>;
</code>```

The only way you can get the next thing from an Iterator is to mutate it.  find doesn't have any choice.

The range has to be mutable because you're using it as an iterator, and iterators have to be mutable to be iterated, and searching an iterator requires iterating it.

Body:
I  want to find the first even number that is not 0. I'm not interested in mutating it, so I thought that this code above would give me an immutable option back:

fn main() {
    let first_ten = 0..10;
    let val = first_ten.find(|&n| (n % 2 == 0) && n > 0);
    println!("{}", val.unwrap());
}

Instead, I get the following error:

 --> src/main.rs:3:13
  |
2 |   let first_ten = 0..10;
  |       --------- consider changing this to `mut first_ten`
3 |   let val = first_ten.find(|&n| (n % 2 == 0) && n > 0);
  |             ^^^^^^^^^ cannot borrow mutably

I found this documentation page and I see that the predicate is defined as:

P: FnMut(&Self::Item) -> bool,

If I change the definition of first_ten to be let mut first_ten = 0..10, then the code works. Why does first_ten need to have mut?

Body:
find is Iterator::find, and that's defined as:

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>

The definition of the predicate is irrelevant.  The important part is &mut self.

Why is it &mut self and not &self?  Because it's defined on Iterator, and the only base method on Iterator (i.e. that implementations must provide) is next, which is:

 fn next(&mut self) -> Option<Self::Item>;

The only way you can get the next thing from an Iterator is to mutate it.  find doesn't have any choice.

The range has to be mutable because you're using it as an iterator, and iterators have to be mutable to be iterated, and searching an iterator requires iterating it.


问:
jquery: creating a custom dropdown menu?
I have created a custom drop-down menu using jQuery and CSS and it all works fine.

However, I have one issue that I cannot find a solution for.

Currently, I can select the Options (Option 1, Option 2, etc...) and I can also, de-select them by clicking on my selection.

When an option is selected, I change the drop-down menu background: and its color: and I add a checked icon to it so the user can see that they have selected something...

However, because I allow the users to de-select their options, I need to be able to change the background: and the color: and remove the checked icon IF there are no selections under that particular dropdown.

To explain this better, I have created this working FIDDLE:

https://jsfiddle.net/okmpxkcu/3/

If you click on the drop-down menus, you can select different options and then you can de-select them again.

I need the drop-down menu to go back it's original background color etc if there are no selections made.

Do help me if you understand

答:
Using .parent() count all the
 with the class added, if the length is greater than zero add the green background else remove the background.

var cou = 0;
var myI = 0;
var videoSource = [];
$("div.buildExMain").find('i.fa').hide();

$(document).on('click', '.buildExMain', function(e) {
    $('.buildExDrop').hide();
    $(this).children('.buildExDrop').show();
});

$(document).on('click', '.pSelection', function(e) {
    //        console.log($(this).parent().children());
    var vidToAdd = $(this).attr("data-id");

    ///check if its added/////
    if ($(this).hasClass("added")) {
        $(this).removeClass("added");
        $('.fa-check:last-child', this).remove();
        $('.buildExDrop').hide();
        e.stopPropagation();

        videoSource = videoSource.filter(x => x != vidToAdd);

        console.log(videoSource);
    } else {

        $('.exHolder').addClass('buildExMain');
        $(this).addClass('added');
        $(this).append('');

        videoSource.push(vidToAdd);

        var videoCount = videoSource.length;

        console.log(videoSource);

        if ($(this).hasClass("exc")) {
            cou++;
        }
        e.stopPropagation();
        $('.buildExDrop').hide();

    }
    // check if p tags with added class exists
    if ($(this).parent().find('p.pSelection.exc.added').length > 0) {
        $(this).closest("div.buildExMain").find('i.fa').show();
        $(this).closest('.buildExMain').addClass('selected');
    } else {
        $(this).closest("div.buildExMain").find('i.fa').hide();
        $(this).closest('.buildExMain').removeClass('selected');
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.exHolder {
    width: 100%;
    color: #e91e62;
    border: solid 1px #e91e62;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 10px;
    font-size: 20px;
    position: relative;
    display: inline-block;
}
.buildExDrop {
    background: green;
    width: 100%;
    height: auto;
    border: solid 1px #e91e62;
    font-family: 'Raleway';
    color: #fff;
    display: none;
    position: absolute;
    left: 0;
    z-index: 1;
    border-radius: 4px;
}
.pSelection {
    position: relative;
    border-bottom: solid 1px #000;
}
.pSelection:hover {
    background-color: #ccc;
    cursor: pointer;
}
.fa-check-circle {
    position: absolute;
    right: 20px;
    font-size: 24px;
    top: 4px;
    display: none;
}
.fa-check {
    position: absolute;
    right: 20px;
    font-size: 24px;
    top: 0px;
    display: none;
}
.selected {
    background-color: green;
    color: #fff;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Select Options

Option 1

Option 2

Option 3

Option 4

Select Options

Option 1

Option 2

Option 3

Option 4

```

Body:
Using .parent() count all the <p> with the class added, if the length is greater than zero add the green background else remove the background.

var cou = 0;
var myI = 0;
var videoSource = [];
$("div.buildExMain").find('i.fa').hide();

$(document).on('click', '.buildExMain', function(e) {
    $('.buildExDrop').hide();
    $(this).children('.buildExDrop').show();
});

$(document).on('click', '.pSelection', function(e) {
    //        console.log($(this).parent().children());
    var vidToAdd = $(this).attr("data-id");

    ///check if its added/////
    if ($(this).hasClass("added")) {
        $(this).removeClass("added");
        $('.fa-check:last-child', this).remove();
        $('.buildExDrop').hide();
        e.stopPropagation();

        videoSource = videoSource.filter(x => x != vidToAdd);

        console.log(videoSource);
    } else {

        $('.exHolder').addClass('buildExMain');
        $(this).addClass('added');
        $(this).append('<i class="fa fa-check" aria-hidden="true"></i>');

        videoSource.push(vidToAdd);

        var videoCount = videoSource.length;

        console.log(videoSource);

        if ($(this).hasClass("exc")) {
            cou++;
        }
        e.stopPropagation();
        $('.buildExDrop').hide();

    }
    // check if p tags with added class exists
    if ($(this).parent().find('p.pSelection.exc.added').length > 0) {
        $(this).closest("div.buildExMain").find('i.fa').show();
        $(this).closest('.buildExMain').addClass('selected');
    } else {
        $(this).closest("div.buildExMain").find('i.fa').hide();
        $(this).closest('.buildExMain').removeClass('selected');
    }
});

.exHolder {
    width: 100%;
    color: #e91e62;
    border: solid 1px #e91e62;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 10px;
    font-size: 20px;
    position: relative;
    display: inline-block;
}
.buildExDrop {
    background: green;
    width: 100%;
    height: auto;
    border: solid 1px #e91e62;
    font-family: 'Raleway';
    color: #fff;
    display: none;
    position: absolute;
    left: 0;
    z-index: 1;
    border-radius: 4px;
}
.pSelection {
    position: relative;
    border-bottom: solid 1px #000;
}
.pSelection:hover {
    background-color: #ccc;
    cursor: pointer;
}
.fa-check-circle {
    position: absolute;
    right: 20px;
    font-size: 24px;
    top: 4px;
    display: none;
}
.fa-check {
    position: absolute;
    right: 20px;
    font-size: 24px;
    top: 0px;
    display: none;
}
.selected {
    background-color: green;
    color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="exHolder buildExMain"><span>Select Options</span><i class="fa fa-check-circle" aria-hidden="true"></i>
    <div class="buildExDrop">
        <p class="pSelection exc" data-id="1">Option 1 </p>
        <p class="pSelection exc" data-id="2">Option 2 </p>
        <p class="pSelection exc" data-id="3">Option 3 </p>
        <p class="pSelection exc" data-id="4">Option 4 </p>

    </div>
</div>
<div class="exHolder buildExMain"><span>Select Options</span><i class="fa fa-check-circle" aria-hidden="true"></i>
    <div class="buildExDrop">
        <p class="pSelection exc" data-id="1">Option 1 </p>
        <p class="pSelection exc" data-id="2">Option 2 </p>
        <p class="pSelection exc" data-id="3">Option 3 </p>
        <p class="pSelection exc" data-id="4">Option 4 </p>
    </div>
</div>


问:
Start pick image activity from Broadcast Receiver
Hi I have an app that has a custom notification with buttons. Now I have been able to detect that the broadcast receiver receives the button presses on the notification. But my idea is that when the user presses one of the buttons it will initiate the CropImage.startPickImageActivity, I am using the Android Image Cropper Library.

But everytime I try to start the pick image activity on the button press from the notification. My app crashes, can anyone tell why is this happening or what am I doing wrong?

This is my code for my broadcast receiver:

```<code>public class NotificationReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if (action.equals("btn2")){
        CropImage.startPickImageActivity((Activity) context);
    }
  }

 }
</code>```

Thanks in advance for any help guys! :D

答:
That's because you can not just downcast context in Activity it it's not an Activity .
Change this line.

```<code>CropImage.startPickImageActivity((Activity) context);
</code>```

Now the solution can be for this problem.

If you want to handle both Background and forground scenario . Then you should open an Activity from broadcast receiver . And in it's onCreate() you can pass the data and hopefully open your Cropper too .

Second is you can directly open Cropper activity with intent(if it's a activity only) . If you do not need any result back from it you can directly open it .
I think that's it . Thx .

Body:
Hi I have an app that has a custom notification with buttons. Now I have been able to detect that the broadcast receiver receives the button presses on the notification. But my idea is that when the user presses one of the buttons it will initiate the CropImage.startPickImageActivity, I am using the Android Image Cropper Library.

But everytime I try to start the pick image activity on the button press from the notification. My app crashes, can anyone tell why is this happening or what am I doing wrong?

This is my code for my broadcast receiver:

public class NotificationReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if (action.equals("btn2")){
        CropImage.startPickImageActivity((Activity) context);
    }
  }

 }

Thanks in advance for any help guys! :D

Body:
That's because you can not just downcast context in Activity it it's not an Activity .
Change this line.

CropImage.startPickImageActivity((Activity) context);

Now the solution can be for this problem.

If you want to handle both Background and forground scenario . Then you should open an Activity from broadcast receiver . And in it's onCreate() you can pass the data and hopefully open your Cropper too .

Second is you can directly open Cropper activity with intent(if it's a activity only) . If you do not need any result back from it you can directly open it .
I think that's it . Thx .


问:
Deleting rows from multiple data frames with loop in R
I have multiple data frames with the exact same structure.  I'd like to loop through all these data frames and remove rows where the variable "Hat" = D. Below is what I have for a singular instance but would like to write a loop to do this for multiple data frames.   </p>

```<code>final_prices_designations_20161101_20161114.csv <- subset.data.frame(final_prices_designations_20161101_20161114.csv,
    final_prices_designations_20161101_20161114.csv$Hat == "D")
</code>```

答:
The easiest way to manage this is to use an apply() function to read the data and subset items to remove where Hat == 'D'.

```<code># first, read list of files from disk
theCSVFiles <- list.files(...)
# read each file and subset to eliminate Hat == D
fileList <- lapply(theCSVFiles,function(x) read.csv(x)[x$Hat!='D',])
# if necessary to combine to single file
aResult <- do.call(rbind,fileList)
</code>```

Body:
I have multiple data frames with the exact same structure.  I'd like to loop through all these data frames and remove rows where the variable "Hat" = D. Below is what I have for a singular instance but would like to write a loop to do this for multiple data frames.

final_prices_designations_20161101_20161114.csv <- subset.data.frame(final_prices_designations_20161101_20161114.csv,
    final_prices_designations_20161101_20161114.csv$Hat == "D")

Body:
The easiest way to manage this is to use an apply() function to read the data and subset items to remove where Hat == 'D'.

# first, read list of files from disk
theCSVFiles <- list.files(...)
# read each file and subset to eliminate Hat == D
fileList <- lapply(theCSVFiles,function(x) read.csv(x)[x$Hat!='D',])
# if necessary to combine to single file
aResult <- do.call(rbind,fileList)


问:
How to debug OpenERP / Odoo properly?
I am using pdb.set_trace() as a breakpoint in my python function during Odoo development and I keep getting the log messages.

```<code> pdb.set_trace()
    -> if s['confirm_state'] in ['draft','confirmed']:

(Pdb) 2015-04-05 05:40:12,794 9981 INFO vvm_odoo_new werkzeug: 127.0.0.1 - - [05/Apr/2015 05:40:12] "POST /longpolling/poll HTTP/1.1" 200 -
2015-04-05 05:40:47,769 9981 INFO vvm_odoo_new werkzeug: 127.0.0.1 - - [05/Apr/2015 05:40:47] "POST /longpolling/poll HTTP/1.1" 200 -
</code>```

I first thought that it was because of the instant messaging feature and so I un-installed it. But I still keep getting this message.

This does not stop me from using the pdb stack trace but the problem here is that this terminal message keeps showing up in between the typing in the pdb trace point.

答:
I recommend you to install the Visual Studio Code to debug Odoo:

Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring. It is free and open-source, although the official download is under a proprietary license.

First, you need to install the Python Extension within VSCode. Then, if you want to start debugging you just need to click on the Debug button and click on the wheel on the top of the sidebar. The file launch.json will open and you just need to add this element to the bottom.

```<code>{
    "name": "Python: Odoo",
    "type": "python",
    "request": "launch",
    "stopOnEntry": false,
    "pythonPath": "${config:python.pythonPath}",
    "console": "externalTerminal",
    "program": "/odoo_path/odoo.py",
    "args": [
        "--config=/odoo_config_path/.odoo_8.conf",
    ],
    "cwd": "${workspaceRoot}",
    "env": {},
    "envFile": "${workspaceRoot}/.env",
    "debugOptions": [
        "WaitOnAbnormalExit",
        "WaitOnNormalExit",
        "RedirectOutput"
    ]
}
</code>```

Once it is added you already can run Odoo under VSCode. For more information about the launch configurations click here

Now you can create breakpoint as usual. You can use the debugger console as well. And if you use the property: "console": "externalTerminal" as I did, you can show the log in an external console at the same time

Title: How to debug OpenERP / Odoo properly?

Body:
I am using pdb.set_trace() as a breakpoint in my python function during Odoo development and I keep getting the log messages.

 pdb.set_trace()
    -> if s['confirm_state'] in ['draft','confirmed']:

(Pdb) 2015-04-05 05:40:12,794 9981 INFO vvm_odoo_new werkzeug: 127.0.0.1 - - [05/Apr/2015 05:40:12] "POST /longpolling/poll HTTP/1.1" 200 -
2015-04-05 05:40:47,769 9981 INFO vvm_odoo_new werkzeug: 127.0.0.1 - - [05/Apr/2015 05:40:47] "POST /longpolling/poll HTTP/1.1" 200 -

I first thought that it was because of the instant messaging feature and so I un-installed it. But I still keep getting this message.

This does not stop me from using the pdb stack trace but the problem here is that this terminal message keeps showing up in between the typing in the pdb trace point.

Body:
I recommend you to install the Visual Studio Code to debug Odoo:

Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring. It is free and open-source, although the official download is under a proprietary license.

First, you need to install the Python Extension within VSCode. Then, if you want to start debugging you just need to click on the Debug button and click on the wheel on the top of the sidebar. The file launch.json will open and you just need to add this element to the bottom.

{
    "name": "Python: Odoo",
    "type": "python",
    "request": "launch",
    "stopOnEntry": false,
    "pythonPath": "${config:python.pythonPath}",
    "console": "externalTerminal",
    "program": "/odoo_path/odoo.py",
    "args": [
        "--config=/odoo_config_path/.odoo_8.conf",
    ],
    "cwd": "${workspaceRoot}",
    "env": {},
    "envFile": "${workspaceRoot}/.env",
    "debugOptions": [
        "WaitOnAbnormalExit",
        "WaitOnNormalExit",
        "RedirectOutput"
    ]
}

Once it is added you already can run Odoo under VSCode. For more information about the launch configurations click here

Now you can create breakpoint as usual. You can use the debugger console as well. And if you use the property: "console": "externalTerminal" as I did, you can show the log in an external console at the same time


问:
mybatis <id> tag in <resultMap> behavior
I wrote mapping file like below.

```<code><resultMap id="fooResultMap" type="Foo" >
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>
</code>```

When I get 2 record of same NAME colmun value, mybatis return only 1 Foo object.
I want 2 Foo object becouse bar's column is different.

So, I workaround below.

```<code><resultMap id="fooResultMap" type="Foo" >
  <id column="dummy_column_for_unique" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>
</code>```

I added <id> tag in <resultMap> and "dummy_column_for_unique" column is dummy(not exists).
I successfully got 2 Foo object.

I suppose dummy column result in null, and mybatis probably handle null value as different record.
But such behavior is not explained in manual or other resources on internet I searched.

Is there any information of this behavior ?

答:
In mybatis's mailing list, I was recommended to use row number.
https://groups.google.com/forum/#!topic/mybatis-user/FAvrJ4piYlU

So, my final resultMap is like below.

```<code><resultMap id="fooResultMap" type="Foo" >
  <id column="rownum" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>
</code>```

And sql is like below(original sql is wraped by outer select sentence for not modifying original sql, and this sql grammar is for mysql).

```<code>select @rownum:=@rownum+1 as rownum, org.* from (
### original sql ###
) org, (select @rownum:=0) r
</code>```

I hope this will help someone.

Body:
I wrote mapping file like below.

<resultMap id="fooResultMap" type="Foo" >
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>

When I get 2 record of same NAME colmun value, mybatis return only 1 Foo object.
I want 2 Foo object becouse bar's column is different.

So, I workaround below.

<resultMap id="fooResultMap" type="Foo" >
  <id column="dummy_column_for_unique" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>

I added <id> tag in <resultMap> and "dummy_column_for_unique" column is dummy(not exists).
I successfully got 2 Foo object.

I suppose dummy column result in null, and mybatis probably handle null value as different record.
But such behavior is not explained in manual or other resources on internet I searched.

Is there any information of this behavior ?

Body:
In mybatis's mailing list, I was recommended to use row number.
https://groups.google.com/forum/#!topic/mybatis-user/FAvrJ4piYlU

So, my final resultMap is like below.

<resultMap id="fooResultMap" type="Foo" >
  <id column="rownum" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>

And sql is like below(original sql is wraped by outer select sentence for not modifying original sql, and this sql grammar is for mysql).

select @rownum:=@rownum+1 as rownum, org.* from (
### original sql ###
) org, (select @rownum:=0) r

I hope this will help someone.


问:
MUTEX LOCK and MUTEX UNLOCK
what happen in the extremely unlucky case that two processes arrive at exactly & precisely the same moment.  This is not likely, but probabilistically can happen from time to time.  Even more coincidentally, let’s assume the lock is OPEN so that both processes would find the lock available. What happens? </p>

答:
Mutexes implemented using atomic operations. Different processor architectures implement this differently, but regardless of what processor does, on the lower level there is always a bus arbiter hardware that will have to pick correct order for all simultaneous memory accesses.

So even if two processors are accessing the same mutex at exactly the same moment in time, bus arbiter will choose who will be the first one and who will be the second one.

In the end, nothing happens at exactly the same moment in time - everything is ordered.

You may read more about how memory access works at Fixing Gap in knowledge about C/C++ and register access

In short, processor does not access memory directly, instead it asks memory controller to do this. When two processor ask memory device to do something at the same time, it has to pick one of them first.

Title: MUTEX LOCK and MUTEX UNLOCK


问:
How to install a compiled by Gradle jar into the local Gradle Repository files-2.1 instead of the Maven repository?
In my build.gradle, I added the plugin:

```<code>apply plugin: 'maven'
</code>```

Then using gradle install I can copy the resulted jar into the maven repository : ~/.m2/repository

However, my Gradle repository resides in ~/.gradle/caches/modules-2/files-2.1. How can I install the jar into this repository?

答:
mavenLocal() is resolved like this:

In order to make use of a non-standard local maven repository, you can use the following configuration in your build.gradle:

repositories {
    maven {
        url '/Users/manuelj/apache/maven/repository'
    }
}

Body:
In my build.gradle, I added the plugin:

apply plugin: 'maven'

Then using gradle install I can copy the resulted jar into the maven repository : ~/.m2/repository

However, my Gradle repository resides in ~/.gradle/caches/modules-2/files-2.1. How can I install the jar into this repository?


问:
Is there any good add-ins in Visual C#2008?
My visual assist x didn't work after I installed visual c# 2008.
Is there any good add-ins like VAX? </p>

答: Their homepage says it works with VS 2008. Maybe it was disabled? Tool menu... Add-ins Manager. Otherwise might try a reinstall. VS2005 and VS2008 Add-ins are in different spots in the registry so having an Add-in installed for VS2005 will not automatically make it available for VS2008.</p>

OwnerDisplayName: Jinx

LastEditorDisplayName: Jinx

OwnerDisplayName: David Thomas Garcia


问:
Access created_on from response object - get file action PODIO API
Hello folks I'm trying to access the created_on object using code below but it is not working, I'm getting incorrect date January 1, 1970 12:00. Also tried

```<code>$item = PodioItem::get($item_id);
$file_id = "";
$created_on = "";
foreach ($item->files as $file) {
echo date('F j, Y h:i',strtotime($file->created_on))."<br>";
}
</code>```

Below is the response object from print_r($file,true), I can access the other object without any issue like $file->file_id, $file->link. What I'm trying to accomplish is store the created_on data in a variable then create a function to check and grab the latest date, then grab the file_id of it.

```<code> PodioFile Object

 [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464714088
            [link] => https://files.podio.com/464714088
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => KEjj4UQSUV.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:03:36
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )

 PodioFile Object
(
    [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464716575
            [link] => https://files.podio.com/464716575
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => IiaCfJjwws.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:15:30
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )

PodioFile Object
(
    [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464728331
            [link] => https://files.podio.com/464728331
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => g6cmAeUCiV.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:49:15
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )
</code>```

答:
Luckily found the answer on sample provided here - https://hotexamples.com/examples/-/PodioItem/filter/php-podioitem-filter-method-examples.html

date_format($file->created_on, 'Y/m/d H:i:s') did the trick

Body:
Hello folks I'm trying to access the created_on object using code below but it is not working, I'm getting incorrect date January 1, 1970 12:00. Also tried

$item = PodioItem::get($item_id);
$file_id = "";
$created_on = "";
foreach ($item->files as $file) {
echo date('F j, Y h:i',strtotime($file->created_on))."
";
}

Below is the response object from print_r($file,true), I can access the other object without any issue like $file->file_id, $file->link. What I'm trying to accomplish is store the created_on data in a variable then create a function to check and grab the latest date, then grab the file_id of it.

 PodioFile Object

 [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464714088
            [link] => https://files.podio.com/464714088
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => KEjj4UQSUV.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:03:36
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )

 PodioFile Object
(
    [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464716575
            [link] => https://files.podio.com/464716575
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => IiaCfJjwws.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:15:30
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )

PodioFile Object
(
    [__attributes:PodioObject:private] => Array
        (
            [file_id] => 464728331
            [link] => https://files.podio.com/464728331
            [perma_link] =>
            [thumbnail_link] =>
            [hosted_by] => podio
            [name] => g6cmAeUCiV.PDF
            [description] =>
            [mimetype] => application/pdf
            [size] => 785849
            [created_on] => 2017-12-08 23:49:15
            [rights] => Array
                (
                    [0] => download
                    [1] => view
                    [2] => delete
                    [3] => update
                )


问:
Calling method inside __str__ function in python class
'List' object has no attribute 'points' is the error I'm getting. I think I'm not calling points correctly inside the __str__ function, but don't know how to fix it. Before, I had points defined before __str__ and had the same error.

```<code>class Persons(object):

    def __init__(self,name,radius,home_universe,x,y,dx,dy,current_universe,rewards):

        self.name = name
        self.radius = radius
        self.home_universe = home_universe
        self.x = x
        self.y = y
        self.dx = dx
        self.dy = dy
        self.current_universe = current_universe
        self.rewards = rewards

    def __str__(self):

        return '{} of {} in universe {}\n at ({},{}) speed ({},{}) with {} rewards and {} points'.\
               format(self.name, self.home_universe, self.current_universe, self.x, self.y, self.dx,\
                      self.dy, len(self.rewards), self.rewards.points())

    def points(self):

        cnt = 0
        if len(self.rewards) == 0:
            return 0
        else:
            for reward in self.rewards:
                cnt += reward[2]
            return cnt
</code>```

答:
You use self.rewards.points() but you have only self.points().

Use self.points()

Body:
'List' object has no attribute 'points' is the error I'm getting. I think I'm not calling points correctly inside the __str__ function, but don't know how to fix it. Before, I had points defined before __str__ and had the same error.

class Persons(object):

    def __init__(self,name,radius,home_universe,x,y,dx,dy,current_universe,rewards):

        self.name = name
        self.radius = radius
        self.home_universe = home_universe
        self.x = x
        self.y = y
        self.dx = dx
        self.dy = dy
        self.current_universe = current_universe
        self.rewards = rewards

    def __str__(self):

        return '{} of {} in universe {}\n at ({},{}) speed ({},{}) with {} rewards and {} points'.\
               format(self.name, self.home_universe, self.current_universe, self.x, self.y, self.dx,\
                      self.dy, len(self.rewards), self.rewards.points())

    def points(self):

        cnt = 0
        if len(self.rewards) == 0:
            return 0
        else:
            for reward in self.rewards:
                cnt += reward[2]
            return cnt


问:
Matplotlib imshow() issues: title on top of top xlabels, and ylabels not aligned in pdf
I'm having some issues in using imshow() from matplotlib, in specific with creating a pdf from it.

I'm dealing with a 500x500 matrix which, for the sake of this question, will be just random values:

```<code>np.random.seed(1)
arr = np.array(np.random.random((500, 500)))
</code>```

The rows and columns are all labelled with different names, but for the sake of this question, let's just make them simple:

```<code>labels = ["Big_Label" if x % 2 == 0 else "Bigger_Big_Label" for x in range(500)]
</code>```

So, I have the following code to plot that matrix:

```<code>plt.rc('figure', figsize=(5,5), dpi=500)
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(arr)

# defining the same labels for rows and columns
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
# showing the labels for all the ticks
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
# personalising the ticks. In particular, labels on top
ax.tick_params(axis='both', which='both', labelsize=0.5, length=0)
ax.tick_params(axis='x',which='both', labelbottom='off', labeltop='on')
ax.tick_params(axis='both', pad=1)
# vertical labels
for label in im.axes.xaxis.get_ticklabels():
    label.set_rotation(90)

plt.colorbar(im)
plt.title("Just a Big Title With Words")

# Removing outer lines because they hide part of the lines/columns
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

plt.savefig("fig.pdf")
plt.show()
</code>```

The first issue is with the title because is on top of the xlabels:

The second issue is, when zooming to see the ylabels and xlabels, they are not aligned. With regards the left labels, they have varying spaces between them and the plot, when I specifically coded ax.tick_params(axis='both', pad=1); if I execute this python code in an IDE or in terminal, this issue doesn't happen (they are all close to the plot). So I guess something is going on when putting this image into a pdf?. With regards with both labels, you can see they are not aligned with the actual rows and columns; for example, the second label on the top is in middle of the blue and orange square, when it should be aligned with the middle of the orange square:

Finally, I tried to call fig.autofmt_xdate() just before plt.savefig(), but the result is even worse, as the top labels are just completely not aligned:

Can you help me solving this issues? I know you have to do a big zoom to see labels, but for the real matrices that I have that is necessary. I also inform that I'm using matplotlib 1.5; I can't use 2.x because of a compatibility issue with another tool

答:
There is a PR for automatically moving the title. Should be included in v2.2 (Feb timeframe) https://github.com/matplotlib/matplotlib/pull/9498, and another for the title padding  https://github.com/matplotlib/matplotlib/pull/9816.  So we are working on it.

As for your label misalignment in PDF, it looks like there is a bug in label alignment if labelsize is less than 1.0, so don't do that:  https://github.com/matplotlib/matplotlib/issues/9963  Its a bug, but I would imagine a low-priority one.

Body:
I'm having some issues in using imshow() from matplotlib, in specific with creating a pdf from it.

I'm dealing with a 500x500 matrix which, for the sake of this question, will be just random values:

np.random.seed(1)
arr = np.array(np.random.random((500, 500)))

The rows and columns are all labelled with different names, but for the sake of this question, let's just make them simple:

labels = ["Big_Label" if x % 2 == 0 else "Bigger_Big_Label" for x in range(500)]

So, I have the following code to plot that matrix:

plt.rc('figure', figsize=(5,5), dpi=500)
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(arr)

# defining the same labels for rows and columns
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
# showing the labels for all the ticks
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
# personalising the ticks. In particular, labels on top
ax.tick_params(axis='both', which='both', labelsize=0.5, length=0)
ax.tick_params(axis='x',which='both', labelbottom='off', labeltop='on')
ax.tick_params(axis='both', pad=1)
# vertical labels
for label in im.axes.xaxis.get_ticklabels():
    label.set_rotation(90)

plt.colorbar(im)
plt.title("Just a Big Title With Words")

# Removing outer lines because they hide part of the lines/columns
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

plt.savefig("fig.pdf")
plt.show()

The first issue is with the title because is on top of the xlabels:

The second issue is, when zooming to see the ylabels and xlabels, they are not aligned. With regards the left labels, they have varying spaces between them and the plot, when I specifically coded ax.tick_params(axis='both', pad=1); if I execute this python code in an IDE or in terminal, this issue doesn't happen (they are all close to the plot). So I guess something is going on when putting this image into a pdf?. With regards with both labels, you can see they are not aligned with the actual rows and columns; for example, the second label on the top is in middle of the blue and orange square, when it should be aligned with the middle of the orange square:

Finally, I tried to call fig.autofmt_xdate() just before plt.savefig(), but the result is even worse, as the top labels are just completely not aligned:

Can you help me solving this issues? I know you have to do a big zoom to see labels, but for the real matrices that I have that is necessary. I also inform that I'm using matplotlib 1.5; I can't use 2.x because of a compatibility issue with another tool


问:
boost::priority_queue not compiling
Created a boost::priority_queue with my comparison operation defined. Here is how my priority_queue looks,

```<code>boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > max_heap;
</code>```

My comparison is defined as,

```<code>struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getTime() < rhs->getTime());
    }
};
</code>```

I have used it as,

```<code>myObject* obj1 = static_cast<myObject*>(base1);
</code>```

'base1' is an object of class 'myBase'(base class of myObject)

myObject and getTime() within it used for comparision are defined as,

```<code>class myObject : public myBase {
    Time getTime() const { return time; }
.
.
.
...
}
</code>```

Compiling this gives me this error,

```<code>c:\Projects\pq_test.cpp(27): error C2662: 'void boost::heap::priority_queue<myObject*,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>::push(myObject *const &)' : cannot convert 'this' pointer from 'const boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' to 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_> &'
1>          Conversion loses qualifiers
</code>```

Using Visual Studio 2013 C++. I understand that I am doing something wrong with const correctness, but I am not able to figure out what is wrong. Any help is appreciated.

TIA!

EDIT1:
@Maxim Egorushkin : Thanks!
I saw that,

```<code>myObject* obj1 = static_cast<myObject*>(base1);
</code>```

is in a function which is a const function whose signature is,

```<code>void workOnObj(myBase* base1) const;
</code>```

So, I changed my definition of my priority_queue to const as,

```<code>const boost::heap::priority_queue<Container*, boost::heap::compare<ContainerPtrCompare> > max_heap;
</code>```

and expected that the error would go away, but it still has the same error.

答:
In cases of trouble, always post a self-contained example. Your sample doesn't even show a push operation, so it cannot possibly generate the error message shown.

Here's a simplistic example showing your types that works, so you can see what you're doing differently:

Live On Coliru

```<code>#include <boost/heap/priority_queue.hpp>
#include <iostream>
#include <random>

static std::mt19937 s_rng { std::random_device{}() };

struct myObject {
    int _time = s_rng() % 1024;
    int getTime() const { return _time; }
};

struct myObjectPtrCompare {
    bool operator()(myObject const *lhs, myObject const *rhs) const { return lhs->getTime() < rhs->getTime(); }
};

int main() {
    boost::heap::priority_queue<myObject *, boost::heap::compare<myObjectPtrCompare> > max_heap;

    for (auto i = 0u; i < s_rng() % 100; ++i)
        max_heap.push(new myObject{});

    while (max_heap.size()) {
        std::cout << "time: " << max_heap.top()->getTime() << "\n";
        delete max_heap.top();
        max_heap.pop();
    }
}
</code>```

It uses random data each time, but will print something similar to:

```<code>time: 1012
time: 994
time: 957
time: 904
time: 889
time: 872
time: 566
time: 460
time: 378
time: 310
time: 254
time: 243
time: 22
</code>```

Title: boost::priority_queue not compiling

Body:
Created a boost::priority_queue with my comparison operation defined. Here is how my priority_queue looks,

boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > max_heap;

My comparison is defined as,

struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getTime() < rhs->getTime());
    }
};

I have used it as,

myObject* obj1 = static_cast<myObject*>(base1);

'base1' is an object of class 'myBase'(base class of myObject)

myObject and getTime() within it used for comparision are defined as,

class myObject : public myBase {
    Time getTime() const { return time; }
.
.
.
...
}

Compiling this gives me this error,

c:\Projects\pq_test.cpp(27): error C2662: 'void boost::heap::priority_queue<myObject*,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>::push(myObject *const &)' : cannot convert 'this' pointer from 'const boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' to 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_> &'
1>          Conversion loses qualifiers

Using Visual Studio 2013 C++. I understand that I am doing something wrong with const correctness, but I am not able to figure out what is wrong. Any help is appreciated.

TIA!

EDIT1:
@Maxim Egorushkin : Thanks!
I saw that,

myObject* obj1 = static_cast<myObject*>(base1);

is in a function which is a const function whose signature is,

void workOnObj(myBase* base1) const;

So, I changed my definition of my priority_queue to const as,

const boost::heap::priority_queue<Container*, boost::heap::compare<ContainerPtrCompare> > max_heap;

and expected that the error would go away, but it still has the same error.

Body:
In cases of trouble, always post a self-contained example. Your sample doesn't even show a push operation, so it cannot possibly generate the error message shown.

Here's a simplistic example showing your types that works, so you can see what you're doing differently:

Live On Coliru

#include <boost/heap/priority_queue.hpp>
#include <iostream>
#include <random>

static std::mt19937 s_rng { std::random_device{}() };

struct myObject {
    int _time = s_rng() % 1024;
    int getTime() const { return _time; }
};

struct myObjectPtrCompare {
    bool operator()(myObject const *lhs, myObject const *rhs) const { return lhs->getTime() < rhs->getTime(); }
};

int main() {
    boost::heap::priority_queue<myObject *, boost::heap::compare<myObjectPtrCompare> > max_heap;

    for (auto i = 0u; i < s_rng() % 100; ++i)
        max_heap.push(new myObject{});

    while (max_heap.size()) {
        std::cout << "time: " << max_heap.top()->getTime() << "\n";
        delete max_heap.top();
        max_heap.pop();
    }
}

It uses random data each time, but will print something similar to:

time: 1012
time: 994
time: 957
time: 904
time: 889
time: 872
time: 566
time: 460
time: 378
time: 310
time: 254
time: 243
time: 22


问:
Conversion of dataframe into a realRatingMatrix in R
I'm trying to convert a data-frame that contains three columns username, itemnumber or itemID and the rating. The datatype of the three columns are mentioned below.

```<code>>             userID          itemid         rating
               <chr>           <int>          <dbl>
</code>```

I found the method to convert a data-frame into a realRatingMatrix when all the columns are numeric. However, I was unable to find a function to convert this data-frame which contains both character and numeric datatype.
Can someone please suggest any solution to convert a data-frame to realRatingMatrix.

答:
Couple of steps and this worked for me:

```<code>m$userID <- as.factor(m$userID)
m$itemID <- as.factor(m$itemID)
m$rating <- as.numeric(m$rating)

m <- as(m, "realRatingMatrix")
</code>```

I needed my  rating to be numeric, not sure if double works but I don't see a reason it shouldn't.

Body:
I'm trying to convert a data-frame that contains three columns username, itemnumber or itemID and the rating. The datatype of the three columns are mentioned below.

>             userID          itemid         rating
               <chr>           <int>          <dbl>

I found the method to convert a data-frame into a realRatingMatrix when all the columns are numeric. However, I was unable to find a function to convert this data-frame which contains both character and numeric datatype.
Can someone please suggest any solution to convert a data-frame to realRatingMatrix.

Body:
Couple of steps and this worked for me:

m$userID <- as.factor(m$userID)
m$itemID <- as.factor(m$itemID)
m$rating <- as.numeric(m$rating)

m <- as(m, "realRatingMatrix")

I needed my  rating to be numeric, not sure if double works but I don't see a reason it shouldn't.


问:
Get value Before last value with Entity Framework
I have query with Entity Frameworks like this:

```<code>var lastYear = anios.Select(x => x.ID).LastOrDefault();
</code>```

I want to know if it's possible to get value before LastOrDefault item.

For example if I have:

2015
2016
2017
2018

I want to get 2017 instead 2018. there is some trick to get this value with EF?

答:
```<code>var lastYear = anios.Select(x => x.ID).OrderByDescending(x => x)
    .Take(2).Last();
</code>```

Sorry I dont have exact syntax.... the intent of my answer is to sort descending and take the top two.  Of the two take the second.  You should check the count first of course which my example does not show.

Body:
I have query with Entity Frameworks like this:

var lastYear = anios.Select(x => x.ID).LastOrDefault();

I want to know if it's possible to get value before LastOrDefault item.

For example if I have:

2015
2016
2017
2018

I want to get 2017 instead 2018. there is some trick to get this value with EF?

Body:
var lastYear = anios.Select(x => x.ID).OrderByDescending(x => x)
    .Take(2).Last();

Sorry I dont have exact syntax.... the intent of my answer is to sort descending and take the top two.  Of the two take the second.  You should check the count first of course which my example does not show.