问:
gnuplot plotting multiple errorbars depending on first column
I have a data file with the following format:
col1: plot[0-9]+
col2: x
col3: y
col4: delta

For example:

```<code>plot0, 1, 1, 2
plot1, 1, 2, 2
plot0, 2, 2, 1
plot1, 2, 3, 2
</code>```

I am trying to plot a yerrorbars for each plotX of the first column with separated legend and color.

A none scalable example would be:

```<code>plot 'ex.dat' using 1:2:3 with yerrorbars, 'ex1.dat' using 1:2:3 with yerrorbars
</code>```

答:
Maybe something like this? The color of the datapoint+yerrorbar is taken from the first column via the function GetPlotNo(n) = int(strcol(n)[5:]).
The second plot command is actually plotting a dummy outside of the range just to get the colors of the legend right. If you need the datapoints of each plot1, plot2, ... to be connected, this might get a bit more complicated.

Code:

```<code>### color of datapoints depending on a column
reset session
set colorsequence classic

$Data <<EOD
plot0, 1.0, 1, 2
plot1, 1.1, 2, 2
plot0, 2.0, 2, 1
plot1, 2.1, 3, 2
plot2, 1.2, 3, 2
plot0, 3.0, 3, 1
plot1, 3.1, 4, 1
plot2, 2.2, 5, 1
plot2, 3.2, 4, 1
EOD

set datafile separator ","
set xrange[0:4]
set yrange[-1:7]

GetPlotNo(n) = int(strcol(n)[5:])

plot \
    $Data u 2:3:4:(GetPlotNo(1)+1) w yerrorbars pt 7 lc var lw 2 notitle, \
    for [i=0:2] -999 w lp pt 7 lc i+1 lw 2 title sprintf("plot%i",i) noautoscale
### end of code
</code>```

Result:

Addition:

Actually, if you want the lines to be connected it requires a small modification. Add/exchange the following lines and the lines of each plot will be connected.

```<code>set datafile missing NaN
plot \
    $Data u 2:3:4:(GetPlotNo(1)+1) w yerrorbars pt 7 lc var lw 2 notitle, \
    for [i=0:2] '' u (i==GetPlotNo(1)?$2:NaN):3:(GetPlotNo(1)+1) w lp pt 7 lc var lw 2 title sprintf("plot%i",i)
</code>```

Body:
I have a data file with the following format:
col1: plot[0-9]+
col2: x
col3: y
col4: delta

For example:

plot0, 1, 1, 2
plot1, 1, 2, 2
plot0, 2, 2, 1
plot1, 2, 3, 2

I am trying to plot a yerrorbars for each plotX of the first column with separated legend and color.

A none scalable example would be:

plot 'ex.dat' using 1:2:3 with yerrorbars, 'ex1.dat' using 1:2:3 with yerrorbars

Body:
Maybe something like this? The color of the datapoint+yerrorbar is taken from the first column via the function GetPlotNo(n) = int(strcol(n)[5:]).
The second plot command is actually plotting a dummy outside of the range just to get the colors of the legend right. If you need the datapoints of each plot1, plot2, ... to be connected, this might get a bit more complicated.

Code:

### color of datapoints depending on a column
reset session
set colorsequence classic

$Data <<EOD
plot0, 1.0, 1, 2
plot1, 1.1, 2, 2
plot0, 2.0, 2, 1
plot1, 2.1, 3, 2
plot2, 1.2, 3, 2
plot0, 3.0, 3, 1
plot1, 3.1, 4, 1
plot2, 2.2, 5, 1
plot2, 3.2, 4, 1
EOD

set datafile separator ","
set xrange[0:4]
set yrange[-1:7]

GetPlotNo(n) = int(strcol(n)[5:])

plot \
    $Data u 2:3:4:(GetPlotNo(1)+1) w yerrorbars pt 7 lc var lw 2 notitle, \
    for [i=0:2] -999 w lp pt 7 lc i+1 lw 2 title sprintf("plot%i",i) noautoscale
### end of code

Result:

Addition:

Actually, if you want the lines to be connected it requires a small modification. Add/exchange the following lines and the lines of each plot will be connected.

set datafile missing NaN
plot \
    $Data u 2:3:4:(GetPlotNo(1)+1) w yerrorbars pt 7 lc var lw 2 notitle, \
    for [i=0:2] '' u (i==GetPlotNo(1)?$2:NaN):3:(GetPlotNo(1)+1) w lp pt 7 lc var lw 2 title sprintf("plot%i",i)


来源: stackexchange

问:
how to unlist a list of regression models in R
I fitted a several models on a single variable (a) as a mod1. Output mod1 contains regression fitting list of the 5 models. I did several operation in the list of models. Now I want to unlist mod1 into a single regression model output like fit1, fit2,...fit5 etc.

```<code>func <-function(z){
  fit1 <- lm( y~ x + z )
  fit2 <- lm( y~x + I(z^2))
  fit3 <- lm( y~poly(x,3) + z)
  fit4 <- lm( y~ns(x, 3) + z)
  fit5 <- lm( y~ns(x, 9) + z)
  return(list(fit1, fit2, fit3, fit4, fit5))
}

mod1 <- func(data$a)

test <- unlist(mod1, recursive = TRUE, use.names = TRUE)
</code>```

When I used unlist(), output turned very long un-understandable strings. Even when I tried this following, it is still a list of 1 model.

```<code>fit1 <- mod1[1]
</code>```

Does anyone have any idea about how to separate models one by one from a list of regression model output?

Thanks in advance!

答:
I'd recommend a combination of using broom to tidy the output of lm, and standard list methods lapply and [[ indexing to work with lists.

Read more about working with lists in R here.

```<code>library(splines)

# create some example data
d <- data.frame(x = rnorm(100, 0, 1),
                y = rnorm(100, 0, 1),
                z = rnorm(100, 0, 1))

# function to fit 5 models
func <-function(d){
  fit1 <- lm( y~ x + z, data = d)
  fit2 <- lm( y~x + I(z^2), data = d)
  fit3 <- lm( y~poly(x,3) + z, data = d)
  fit4 <- lm( y~ns(x, 3) + z, data = d)
  fit5 <- lm( y~ns(x, 9) + z, data = d)

  # store models in a list
  l <- list(fit1, fit2, fit3, fit4, fit5)

  # name the models
  names(l) <- paste0("fit", 1:5)

  return(l)
}

# run the function
mods <- func(d)
</code>```

Access each element of the list with double brackets [[

```<code>mods[[1]]

Call:
  lm(formula = y ~ x + z, data = d)

Coefficients:
  (Intercept)            x            z
0.03339     -0.05128     -0.15288

mods[[2]]

Call:
  lm(formula = y ~ x + I(z^2), data = d)

Coefficients:
  (Intercept)            x       I(z^2)
0.01739     -0.04490      0.01258

</code>```

Use broom to "tidy" model output

```<code>library(broom)
tidy(mods[[1]])

# A tibble: 3 x 5
term        estimate std.error statistic p.value
<chr>          <dbl>     <dbl>     <dbl>   <dbl>
  1 (Intercept)   0.0334    0.0985     0.339   0.735
2 x            -0.0513    0.103     -0.499   0.619
3 z            -0.153     0.102     -1.50    0.138

</code>```

Use lapply (or purrr::map) to tidy the list of model output.

```<code>tidy_mods <- lapply(mods, tidy)

# add names to each data frame and combine into one big data frame
for(i in 1:length(tidy_mods)) tidy_mods[[i]]$mod <- names(tidy_mods[i])
do.call(rbind.data.frame, tidy_mods)

# A tibble: 27 x 6
term        estimate std.error statistic p.value mod
* <chr>          <dbl>     <dbl>     <dbl>   <dbl> <chr>
  1 (Intercept)   0.0334    0.0985     0.339  0.735  fit1
2 x            -0.0513    0.103     -0.499  0.619  fit1
3 z            -0.153     0.102     -1.50   0.138  fit1
4 (Intercept)   0.0174    0.130      0.134  0.894  fit2
5 x            -0.0449    0.105     -0.429  0.669  fit2
6 I(z^2)        0.0126    0.0894     0.141  0.888  fit2
7 (Intercept)   0.0309    0.0975     0.317  0.752  fit3
8 poly(x, 3)1  -0.493     0.975     -0.505  0.614  fit3
9 poly(x, 3)2  -0.569     0.975     -0.584  0.561  fit3
10 poly(x, 3)3   1.78      0.976      1.83   0.0709 fit3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I fitted a several models on a single variable (a) as a mod1. Output mod1 contains regression fitting list of the 5 models. I did several operation in the list of models. Now I want to unlist mod1 into a single regression model output like fit1, fit2,...fit5 etc.

func <-function(z){
  fit1 <- lm( y~ x + z )
  fit2 <- lm( y~x + I(z^2))
  fit3 <- lm( y~poly(x,3) + z)
  fit4 <- lm( y~ns(x, 3) + z)
  fit5 <- lm( y~ns(x, 9) + z)
  return(list(fit1, fit2, fit3, fit4, fit5))
}

mod1 <- func(data$a)

test <- unlist(mod1, recursive = TRUE, use.names = TRUE)

When I used unlist(), output turned very long un-understandable strings. Even when I tried this following, it is still a list of 1 model.

fit1 <- mod1[1]

Does anyone have any idea about how to separate models one by one from a list of regression model output?

Thanks in advance!

Body:
I'd recommend a combination of using broom to tidy the output of lm, and standard list methods lapply and [[ indexing to work with lists.

Read more about working with lists in R here.

library(splines)

# create some example data
d <- data.frame(x = rnorm(100, 0, 1),
                y = rnorm(100, 0, 1),
                z = rnorm(100, 0, 1))

# function to fit 5 models
func <-function(d){
  fit1 <- lm( y~ x + z, data = d)
  fit2 <- lm( y~x + I(z^2), data = d)
  fit3 <- lm( y~poly(x,3) + z, data = d)
  fit4 <- lm( y~ns(x, 3) + z, data = d)
  fit5 <- lm( y~ns(x, 9) + z, data = d)

  # store models in a list
  l <- list(fit1, fit2, fit3, fit4, fit5)

  # name the models
  names(l) <- paste0("fit", 1:5)

  return(l)
}

# run the function
mods <- func(d)

Access each element of the list with double brackets [[

mods[[1]]

Call:
  lm(formula = y ~ x + z, data = d)

Coefficients:
  (Intercept)            x            z
0.03339     -0.05128     -0.15288

mods[[2]]

Call:
  lm(formula = y ~ x + I(z^2), data = d)

Coefficients:
  (Intercept)            x       I(z^2)
0.01739     -0.04490      0.01258

Use broom to "tidy" model output

library(broom)
tidy(mods[[1]])

# A tibble: 3 x 5
term        estimate std.error statistic p.value
<chr>          <dbl>     <dbl>     <dbl>   <dbl>
  1 (Intercept)   0.0334    0.0985     0.339   0.735
2 x            -0.0513    0.103     -0.499   0.619
3 z            -0.153     0.102     -1.50    0.138

Use lapply (or purrr::map) to tidy the list of model output.

tidy_mods <- lapply(mods, tidy)

# add names to each data frame and combine into one big data frame
for(i in 1:length(tidy_mods)) tidy_mods[[i]]$mod <- names(tidy_mods[i])
do.call(rbind.data.frame, tidy_mods)

# A tibble: 27 x 6
term        estimate std.error statistic p.value mod
* <chr>          <dbl>     <dbl>     <dbl>   <dbl> <chr>
  1 (Intercept)   0.0334    0.0985     0.339  0.735  fit1
2 x            -0.0513    0.103     -0.499  0.619  fit1
3 z            -0.153     0.102     -1.50   0.138  fit1
4 (Intercept)   0.0174    0.130      0.134  0.894  fit2
5 x            -0.0449    0.105     -0.429  0.669  fit2
6 I(z^2)        0.0126    0.0894     0.141  0.888  fit2
7 (Intercept)   0.0309    0.0975     0.317  0.752  fit3
8 poly(x, 3)1  -0.493     0.975     -0.505  0.614  fit3
9 poly(x, 3)2  -0.569     0.975     -0.584  0.561  fit3
10 poly(x, 3)3   1.78      0.976      1.83   0.0709 fit3


问:
Bidirectional Functional Dependencies
I have a type class that looks a bit like the following:

```<code>class Foo a b | a -> b where
  f :: a -> Bool
  g :: b -> Bool
  h :: a -> b -> Bool
</code>```

Or at least these are the bits that are important to my question.  This class does not compile, and for good reason. The problem with this class is that I could (if I wanted to) do the following:

```<code>instance Foo () Bool where
  f x = True
  g y = y
  h x y = False

instance Foo ((), ()) Bool where
  f x = True
  g y = not y
  h x y = False
</code>```

Now if I call g True there are two separate results one for each instance.   And the compiler picks up on this possibility and informs me that my type class is no good.

My issue is that the dependency | a -> b is not quite what I mean.  I don't just mean that you can find a from b, but also that you can find b from a.  That is each type should only ever be a member of Foo with one other type so we can given one type find the other.  Or to put it in yet another way the dependency is bidirectional.  Such a functional dependency would prevent me from having Bool present in two separate instances because the first parameter would be derivable from the second as well as the second from the first.

But I don't know how to express this idea to the compiler.

How can I create a bidirectional functional dependency?  Or, more likely, is there a way that I can rephrase my type class to get something that could replace a bidirectional functional dependency?

答:
A bidirectional dependency between a and b can be presented as two functional dependencies a -> b and b -> a, like:

```<code>class Foo a b | a -> b<b>, b -> a</b> where
  f :: a -> Bool
  g :: b -> Bool
  h :: a -> b -> Bool</code>```

So here a is functional dependent on b and b is functional dependent on a.

For your instances however this of course raises an error, since now you defined two different as for b ~ Bool. This will raise an error like:

```<code>file.hs:6:10: error:
    <b>Functional dependencies conflict</b> between instance declarations:
      instance Foo () Bool -- Defined at file.hs:6:10
      instance Foo ((), ()) Bool -- Defined at file.hs:11:10
Failed, modules loaded: none.</code>```

Because of the functional dependency, you can only define one a for b ~ Bool. But this is probably exactly what you are looking for: a mechanism to prevent defining Foo twice for the same a, or the same b.

Title: Bidirectional Functional Dependencies

Body:
I have a type class that looks a bit like the following:

class Foo a b | a -> b where
  f :: a -> Bool
  g :: b -> Bool
  h :: a -> b -> Bool

Or at least these are the bits that are important to my question.  This class does not compile, and for good reason. The problem with this class is that I could (if I wanted to) do the following:

instance Foo () Bool where
  f x = True
  g y = y
  h x y = False

instance Foo ((), ()) Bool where
  f x = True
  g y = not y
  h x y = False

Now if I call g True there are two separate results one for each instance.   And the compiler picks up on this possibility and informs me that my type class is no good.

My issue is that the dependency | a -> b is not quite what I mean.  I don't just mean that you can find a from b, but also that you can find b from a.  That is each type should only ever be a member of Foo with one other type so we can given one type find the other.  Or to put it in yet another way the dependency is bidirectional.  Such a functional dependency would prevent me from having Bool present in two separate instances because the first parameter would be derivable from the second as well as the second from the first.

But I don't know how to express this idea to the compiler.

How can I create a bidirectional functional dependency?  Or, more likely, is there a way that I can rephrase my type class to get something that could replace a bidirectional functional dependency?

Body:
A bidirectional dependency between a and b can be presented as two functional dependencies a -> b and b -> a, like:

class Foo a b | a -> b, b -> a where
  f :: a -> Bool
  g :: b -> Bool
  h :: a -> b -> Bool

So here a is functional dependent on b and b is functional dependent on a.

For your instances however this of course raises an error, since now you defined two different as for b ~ Bool. This will raise an error like:

file.hs:6:10: error:
    Functional dependencies conflict between instance declarations:
      instance Foo () Bool -- Defined at file.hs:6:10
      instance Foo ((), ()) Bool -- Defined at file.hs:11:10
Failed, modules loaded: none.

Because of the functional dependency, you can only define one a for b ~ Bool. But this is probably exactly what you are looking for: a mechanism to prevent defining Foo twice for the same a, or the same b.


问:
React hooks warn me for missing dependencies
Suppose I am using useEffect to prefetch data on initial rendering:

```<code>function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}
</code>```

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.

答:
You can use useRef or useMemo to store the value.

See https://stackoverflow.com/a/54963730/9351632

Body:
Suppose I am using useEffect to prefetch data on initial rendering:

function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.


问:
As3 to YouTube Upload
I would like to know if it's possible to capture a users webcam in flash and directly upload it to YouTube without  a backend server setup. Or if there are any third party providers that support this service.

I see YouTube offers a live streaming API, but it seems it's only available for selected users.

Thank in advance.

答: Yes you can, by using YouTube's Data API. Basically you will interact with the API using XML and HTTP and then you can upload as well as any other functionality (create play lists, search, etc)</p>

ContentLicense: CC BY-SA 3.0

Title: As3 to YouTube Upload


问:
Numpy reshape function. How are these two lines of code different?
How are these two lines of codes different:</p>

```<code>X_flatten = X.reshape(X.shape[0], -1).T

X_flatten = X.reshape(-1, X.shape[0])
</code>```

答:
these two lines have different outputs which are not related to each other
look at this example:
suppose X is like the following:

```<code>>>> X = np.arange(6).reshape(2,3)
>>> X
array([[0, 1, 2],
       [3, 4, 5]])
</code>```

first line output:

```<code>>>> X_flatten = X.reshape(X.shape[0], -1).T
>>> X_flatten
array([[0, 3],
       [1, 4],
       [2, 5]])
</code>```

and the second line output is:

```<code>>>> X_flatten = X.reshape(-1, X.shape[0])
>>> X_flatten
array([[0, 1],
       [2, 3],
       [4, 5]])
</code>```

Body:
How are these two lines of codes different:

X_flatten = X.reshape(X.shape[0], -1).T

X_flatten = X.reshape(-1, X.shape[0])

Body:
these two lines have different outputs which are not related to each other
look at this example:
suppose X is like the following:

>>> X = np.arange(6).reshape(2,3)
>>> X
array([[0, 1, 2],
       [3, 4, 5]])

first line output:

>>> X_flatten = X.reshape(X.shape[0], -1).T
>>> X_flatten
array([[0, 3],
       [1, 4],
       [2, 5]])

and the second line output is:

>>> X_flatten = X.reshape(-1, X.shape[0])
>>> X_flatten
array([[0, 1],
       [2, 3],
       [4, 5]])


问:
Method returns None even if value is not none in python 3
I'm getting input at run time. If first attempt itself correct input given means I'm not getting the error. Otherwise it is showing can't unpack non-iterable error.

I can see it is sending None if recursive method called once. Even it prints value before return, but after receiving it shows None.

```<code>class Game:
    def set_val(self):
        try:
            p1=input("Enter player 1 name:")
            p2=input("Enter player 2 name:")
            goal=int(input("Enter a number to set goal:"))
            if p1 is None or p2 is None or goal is None:
                print("Please give proper input")
                self.set_val()
            else:
                print(p1,p2,goal)
                return p1,p2,goal
        except:
            print("Please give proper input")
            self.set_val()
G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)
</code>```

OUTPUT:

```<code>Enter player 1 name:s
Enter player 2 name:c
Enter a number to set goal:s
Please give proper input
Enter player 1 name:s
Enter player 2 name:v
Enter a number to set goal:2
s v 2
Traceback (most recent call last):
  File "D:\test.py", line 18, in <module>
    p1,p2,goal=G.set_val()
TypeError: cannot unpack non-iterable NoneType object
</code>```

I can assume it because of recursive calls, but not able to figure it out why. Please explain give a solution to get all input values without error.

答:
Recursion has its uses, but using it to start over is not one of them.  Naked except is also bad.

If you need to loop, use a loop.

If you need to catch an exception, catch the expected exception.  That way if an unexpected exception occurs, you can see and deal with the bug.

Example:

```<code>class Game:
    def set_val(self):
        while True:
            p1=input("Enter player 1 name:")
            if p1: break
        while True:
            p2=input("Enter player 2 name:")
            if p2: break

        # Loop until good input
        # int() will throw ValueError if input is not convertible to int.
        while True:
            try:
                goal=int(input("Enter a number to set goal:"))
                break # break from the loop if no exception
            except ValueError:
                print("Please give proper input")

        return p1,p2,goal

G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)
</code>```

Body:
I'm getting input at run time. If first attempt itself correct input given means I'm not getting the error. Otherwise it is showing can't unpack non-iterable error.

I can see it is sending None if recursive method called once. Even it prints value before return, but after receiving it shows None.

class Game:
    def set_val(self):
        try:
            p1=input("Enter player 1 name:")
            p2=input("Enter player 2 name:")
            goal=int(input("Enter a number to set goal:"))
            if p1 is None or p2 is None or goal is None:
                print("Please give proper input")
                self.set_val()
            else:
                print(p1,p2,goal)
                return p1,p2,goal
        except:
            print("Please give proper input")
            self.set_val()
G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)

OUTPUT:

Enter player 1 name:s
Enter player 2 name:c
Enter a number to set goal:s
Please give proper input
Enter player 1 name:s
Enter player 2 name:v
Enter a number to set goal:2
s v 2
Traceback (most recent call last):
  File "D:\test.py", line 18, in <module>
    p1,p2,goal=G.set_val()
TypeError: cannot unpack non-iterable NoneType object

I can assume it because of recursive calls, but not able to figure it out why. Please explain give a solution to get all input values without error.

Body:
Recursion has its uses, but using it to start over is not one of them.  Naked except is also bad.

If you need to loop, use a loop.

If you need to catch an exception, catch the expected exception.  That way if an unexpected exception occurs, you can see and deal with the bug.

Example:

class Game:
    def set_val(self):
        while True:
            p1=input("Enter player 1 name:")
            if p1: break
        while True:
            p2=input("Enter player 2 name:")
            if p2: break

        # Loop until good input
        # int() will throw ValueError if input is not convertible to int.
        while True:
            try:
                goal=int(input("Enter a number to set goal:"))
                break # break from the loop if no exception
            except ValueError:
                print("Please give proper input")

        return p1,p2,goal

G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)


问:
sort_value working on Name column but not Number column in dataframe
When try to sort my dataframe by the column "Number" i get the error code

1708         # Check for duplicates

KeyError: 'Number'

the dataframe looks something like this

```<code>Number Name City Sex

3 Jay A M

1 Marry A F

5 John B M
</code>```

Number is int64 and the rest are objects

```<code>df.sort_values(by=['Number']) --> error

df.sort_values(by=['Name']) --> works

df.sort_values(by=['City']) --> error

df.sort_values(by=['Sex']) --> works
</code>```

What i  am looking for is something like this

```<code>Number Name City Sex

  1 Marry A F

  3 Jay A M

  5 John B M
</code>```

答:
I try to make a DataFrame like yours and sort it & it works to sort by Number column:

```<code>df=pd.DataFrame({'Number':[3,1,5],
                'Name':['Jay','Marry','John'],
                'City':['A','A','B'],
                'Sex':['M','F','M']})
print(df)
print(df.Number.dtype)
df=df.sort_values(by=['Number'])
print(df)
</code>```

Output:

```<code>   Number   Name City Sex
0       3    Jay    A   M
1       1  Marry    A   F
2       5   John    B   M

int64

   Number   Name City Sex
1       1  Marry    A   F
0       3    Jay    A   M
2       5   John    B   M
</code>```

Maybe there is a white space in your columns, try this before sorting:

```<code>df.columns=df.columns.str.strip()
</code>```

Body:
When try to sort my dataframe by the column "Number" i get the error code

1708         # Check for duplicates

KeyError: 'Number'

the dataframe looks something like this

Number Name City Sex

3 Jay A M

1 Marry A F

5 John B M

Number is int64 and the rest are objects

df.sort_values(by=['Number']) --> error

df.sort_values(by=['Name']) --> works

df.sort_values(by=['City']) --> error

df.sort_values(by=['Sex']) --> works

What i  am looking for is something like this

Number Name City Sex

  1 Marry A F

  3 Jay A M

  5 John B M

Body:
I try to make a DataFrame like yours and sort it & it works to sort by Number column:

df=pd.DataFrame({'Number':[3,1,5],
                'Name':['Jay','Marry','John'],
                'City':['A','A','B'],
                'Sex':['M','F','M']})
print(df)
print(df.Number.dtype)
df=df.sort_values(by=['Number'])
print(df)

Output:

   Number   Name City Sex
0       3    Jay    A   M
1       1  Marry    A   F
2       5   John    B   M

int64

   Number   Name City Sex
1       1  Marry    A   F
0       3    Jay    A   M
2       5   John    B   M

Maybe there is a white space in your columns, try this before sorting:

df.columns=df.columns.str.strip()


问:
Method importing parameter type range of any
I am trying to build a dynamic method and I need to pass any range table to it. So I want to make sure a) only a range can be passed or b) I leave the processing if the provided table is not a range. So my question would be:

Is there a way to define a method so the importing parameter has to be a range table (any type of range table)?

If there isn't any good was I would do it like this to check if the importet table is a range.

1) I would check for a table header.

```<code>Methods: this_method
  IMPORTING
    i_table TYPE any table.

IF i_table IS INITIAL.
  "do some code
ENDIF.
</code>```

If this doesn't work I'll take the longer way.

2) I would use cl_abap_*descr classes to find out if the passed table has fields named "sign", "option", "low", high".

答:
There isn't an equivalent of "any range table" typed parameter.

Your second option with RTTS would work.

Another option with a better performance that can only approve if the parameter is not of range table type, is to assign SIGN, OPTION etc... components of the first line if exists and then check IS NOT ASSIGNED.

Body:
I am trying to build a dynamic method and I need to pass any range table to it. So I want to make sure a) only a range can be passed or b) I leave the processing if the provided table is not a range. So my question would be:

Is there a way to define a method so the importing parameter has to be a range table (any type of range table)?

If there isn't any good was I would do it like this to check if the importet table is a range.

1) I would check for a table header.

Methods: this_method
  IMPORTING
    i_table TYPE any table.

IF i_table IS INITIAL.
  "do some code
ENDIF.

If this doesn't work I'll take the longer way.

2) I would use cl_abap_*descr classes to find out if the passed table has fields named "sign", "option", "low", high".


问:
Slide UITableViewCell
My goal is to have a UITableViewCell slide off one side of the screen (like in Twitter) and then slide back on from the other side. I'm able to make the cell slide off the screen to the right, but I can't seem to figure out how to get it to slide back onto the screen from the left right after. Here's my code to slide it off to the right:

```<code>UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];
[cell.layer setAnchorPoint:CGPointMake(0, 0.5)];
[cell.layer setPosition:CGPointMake(cell.frame.size.width, cell.layer.position.y)];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
[animation setRemovedOnCompletion:NO];
[animation setDelegate:self];
[animation setDuration:0.14];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[cell.layer addAnimation:animation forKey:@"reveal"];
</code>```

Thanks for any help!

答:
The behavior you want should be done by animating subviews of the cell, not the cell itself. The cell should stay in place in the table. Create a custom cell with the subviews you want in the contentArea and then slide those on/off as you like.

The standard UIView block based animations should work great for this as well.

Title: Slide UITableViewCell

Body:
My goal is to have a UITableViewCell slide off one side of the screen (like in Twitter) and then slide back on from the other side. I'm able to make the cell slide off the screen to the right, but I can't seem to figure out how to get it to slide back onto the screen from the left right after. Here's my code to slide it off to the right:

UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];
[cell.layer setAnchorPoint:CGPointMake(0, 0.5)];
[cell.layer setPosition:CGPointMake(cell.frame.size.width, cell.layer.position.y)];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
[animation setRemovedOnCompletion:NO];
[animation setDelegate:self];
[animation setDuration:0.14];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[cell.layer addAnimation:animation forKey:@"reveal"];

Thanks for any help!


问:
NGXS: Need to call method on change of state
I want to call method by passing the new state value to that method.

I am using selector @Select(AccountState.getAccount) account$: Observable;. Is there a way we can subscribe account$ and on change of the state we can call method?

答:
Yes, that is fairly trivial.

You should subscribe to the state in your component's ngOnInit method and then you can pass that state to whichever method you want.

```<code>@Component({
 ...
})
export class MyComponent implements OnInit, OnDestroy {

  @Select(AccountState.getAccount) account$: Observable;
  private accountSubscription: Subscription;

  constructor(...) { ... }

  ngOnInit() {
    this.accountSubscription = this.account$.subscribe(accountState => {
      this.componentMethod(accountState);
    });

  }

  ngOnDestroy() {
    // dont forget to unsubscribe upon component's life cycle end
    // to avoid memory leaks
    this.accountSubscription.unsubscribe();
  }

  componentMethod(accountState) {
    // do something with account state

  }}

}

</code>```

Body:
Yes, that is fairly trivial.

You should subscribe to the state in your component's ngOnInit method and then you can pass that state to whichever method you want.

@Component({
 ...
})
export class MyComponent implements OnInit, OnDestroy {

  @Select(AccountState.getAccount) account$: Observable;
  private accountSubscription: Subscription;

  constructor(...) { ... }

  ngOnInit() {
    this.accountSubscription = this.account$.subscribe(accountState => {
      this.componentMethod(accountState);
    });

  }

  ngOnDestroy() {
    // dont forget to unsubscribe upon component's life cycle end
    // to avoid memory leaks
    this.accountSubscription.unsubscribe();
  }

  componentMethod(accountState) {
    // do something with account state

  }}

}


问:
OpenAL Python openal.audio module not found
I was trying to do some work in Python with simulating 3D sound. I was trying to run this code (provided in the answer): Python openAL 3D sound and similar, both times receiving:

```<code>ModuleNotFoundError: No module named 'openal.audio'
</code>```

I've installed OpenAL, PyAL, and tried installing an older version (uninstalled it and reinstalled the new one), but it still doesn't work.

I've also tried the following code:

from openal import *

class AudioSource:
    def __init__(self, path_to_file):
        self.src = oalOpen(path_to_file)

    def play(self):
        self.src.play()
        self.src.position = (-100, 0, 0)
        self.src.update()
```

which doesn't use the openal.audio package, but the position doesn't seem to have any effect on the sound source either. I'm open to any solution (including using a newer package if one is available that will produce 3D sound)

答:
Using link to python OpenAL library at https://bitbucket.org/marcusva/py-al/downloads/

just download either the tar.gz or other one then once expanded it gives you dir something like

```<code>~/src/PyAL-0.1.0/
</code>```

then type

```<code>make
</code>```

if no errors there to install issue

```<code>make install

sudo make install  #  this works on ubuntu ... dunno about Windows or osx
</code>```

then to kick tires run the provided example

```<code>cd ~/src/PyAL-0.1.0/examples/
python ./player.py
</code>```

which is a rather nice 3D audio demo ... now your python import openal will work ... I confirmed this by running another script at https://stackoverflow.com/a/40945609/147175

If this still goes pear shaped what OS are you on ?

Body:
I was trying to do some work in Python with simulating 3D sound. I was trying to run this code (provided in the answer): Python openAL 3D sound and similar, both times receiving:

ModuleNotFoundError: No module named 'openal.audio'

I've installed OpenAL, PyAL, and tried installing an older version (uninstalled it and reinstalled the new one), but it still doesn't work.

I've also tried the following code:

from openal import *

class AudioSource:
    def __init__(self, path_to_file):
        self.src = oalOpen(path_to_file)

    def play(self):
        self.src.play()
        self.src.position = (-100, 0, 0)
        self.src.update()

which doesn't use the openal.audio package, but the position doesn't seem to have any effect on the sound source either. I'm open to any solution (including using a newer package if one is available that will produce 3D sound)

Body:
Using link to python OpenAL library at https://bitbucket.org/marcusva/py-al/downloads/

just download either the tar.gz or other one then once expanded it gives you dir something like

~/src/PyAL-0.1.0/

then type

make

if no errors there to install issue

make install

sudo make install  #  this works on ubuntu ... dunno about Windows or osx

then to kick tires run the provided example

cd ~/src/PyAL-0.1.0/examples/
python ./player.py

which is a rather nice 3D audio demo ... now your python import openal will work ... I confirmed this by running another script at https://stackoverflow.com/a/40945609/147175

If this still goes pear shaped what OS are you on ?


问:
How to use lapply or another higher order function when calling tabPanel in R shiny
I am using tabPanel in R shiny and would like to make the coder nicer by using a function like lapply

This is the tabBox

```<code>tabBox(
  title = mytitle, id = myid, width = "8",
  tabPanel(myTitle[1], icon = icon("adjust"), plotOutput(myPlot[1])),
  tabPanel(myTitle[2], icon = icon("adjust"), plotOutput(myPlot[2])),
  tabPanel(myTitle[3], icon = icon("adjust"), plotOutput(myPlot[3])),
  tabPanel(myTitle[4], icon = icon("adjust"), plotOutput(myPlot[4]))
)
</code>```

the vectors myTitle and myPlot are defined as

```<code>myTitle=c("A","B","C","D")
myPlot =c("X1","X2","X3","X4")
</code>```

How can I avoid repeated tabPanel definitions by using a higher order function, e.g. lapply or another one?

Thanks for any help

答:
```<code>do.call(function(...){
  tabBox(title = mytitle, id = myid, width = "8", ...)
}, mapply(function(title, plotid){
  tabPanel(title, icon = icon("adjust"), plotOutput(plotid))
}, myTitle, myPlot, SIMPLIFY = FALSE, USE.NAMES = FALSE))
</code>```

Not highly readable, but this avoids the repetitions.

Body:
I am using tabPanel in R shiny and would like to make the coder nicer by using a function like lapply

This is the tabBox

tabBox(
  title = mytitle, id = myid, width = "8",
  tabPanel(myTitle[1], icon = icon("adjust"), plotOutput(myPlot[1])),
  tabPanel(myTitle[2], icon = icon("adjust"), plotOutput(myPlot[2])),
  tabPanel(myTitle[3], icon = icon("adjust"), plotOutput(myPlot[3])),
  tabPanel(myTitle[4], icon = icon("adjust"), plotOutput(myPlot[4]))
)

the vectors myTitle and myPlot are defined as

myTitle=c("A","B","C","D")
myPlot =c("X1","X2","X3","X4")

How can I avoid repeated tabPanel definitions by using a higher order function, e.g. lapply or another one?

Thanks for any help

Body:
do.call(function(...){
  tabBox(title = mytitle, id = myid, width = "8", ...)
}, mapply(function(title, plotid){
  tabPanel(title, icon = icon("adjust"), plotOutput(plotid))
}, myTitle, myPlot, SIMPLIFY = FALSE, USE.NAMES = FALSE))

Not highly readable, but this avoids the repetitions.


问:
How to implement this in Scheme
I'm pretty new in Scheme and I'm having some problems with one exercise.

Here it goes: Write the genlist function taking two integer as parameter and returning a list containing the set of integers contained between the two provided

For example: (genlist 5 12) => (5 6 7 8 9 10 11 12)

I already did in Python but I dont know how to implement in Scheme.

答:
You can do this using recursion.

The base case for (genlist x y) is when x == y, in that case produce (list x)

The recursive stop would be from (genlist x y) to (genlist (+ x 1) y)

Title: How to implement this in Scheme


问:
Java avoid java.lang.OutOfMemoryError while reading a file but using streams at the same time
I'm trying to read a very large file with streams so I need parallel streams and not iterations per line... I'm trying as follows:

```<code>String cont = new String(Files.readAllBytes(Paths.get(this.File_Path)),
            StandardCharsets.UTF_8);
List<String> words = Arrays.asList(cont.split("\\PL+"));

yep = words.parallelStream()
            .filter(x -> x.contains(toMatch))
            .distinct()
            .collect(Collectors.toList());
</code>```

This works for small file size, but if I try to make the same with a file that has some gbs of size java gives me this exception:

```<code>java.lang.OutOfMemoryError: Required array size too large
</code>```

There is a way to avoid this exception but using parallel stream at the same time instead of iterate with BufferReader or Scanner?

答:
The problem is Files.readAllBytes(). It loads the whole content of the file in a String, therefore in memory.

To read line by line you want to use Files.lines() that returns a Stream<String> and then transform it into a parallel stream and do your transform operation on it :

```<code>List<String> words =
    Files.lines(Paths.get(this.File_Path), charSetOfYourFileIfNotUTF8) // Stream<String>
         .parallel()
         .flatMap(s-> Arrays.stream(s.split("\\PL+"))) // Stream<String>
         .filter(x -> x.contains(toMatch))
         .distinct()
         .collect(Collectors.toList());
</code>```

About performance, note that distinct() in parallel pipelines is expensive with an collect that maintain the order.

You should consider toSet() to improve further performance.

Body:
I'm trying to read a very large file with streams so I need parallel streams and not iterations per line... I'm trying as follows:

String cont = new String(Files.readAllBytes(Paths.get(this.File_Path)),
            StandardCharsets.UTF_8);
List<String> words = Arrays.asList(cont.split("\\PL+"));

yep = words.parallelStream()
            .filter(x -> x.contains(toMatch))
            .distinct()
            .collect(Collectors.toList());

This works for small file size, but if I try to make the same with a file that has some gbs of size java gives me this exception:

java.lang.OutOfMemoryError: Required array size too large

There is a way to avoid this exception but using parallel stream at the same time instead of iterate with BufferReader or Scanner?

Body:
The problem is Files.readAllBytes(). It loads the whole content of the file in a String, therefore in memory.

To read line by line you want to use Files.lines() that returns a Stream<String> and then transform it into a parallel stream and do your transform operation on it :

List<String> words =
    Files.lines(Paths.get(this.File_Path), charSetOfYourFileIfNotUTF8) // Stream<String>
         .parallel()
         .flatMap(s-> Arrays.stream(s.split("\\PL+"))) // Stream<String>
         .filter(x -> x.contains(toMatch))
         .distinct()
         .collect(Collectors.toList());

About performance, note that distinct() in parallel pipelines is expensive with an collect that maintain the order.

You should consider toSet() to improve further performance.


问:
MembershipProvider and RequiresQuestionAndAnswer
We provide a website template for our customers to use as the basis of their websites. Our website has a custom membership provider.

We have had a problem raised by one customer. The customer sends out invitations to prospective members by email with a url to login the member. During registration they set their security question / answer.

However sometimes the prospective member loses the email (and therefore their password) but still tries to join the site.

The customer requested that the member be allowed to reset their password without the usual security question / answer when registration was not complete.

Unfortunately the MembershipProvider doesn't provide the username when requesting whether the question / answer are required. However it does call GetUser() just before.

To get this feature working I added a method (StartingPasswordRecovery) to my MembershipProvider to flag that password reset was active, calling it from the OnVerifyingUser event in the PasswordRecovery page.

While this code works I'm not convinced that it's very robust.

Can anyone point me towards a better solution.

Here's the relevant code I added to my membership provider.

```<code>Private _hasUserDefinedQuestionAndAnswer As Boolean
Private _isResettingPassword As Boolean

Public Overloads Overrides Function GetUser(ByVal username As String, ByVal userIsOnline As Boolean) As System.Web.Security.MembershipUser
    ...
    _hasUserDefinedQuestionAndAnswer = ...
    ...
End Function

Public Overrides ReadOnly Property RequiresQuestionAndAnswer() As Boolean
    Get
        If Me._isResettingPassword Then
            Me._isResettingPassword = False
            Return Me.pRequiresQuestionAndAnswer And Me._hasUserDefinedQuestionAndAnswer
        End If

        Return Me.pRequiresQuestionAndAnswer
    End Get
End Property

Public Sub StartingPasswordRecovery()
    Me._isResettingPassword = True
End Sub
</code>```

答:
I'm not sure if i've understood you correctly, but couldn't you use the User-Profile to determine if a user requires question and answer or not?

web.config:

```<code><profile defaultProvider="YourProfileProvider">
    <providers>
        <clear/>
        <add name="YourProfileProvider" type="System.Web.Profile.SqlProfileProvider"  connectionStringName="ConnectionStringToDB" applicationName="/YourApp"></add>
    </providers>
    <properties>
        <add name="RequiresQuestionAndAnswer" defaultValue="false" />
    </properties>
</profile>
</code>```

Custom membership-provider:

```<code>Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Dim userRequiresQuestionAndAnswer = _
                CType(HttpContext.Current.Profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property
</code>```

You could set it in your user-management page for every user individually:

```<code>HttpContext.Current.Profile.SetPropertyValue("RequiresQuestionAndAnswer", userRequiresQuestionAndAnswer)
HttpContext.Current.Profile.Save()
</code>```

Edit:

according to your comment, i've modified the code a little bit. I hope that helps to get it working:

in custom membership-provider:

```<code>Public Overloads Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Return RequiresQuestionAndAnswer(Membership.GetUser.UserName)
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

Public Overloads ReadOnly Property RequiresQuestionAndAnswer(ByVal userName As String) As Boolean
    Get
        Dim profile As ProfileBase = ProfileBase.Create(userName)
        If Not profile Is Nothing Then
            Dim userRequiresQuestionAndAnswer = _
                CType(profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property
</code>```

where your PasswordRecovery-Control is:

```<code>Protected Sub VerifyingUser(ByVal sender As Object, ByVal e As LoginCancelEventArgs)
    Dim login As WebControls.Login = DirectCast(Me.LoginView1.FindControl("Login1"), WebControls.Login)
    Dim userName = DirectCast(login.FindControl("PwdRecovery"), PasswordRecovery).UserName
    Dim RequiresQuestionAndAnswer = DirectCast(Membership.Provider, YourMembershipProvider).RequiresQuestionAndAnswer(userName)
    '....'
End Sub
</code>```

Body:
We provide a website template for our customers to use as the basis of their websites. Our website has a custom membership provider.

We have had a problem raised by one customer. The customer sends out invitations to prospective members by email with a url to login the member. During registration they set their security question / answer.

However sometimes the prospective member loses the email (and therefore their password) but still tries to join the site.

The customer requested that the member be allowed to reset their password without the usual security question / answer when registration was not complete.

Unfortunately the MembershipProvider doesn't provide the username when requesting whether the question / answer are required. However it does call GetUser() just before.

To get this feature working I added a method (StartingPasswordRecovery) to my MembershipProvider to flag that password reset was active, calling it from the OnVerifyingUser event in the PasswordRecovery page.

While this code works I'm not convinced that it's very robust.

Can anyone point me towards a better solution.

Here's the relevant code I added to my membership provider.

Private _hasUserDefinedQuestionAndAnswer As Boolean
Private _isResettingPassword As Boolean

Public Overloads Overrides Function GetUser(ByVal username As String, ByVal userIsOnline As Boolean) As System.Web.Security.MembershipUser
    ...
    _hasUserDefinedQuestionAndAnswer = ...
    ...
End Function

Public Overrides ReadOnly Property RequiresQuestionAndAnswer() As Boolean
    Get
        If Me._isResettingPassword Then
            Me._isResettingPassword = False
            Return Me.pRequiresQuestionAndAnswer And Me._hasUserDefinedQuestionAndAnswer
        End If

        Return Me.pRequiresQuestionAndAnswer
    End Get
End Property

Public Sub StartingPasswordRecovery()
    Me._isResettingPassword = True
End Sub

Body:
I'm not sure if i've understood you correctly, but couldn't you use the User-Profile to determine if a user requires question and answer or not?

web.config:

<profile defaultProvider="YourProfileProvider">
    <providers>
        <clear/>
        <add name="YourProfileProvider" type="System.Web.Profile.SqlProfileProvider"  connectionStringName="ConnectionStringToDB" applicationName="/YourApp"></add>
    </providers>
    <properties>
        <add name="RequiresQuestionAndAnswer" defaultValue="false" />
    </properties>
</profile>

Custom membership-provider:

Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Dim userRequiresQuestionAndAnswer = _
                CType(HttpContext.Current.Profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

You could set it in your user-management page for every user individually:

HttpContext.Current.Profile.SetPropertyValue("RequiresQuestionAndAnswer", userRequiresQuestionAndAnswer)
HttpContext.Current.Profile.Save()

Edit:

according to your comment, i've modified the code a little bit. I hope that helps to get it working:

in custom membership-provider:

Public Overloads Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Return RequiresQuestionAndAnswer(Membership.GetUser.UserName)
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

Public Overloads ReadOnly Property RequiresQuestionAndAnswer(ByVal userName As String) As Boolean
    Get
        Dim profile As ProfileBase = ProfileBase.Create(userName)
        If Not profile Is Nothing Then
            Dim userRequiresQuestionAndAnswer = _
                CType(profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

where your PasswordRecovery-Control is:

Protected Sub VerifyingUser(ByVal sender As Object, ByVal e As LoginCancelEventArgs)
    Dim login As WebControls.Login = DirectCast(Me.LoginView1.FindControl("Login1"), WebControls.Login)
    Dim userName = DirectCast(login.FindControl("PwdRecovery"), PasswordRecovery).UserName
    Dim RequiresQuestionAndAnswer = DirectCast(Membership.Provider, YourMembershipProvider).RequiresQuestionAndAnswer(userName)
    '....'
End Sub


问:
How to get ForeignKey field value during new model creation?
I'm looking for the most efficient way to implement this kind of mechanism in Django model.
Let's assume a situation, where there are 2 very simple models:

```<code>class FKModel(models.Model):
    value = BooleanField()

class AModel(models.Model):
    fk = models.ForeignKey(FKModel)
    a_value = models.CharField(max_length=150)

    def clean(self, *args, **kwargs):
        # the line below is incorrect
        if not self.fk.value:    # <--- how to do this in a proper way?
            raise ValidationError('FKModel value is False')
        super(AModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(AModel, self).save(*args, **kwargs)
</code>```

I know, that I can do somethink like FKModel.objects.all()/.get(), but I don't think it is the best solution (as it requires additional requests to database).

答:
I am not sure what you try to do in your clean() method, but I assume you are trying to constrain a not null condition for the foreign key. All fields are not null constrained by default, and you have to set null=False and blank=False if you want the field to accept nulls:

```<code>class AModel(models.Model):
    fk = models.ForeignKey(FKModel, null=True, blank=True)
    a_value = models.CharField(max_length=150)
</code>```

If you want to constrain a not null condition for a field by hand, you should do it like this:

```<code>class FKModel(models.Model):
    value = BooleanField()

class AModel(models.Model):
    fk = models.ForeignKey(FKModel)
    a_value = models.CharField(max_length=150)

    def clean(self, *args, **kwargs):
        # the line below is correct
        if self.fk is None:    # <--- this is the proper way?
            raise ValidationError('FKModel value is False')
        super(AModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(AModel, self).save(*args, **kwargs)
</code>```

For retrieving database records and its related records, you use prefetch_related, and you get your record and its related records in one single database hit:

```<code>AModel.objects.all().prefetch_related('fk')
</code>```

Body:
I'm looking for the most efficient way to implement this kind of mechanism in Django model.
Let's assume a situation, where there are 2 very simple models:

class FKModel(models.Model):
    value = BooleanField()

class AModel(models.Model):
    fk = models.ForeignKey(FKModel)
    a_value = models.CharField(max_length=150)

    def clean(self, *args, **kwargs):
        # the line below is incorrect
        if not self.fk.value:    # <--- how to do this in a proper way?
            raise ValidationError('FKModel value is False')
        super(AModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(AModel, self).save(*args, **kwargs)

I know, that I can do somethink like FKModel.objects.all()/.get(), but I don't think it is the best solution (as it requires additional requests to database).

Body:
I am not sure what you try to do in your clean() method, but I assume you are trying to constrain a not null condition for the foreign key. All fields are not null constrained by default, and you have to set null=False and blank=False if you want the field to accept nulls:

class AModel(models.Model):
    fk = models.ForeignKey(FKModel, null=True, blank=True)
    a_value = models.CharField(max_length=150)

If you want to constrain a not null condition for a field by hand, you should do it like this:

class FKModel(models.Model):
    value = BooleanField()

class AModel(models.Model):
    fk = models.ForeignKey(FKModel)
    a_value = models.CharField(max_length=150)

    def clean(self, *args, **kwargs):
        # the line below is correct
        if self.fk is None:    # <--- this is the proper way?
            raise ValidationError('FKModel value is False')
        super(AModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(AModel, self).save(*args, **kwargs)

For retrieving database records and its related records, you use prefetch_related, and you get your record and its related records in one single database hit:

AModel.objects.all().prefetch_related('fk')


问:
Modifying an HTML Element through a JS Class
When defining a method on a user defined class that includes an HTML element JS throws a TypeError saying object.method is not a function.

My hunch is when only returning document.createElement the class inherits HTML object methods that prevent user defined methods from working? So my thought was to contain the HTML object as an element within an array, but still no dice.

```<code>class inputBox {
    constructor(attributeList){
        let element = document.createElement('input')
        //just creating a unique ID here
        attributeList.id = Math.random().toString(36).substr(2, 16);
        for (let attr in attributeList){
            this[attr] = attributeList[attr]
            element.setAttribute(attr,this[attr])
        }
        return [element,attributeList]
    };

    updateValue(newValue) {
        let element = document.querySelector(`#${this[1].id}`)
        return element.value = newValue
    };
}
</code>```

this works fine

```<code>document.body.appendChild(inputBox1[0])
</code>```

this not so much (note: there is no [0] since I'm querying the DOM)

```<code>inputBox1.updateValue("hello")
</code>```

The idea is you could call something like the following with multiple parameters
var inputBox1 = new inputBox({type:'email', placeholder:'Your email'})

I think this is achievable with jquery, but was attempting a vanilla approach as learning exercise. Thx

答:
Whenever you explicitly return an object from a constructor, the return value will be just that object, and not an instance of the class. When you do

```<code>return [element,attributeList]
</code>```

what is returned is just a plain array, without anything connected to an inputBox, so proceeding to reference an inputBox class method on that array won't work.

Instead, put the element and attributeList onto the instance.

By putting the element onto the instance, you can also avoid creating a dynamic unique ID for each element (which is a code smell) - rather, just reference the this.element:

```<code>class inputBox {
    constructor(attributeList){
        this.element = document.createElement('input');
        this.attributeList = attributeList;
        for (const attr in attributeList){
            this.element.setAttribute(attr,this.attributeList[attr]);
        }
    }

    updateValue(newValue) {
        this.element.value = newValue;
    }
}
</code>```

Still, unless there's going to be more code in the inputBox, there doesn't seem to be any use of the class here - after construction, its only exposed functionality is to set the value of the input, which could be done less obscurely by just using a reference to the input. Consider having a function that assigns the attributeList to the element's attributes, and then just using the plain element, eg:

```<code>const myInput = assignAttributes(attributeList);
// ...
myInput.value = 'newValue';
</code>```

Body:
When defining a method on a user defined class that includes an HTML element JS throws a TypeError saying object.method is not a function.

My hunch is when only returning document.createElement the class inherits HTML object methods that prevent user defined methods from working? So my thought was to contain the HTML object as an element within an array, but still no dice.

class inputBox {
    constructor(attributeList){
        let element = document.createElement('input')
        //just creating a unique ID here
        attributeList.id = Math.random().toString(36).substr(2, 16);
        for (let attr in attributeList){
            this[attr] = attributeList[attr]
            element.setAttribute(attr,this[attr])
        }
        return [element,attributeList]
    };

    updateValue(newValue) {
        let element = document.querySelector(`#${this[1].id}`)
        return element.value = newValue
    };
}

this works fine

document.body.appendChild(inputBox1[0])

this not so much (note: there is no [0] since I'm querying the DOM)

inputBox1.updateValue("hello")

The idea is you could call something like the following with multiple parameters
var inputBox1 = new inputBox({type:'email', placeholder:'Your email'})

I think this is achievable with jquery, but was attempting a vanilla approach as learning exercise. Thx

Body:
Whenever you explicitly return an object from a constructor, the return value will be just that object, and not an instance of the class. When you do

return [element,attributeList]

what is returned is just a plain array, without anything connected to an inputBox, so proceeding to reference an inputBox class method on that array won't work.

Instead, put the element and attributeList onto the instance.

By putting the element onto the instance, you can also avoid creating a dynamic unique ID for each element (which is a code smell) - rather, just reference the this.element:

class inputBox {
    constructor(attributeList){
        this.element = document.createElement('input');
        this.attributeList = attributeList;
        for (const attr in attributeList){
            this.element.setAttribute(attr,this.attributeList[attr]);
        }
    }

    updateValue(newValue) {
        this.element.value = newValue;
    }
}

Still, unless there's going to be more code in the inputBox, there doesn't seem to be any use of the class here - after construction, its only exposed functionality is to set the value of the input, which could be done less obscurely by just using a reference to the input. Consider having a function that assigns the attributeList to the element's attributes, and then just using the plain element, eg:

const myInput = assignAttributes(attributeList);
// ...
myInput.value = 'newValue';


问:
How to fix drop dawn button in Bootstrap
Toggle button working in pure HTML but not working in Laravel blade, I don't know why?
When I click toggle button its aria-expanded change to true from false but when I click toggle button again aria-expand doesn't change.
I checked everything nothing seems wrong.

Here is my code in blade:

```<code> <!-- File: ./resources/views/layouts/master.blade.php -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-
    scale=1.0">
            <meta name="csrf-token" content="{{ csrf_token() }}">
            <script src="{{ asset('js/app.js') }}" defer></script>
            <title></title>
            <link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

               <!-- main css -->
               <link rel="stylesheet" href="{{asset('css/style.css')}}">
               <link rel="stylesheet" href="{asset('css/responsive.css')}}">
  </head>
    <body>
        <header class="header_area">
            <div class="main_menu" id="mainNav">
                <nav class="navbar navbar-expand-lg navbar-light ">
                    <div class="container">
                        <!-- Brand and toggle get grouped for better mobile display -->
                        <button class="navbar-toggler "  type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" ">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <!-- Collect the nav links, forms, and other content for toggling -->
                        <div class="collapse navbar-collapse offset" id="navbarSupportedContent">
                            <ul class="nav navbar-nav menu_nav ml-auto" >

                                <li class="nav-item active"><a class="nav-link" href="{{ url('/about') }}">درباره ما</a></li>
                                <li class="nav-item submenu dropdown">
                                    <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">محصولات</a>
                                    <ul class="dropdown-menu">
                                        <li class="nav-item"><a class="nav-link" href="{{url('/azmayeshgahi')}}">آزمایشگاهی</a></li>
                                        <li class="nav-item"><a class="nav-link" href="{{ url('/sanati') }}">صنعتی</a></li>
                                    </ul>
                                </li>
                                <li class="nav-item"><a class="nav-link" href="{{ url('/contact-us') }}">ارتباط با ما</a></li>
                                <li class="nav-item"><a class="nav-link" href="{{ url('/blog') }}">اخبار</a></li>
                                <li class="nav-item"><a class="nav-link" href="{{ url('/') }}">خانه</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>
            </div>
        </header>

       <div style="direction:rtl;" id="app">
            @yield('content')
        </div>

        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="{{asset('js/popper.js')}}"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

    </body>
</html>
</code>```

答:
I find the answer,I just delet the app.js but still i dont know why this happen.
and do i need app.js</p>

Body:
Toggle button working in pure HTML but not working in Laravel blade, I don't know why?
When I click toggle button its aria-expanded change to true from false but when I click toggle button again aria-expand doesn't change.
I checked everything nothing seems wrong.

Here is my code in blade:

    <!DOCTYPE html>

            <meta charset="utf-8">
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-
    scale=1.0">
            <meta name="csrf-token" content="{{ csrf_token() }}">

            <title></title>
            <link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

               <link rel="stylesheet" href="{{asset('css/style.css')}}">
               <link rel="stylesheet" href="{asset('css/responsive.css')}}">

                        <button class="navbar-toggler "  type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" ">

                        </button>

درباره ما

                                    محصولات

آزمایشگاهی

صنعتی

ارتباط با ما

اخبار

خانه

            @yield('content')


问:
MailApp.sendEmail returns strange error when assigning array variable as recipient
I am simply trying to use script in my Google Sheet to send some emails but I am getting an odd error code.

Does the failure have something to do with the brackets around the stored array variable?

What am I missing?

This all works if I manually enter an email address into the script. And it works if I use a simple variable assignment instead of an array.

But I have seen many examples where an array variable is used in the "recipient" or "to" field of the sendEmail syntax.

```<code> //Code A - this works
 for(var x=0; x <= emails.length; x++){
   if(checkedCells[x] = "True" && emails[x] != ""){

   console.log(emails[x]);
   var testEmail = "me@me.com";

      MailApp.sendEmail({
         to: testEmail,
         replyTo: replyEmail,
         subject: subjectLine,
         Body: messageBody,

      });

   }
 }

 //Code B - this gives an error
 for(var x=0; x <= emails.length; x++){
   if(checkedCells[x] = "True" && emails[x] != ""){

   console.log(emails[x]);

      MailApp.sendEmail({
         to: emails[x],
         replyTo: replyEmail,
         subject: subjectLine,
         Body: messageBody,

      });

   }
 }
</code>```

Code A works fine.

Code B does not send the email and gives a different error each time, always beginning with "ERROR
Invalid email: [L" and ending with random characters like ";@388e5b32 at sendScreener(Code:690)"

I notice in the Stackdriver log that testEmail results in
me@me.com

While emails[x] results in
[me@me.com]

...because it is an array variable. Does this matter?

Thanks!

答:
Solved... just needed ".toString()"  after the array... </p>

```<code>to: emails[x].toString()
</code>```

Body:
I am simply trying to use script in my Google Sheet to send some emails but I am getting an odd error code.

Does the failure have something to do with the brackets around the stored array variable?

What am I missing?

This all works if I manually enter an email address into the script. And it works if I use a simple variable assignment instead of an array.

But I have seen many examples where an array variable is used in the "recipient" or "to" field of the sendEmail syntax.

 //Code A - this works
 for(var x=0; x <= emails.length; x++){
   if(checkedCells[x] = "True" && emails[x] != ""){

   console.log(emails[x]);
   var testEmail = "me@me.com";

      MailApp.sendEmail({
         to: testEmail,
         replyTo: replyEmail,
         subject: subjectLine,
         Body: messageBody,

      });

   }
 }

 //Code B - this gives an error
 for(var x=0; x <= emails.length; x++){
   if(checkedCells[x] = "True" && emails[x] != ""){

   console.log(emails[x]);

      MailApp.sendEmail({
         to: emails[x],
         replyTo: replyEmail,
         subject: subjectLine,
         Body: messageBody,

      });

   }
 }

Code A works fine.

Code B does not send the email and gives a different error each time, always beginning with "ERROR
Invalid email: [L" and ending with random characters like ";@388e5b32 at sendScreener(Code:690)"

I notice in the Stackdriver log that testEmail results in
me@me.com

While emails[x] results in
[me@me.com]

...because it is an array variable. Does this matter?

Thanks!

Body:
Solved... just needed ".toString()"  after the array...

to: emails[x].toString()


问:
Missing last line in file
Using the code below. It will not copy the last line in the file.

I have tried the following means of reading the file.

"while IFS=$'\n' read -d '' -r -a myLine" or "while IFS=$'\n' read -r -a myLine"

```<code>while read -a myLine
do
  for ((i=0;i<"${#myLine[@]}";i++))
  do
    temp_array[$i]+=" ${myLine[$i]}"
  done
done < $1
</code>```

File contains numbers like:

```<code>1 2
3 4
5 6
</code>```

when echo is used to see what is in the array i get

```<code>1 2
3 4
</code>```

this is where it drops off the last line.

答:
Since Bash 4:</p>

```<code>mapfile -t MyArray < "$1"
</code>```

Title: Missing last line in file

Body:
Using the code below. It will not copy the last line in the file.

I have tried the following means of reading the file.

"while IFS=$'\n' read -d '' -r -a myLine" or "while IFS=$'\n' read -r -a myLine"

while read -a myLine
do
  for ((i=0;i<"${#myLine[@]}";i++))
  do
    temp_array[$i]+=" ${myLine[$i]}"
  done
done < $1

File contains numbers like:

1 2
3 4
5 6

when echo is used to see what is in the array i get

1 2
3 4

this is where it drops off the last line.

Body:
Since Bash 4:

mapfile -t MyArray < "$1"


问:
What is the "M- notation" and where is it documented?
The man page of cat  says:

```<code>-v, --show-nonprinting
    use ^ and M- notation, except for LFD and TAB
</code>```

What is the M- notation and where is it documented?

Example:

```<code>$cat log -A
wrote 262144 bytes from file test.x in 9.853947s (25.979 KiB/s)^M$
^M> ^H^H  ^H^H>
</code>```

What do ^M and ^H mean?

答:
I am not sure about the M- notation, but the ones involving ^ uses the caret notation:

Caret notation is a notation for control characters in ASCII.

In particular,

The digraph stands for the control character whose ASCII code is the
  same as the character's ASCII code with the uppermost bit, in a 7-bit
  encoding, reversed.

which you can verify by looking at the ASCII binary (octal) representation:

Image source: http://www.asciitable.com

Because ASCII is such a limited character set (as you can see above), it's straightforward to list all control chars representable by the caret notation, e.g., http://xahlee.info/comp/unicode_character_representation.html.

Body:
The man page of cat  says:

-v, --show-nonprinting
    use ^ and M- notation, except for LFD and TAB

What is the M- notation and where is it documented?

Example:

$cat log -A
wrote 262144 bytes from file test.x in 9.853947s (25.979 KiB/s)^M$
^M> ^H^H  ^H^H>

What do ^M and ^H mean?


问:
git rebase --continue still sees conflicts, git status tells me there are none
I am running a fairly complex rebase that had gone well for the last few commits. I fixed a very small conflict and somehow got stuck in limbo --

```<code>    ╰─$ git status
rebase in progress; onto 99e642b
You are currently rebasing branch 'Vince_issue_157' on '99e642b'.
  (all conflicts fixed: run "git rebase --continue")

nothing to commit, working tree clean

    ╰─$ git rebase --continue Applying: RM debugger No changes - did you forget to use git add?
</code>```

Shouldn't those two be contradictions? How can I figure out what git doesnt like?

Quick reflog output if that raises any red flags

```<code>dc04ac4 (HEAD) HEAD@{0}: rebase: improve warning
f97482a HEAD@{1}: rebase: incomplete test for new warning
e73be23 HEAD@{2}: rebase: warning (that needs tweak) on default lang with no translation problem
99e642b (upstream/master, master) HEAD@{3}: rebase: checkout master
5d8b393 (origin/Vince_issue_157, Vince_issue_157) HEAD@{4}: checkout: moving from master to Vince_issue_157
99e642b (upstream/master, master) HEAD@{5}: reset: moving to upstream/master
</code>```

答: I think the problem is that there are no changes to be applied for this revision. Probably you want to do git rebase --skip

Body:
I am running a fairly complex rebase that had gone well for the last few commits. I fixed a very small conflict and somehow got stuck in limbo --

    ╰─$ git status
rebase in progress; onto 99e642b
You are currently rebasing branch 'Vince_issue_157' on '99e642b'.
  (all conflicts fixed: run "git rebase --continue")

nothing to commit, working tree clean

    ╰─$ git rebase --continue Applying: RM debugger No changes - did you forget to use git add?

Shouldn't those two be contradictions? How can I figure out what git doesnt like?

Quick reflog output if that raises any red flags

dc04ac4 (HEAD) HEAD@{0}: rebase: improve warning
f97482a HEAD@{1}: rebase: incomplete test for new warning
e73be23 HEAD@{2}: rebase: warning (that needs tweak) on default lang with no translation problem
99e642b (upstream/master, master) HEAD@{3}: rebase: checkout master
5d8b393 (origin/Vince_issue_157, Vince_issue_157) HEAD@{4}: checkout: moving from master to Vince_issue_157
99e642b (upstream/master, master) HEAD@{5}: reset: moving to upstream/master


问:
Xamarin forms twoway binding not firing after initial load
I have a problem which has taken hours upon hours of my time.  I am sure I am missing something obvious.  I have reproduced the issue on a simplified form which uses just 1 button and 1 label.  Label correctly sets to initial value.  Upon button click I am trying to change the label text.  From David to Terry.

Command button is firing, setter is getting called, onPropertyChange is getting called.  Interestingly after initial debug the get'er is not fired again.  (Checked all obvious things, property is public and a property, it is named correctly, specified TwoWay)

...

```<code>//--- View Model code ---//
public class TestBindingVM : INotifyPropertyChanged
{
    private string profileName;

    public ICommand ChangeTextCommand { get; }

    public TestBindingVM()
    {
        ProfileName = "David";
        ChangeTextCommand = new Command(UpdateTextCommandAction);
    }

    public void UpdateTextCommandAction()
    {
        ProfileName = "Terry";
    }

    public string ProfileName
    {
        get => profileName;
        set
        {
            profileName = value;
            OnPropertyChanged("ProfileName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var propertyChangedCallback = PropertyChanged;
        propertyChangedCallback?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
// ---------------------
// Complete XAML Layout :
//----------------------
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="TrackManager.Views.TestBindingPage">
  <ContentPage.Content>
    <StackLayout>
        <Label Text="{Binding Path=ProfileName}"
            VerticalOptions="CenterAndExpand"
            HorizontalOptions="CenterAndExpand" />
        <Button Margin="0,10,0,0" Text="Change Text"
                    Command="{Binding ChangeTextCommand}"
                    TextColor="White"
                    />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

///----------------------------------------------//
// The page code, creating the bindingcontext    //
///----------------------------------------------//
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestBindingPage : ContentPage
{
    public ViewModels.TestBindingVM vm = new ViewModels.TestBindingVM();

    public TestBindingPage ()
    {
        this.BindingContext = vm;
        InitializeComponent();
    }
}
</code>```

...

This is similar to this post, which did not get a complete answer.  Perhaps due to missing code:

Two way binding Not working In Xamarin Forms

It is just so strange that the value "David" is shown on loading.  Which shows binding is close to working.

Help appreciated.

答: Just for the record, I found the issue.  For some reason there was a local, empty interface of INPC.  I guess when using the refactor function I clicked implement interface rather than add 'using'.  Therefore when the INPC isn't doing what it clearly should, check you are using the actual INPC not some stub :-)</p>

Body:
I have a problem which has taken hours upon hours of my time.  I am sure I am missing something obvious.  I have reproduced the issue on a simplified form which uses just 1 button and 1 label.  Label correctly sets to initial value.  Upon button click I am trying to change the label text.  From David to Terry.

Command button is firing, setter is getting called, onPropertyChange is getting called.  Interestingly after initial debug the get'er is not fired again.  (Checked all obvious things, property is public and a property, it is named correctly, specified TwoWay)

...

//--- View Model code ---//
public class TestBindingVM : INotifyPropertyChanged
{
    private string profileName;

    public ICommand ChangeTextCommand { get; }

    public TestBindingVM()
    {
        ProfileName = "David";
        ChangeTextCommand = new Command(UpdateTextCommandAction);
    }

    public void UpdateTextCommandAction()
    {
        ProfileName = "Terry";
    }

    public string ProfileName
    {
        get => profileName;
        set
        {
            profileName = value;
            OnPropertyChanged("ProfileName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var propertyChangedCallback = PropertyChanged;
        propertyChangedCallback?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
// ---------------------
// Complete XAML Layout :
//----------------------
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="TrackManager.Views.TestBindingPage">
  <ContentPage.Content>
    <StackLayout>

        <Button Margin="0,10,0,0" Text="Change Text"
                    Command="{Binding ChangeTextCommand}"
                    TextColor="White"
                    />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

///----------------------------------------------//
// The page code, creating the bindingcontext    //
///----------------------------------------------//
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestBindingPage : ContentPage
{
    public ViewModels.TestBindingVM vm = new ViewModels.TestBindingVM();

    public TestBindingPage ()
    {
        this.BindingContext = vm;
        InitializeComponent();
    }
}

...

This is similar to this post, which did not get a complete answer.  Perhaps due to missing code:

Two way binding Not working In Xamarin Forms

It is just so strange that the value "David" is shown on loading.  Which shows binding is close to working.

Help appreciated.


问:
Using a int value, which is in another class file?
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

```<code>/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}
</code>```

答:
The standard OOP way to pass data between classes is using getters/setters:

```<code>class Gui {
    private int gameState;

    public void setGameState(int gameState) {
        this.gameState = gameState;
    }
}
</code>```

Of course, you can use a static variable, but this is generally considered bad practice.

Body:
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}

Body:
The standard OOP way to pass data between classes is using getters/setters:

class Gui {
    private int gameState;

    public void setGameState(int gameState) {
        this.gameState = gameState;
    }
}

Of course, you can use a static variable, but this is generally considered bad practice.


问:
(Laravel 5.8) How to get verbosity level inside Exception Handler class
I'm trying to get the verbosity level INSIDE the Exception Handler class so I can print more or less information.

I'm writing a batch script that runs over hundreds of thousands loops and so that my goal is to limit the verbosity of the stack trace, since in this case the only useful traces are the last 3 or 4.

I've tried some other answers given here in SO and have read all around Internet, but none of ther talk about working inside the exception handler.
The one that looks closer is this answer that states $this->getOutput()->getVerbosity();but that doesn't works inside the error handler.

This is my code:

```<code><?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Mail;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use App\Mail\ExceptionOccured;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Output\OutputInterface;

class Handler extends ExceptionHandler
...
...
public function render($request, Exception $e)
    {
        // return parent::render($request, $e);
        Log::error($this->buildMessage($e));
    }

    public function buildMessage($e)
    {
        $verbosity_level = $this->getOutput()->getVerbosity();
        $is_verbose = ($verbosity_level >= OutputInterface::VERBOSITY_DEBUG);

        $t0 = $e->getTrace()[0];
        $tm = "Error: [{$e->getCode()}] {$e->getMessage()} @ {$t0['file']}:{$t0['line']}".PHP_EOL;
        // if ($is_verbose){
            ...(more code) ...
        // }
        return $tm;
    }
}
</code>```

And this is the output:

```<code>PHP Fatal error:
Uncaught Error: Call to undefined method App\Exceptions\Handler::getOutput() in ...\Handler.php:89
</code>```

I've seen that the output property exists but it is protected and has no getter.
Maybe the cited answer is valid for earlier versions.
I'm really lost as I just have 2 months playing with Laravel.

答:
The Exception handler has a specific method for the console: renderForConsole().

/**
 * Render an exception to the console.
 *
 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
 * @param  \Exception  $e
 * @return void
 */
public function renderForConsole($output, Exception $e)
{
    (new ConsoleApplication)->renderException($e, $output);
}
```

It's a pretty simple wrapper around the Symfony Console component's default exception handler. Customize to your needs!

Body:
I'm trying to get the verbosity level INSIDE the Exception Handler class so I can print more or less information.

I'm writing a batch script that runs over hundreds of thousands loops and so that my goal is to limit the verbosity of the stack trace, since in this case the only useful traces are the last 3 or 4.

I've tried some other answers given here in SO and have read all around Internet, but none of ther talk about working inside the exception handler.
The one that looks closer is this answer that states $this->getOutput()->getVerbosity();but that doesn't works inside the error handler.

This is my code:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Mail;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use App\Mail\ExceptionOccured;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Output\OutputInterface;

class Handler extends ExceptionHandler
...
...
public function render($request, Exception $e)
    {
        // return parent::render($request, $e);
        Log::error($this->buildMessage($e));
    }

    public function buildMessage($e)
    {
        $verbosity_level = $this->getOutput()->getVerbosity();
        $is_verbose = ($verbosity_level >= OutputInterface::VERBOSITY_DEBUG);

        $t0 = $e->getTrace()[0];
        $tm = "Error: [{$e->getCode()}] {$e->getMessage()} @ {$t0['file']}:{$t0['line']}".PHP_EOL;
        // if ($is_verbose){
            ...(more code) ...
        // }
        return $tm;
    }
}

And this is the output:

PHP Fatal error:
Uncaught Error: Call to undefined method App\Exceptions\Handler::getOutput() in ...\Handler.php:89

I've seen that the output property exists but it is protected and has no getter.
Maybe the cited answer is valid for earlier versions.
I'm really lost as I just have 2 months playing with Laravel.

Body:
The Exception handler has a specific method for the console: renderForConsole().

/**
 * Render an exception to the console.
 *
 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
 * @param  \Exception  $e
 * @return void
 */
public function renderForConsole($output, Exception $e)
{
    (new ConsoleApplication)->renderException($e, $output);
}

It's a pretty simple wrapper around the Symfony Console component's default exception handler. Customize to your needs!


答:
Quick recap:  The conflicts occurred while Git was trying to copy an existing commit whose subject line is:

```<code>RM debugger
</code>```

That is, during git rebase, which works by copying some series of commits to new-and-improved commits that do the same thing as the originals except for some improvement (e.g., being on a different starting base commit), Git tried to copy that commit, and got some merge conflicts.  So rebase stopped with RM debugger not yet applied.

You then did some work in your index-and-work-tree to resolve these conflicts, including git add at the end.  Then you ran git rebase --continue.

This message:

```<code>$ git rebase --continue
Applying: RM debugger
No changes - did you forget to use git add?
</code>```

does not mean there are conflicts.  It means that the source code in your index now, ready to be committed as the new-and-improved copy of RM debugger, is exactly the same as the source code in your existing commit dc04ac4 (improve warning), which itself is a copy of some older commit whose subject was already improve warning.

Git dislikes making commits that repeat the same source code.  (Git calls these empty commits, although they're not empty at all, they're just immediate repeats.)  It dislikes this so much that git rebase refuses to do it at all by default, including after you have resolved any conflicts.

This is sometimes a sign that you resolved the conflict the wrong way: that you accidentally dropped your change.  But maybe that is the right thing to do.

If the correct thing to do at this point is to drop the original commit entirely—if there's no change needed now because the new base for the new and improved commits doesn't need any fixing—just run:

```<code>git rebase --skip
</code>```

to tell Git: This commit shouldn't be copied after all.

If you really want the empty commit, you can manually commit it yourself, using git commit --allow-empty, then use git rebase --continue to proceed.

Title: git rebase --continue still sees conflicts, git status tells me there are none

Body:
Quick recap:  The conflicts occurred while Git was trying to copy an existing commit whose subject line is:

RM debugger

That is, during git rebase, which works by copying some series of commits to new-and-improved commits that do the same thing as the originals except for some improvement (e.g., being on a different starting base commit), Git tried to copy that commit, and got some merge conflicts.  So rebase stopped with RM debugger not yet applied.

You then did some work in your index-and-work-tree to resolve these conflicts, including git add at the end.  Then you ran git rebase --continue.

This message:

$ git rebase --continue
Applying: RM debugger
No changes - did you forget to use git add?

does not mean there are conflicts.  It means that the source code in your index now, ready to be committed as the new-and-improved copy of RM debugger, is exactly the same as the source code in your existing commit dc04ac4 (improve warning), which itself is a copy of some older commit whose subject was already improve warning.

Git dislikes making commits that repeat the same source code.  (Git calls these empty commits, although they're not empty at all, they're just immediate repeats.)  It dislikes this so much that git rebase refuses to do it at all by default, including after you have resolved any conflicts.

This is sometimes a sign that you resolved the conflict the wrong way: that you accidentally dropped your change.  But maybe that is the right thing to do.

If the correct thing to do at this point is to drop the original commit entirely—if there's no change needed now because the new base for the new and improved commits doesn't need any fixing—just run:

git rebase --skip

to tell Git: This commit shouldn't be copied after all.

If you really want the empty commit, you can manually commit it yourself, using git commit --allow-empty, then use git rebase --continue to proceed.


问:
Sum of two queries
My table looks like this:

I made two queries:

```<code>SELECT COUNT(column_1) AS result_1 FROM table WHERE column_1= 5;
SELECT COUNT(column_2) AS result_2 FROM table WHERE column_2 = 5;
</code>```

The first query gives me result_1 = 2, and the second result_2 = 3

I need to make a query that will give me the sum of these two (2+3=5).
I always get two results or just one of them.

答:
You can use subqueries:

SELECT sub1.result_1 + sub2.result_2 FROM (
SELECT COUNT(column_1) AS result_1 FROM table WHERE column_1 = 5) as sub1, (
SELECT COUNT(column_2) AS result_2 FROM table WHERE column_2 = 5) as sub2
```

Title: Sum of two queries

Body:
My table looks like this:

I made two queries:

SELECT COUNT(column_1) AS result_1 FROM table WHERE column_1= 5;
SELECT COUNT(column_2) AS result_2 FROM table WHERE column_2 = 5;

The first query gives me result_1 = 2, and the second result_2 = 3

I need to make a query that will give me the sum of these two (2+3=5).
I always get two results or just one of them.


问:
for loop not executing after assigning pointer to NULL in main()
I wrote this C code from a pointers practice video and the problem I am having is that after integrating head as a local main variable over a global variable declared before main(), the program is no longer entering the for loop and I can't seem to figure out why.
The interesting part is that I delete the head=NULL, the loop seems to be executing. Does anyone know where the problem with assigning NULL to head is?

Here is my code:

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

struct Node{
    int data;
    struct Node* next;
};

struct Node* Insert(struct Node* head, int data){
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    (*new_node).data = data;
    (*new_node).next = head;

    head = new_node;
}

void Print(struct Node* head){
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp = head;

    while(temp!=NULL){
        printf("%d", (*temp).data);
        temp = (*temp).next;
    }

    printf("\n");
}

int main(){
    struct Node* head = NULL;

    int n, i, x;
    printf("%s", "How large do you want your array to be?\n");
    scanf("%d", &n);

    for(i; i<n; i++){
        printf("Enter a number:\n");
        scanf("%d",&x);
        head = Insert(head, x);
        Print(head);
    }
    return 0;
}
</code>```

答:
I can see a couple of problems with your code:

```<code>struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp = head;
</code>```

should be

```<code>struct Node* temp = head;
</code>```

Then we have

```<code>for(i; i<n; i++)
</code>```

that should be

```<code>for(i=0; i<n; i++)
</code>```

This can be the cause of your problem, since this is undefined behavior.

Another thing that can cause trouble is that you don't do return head as a final statement in Insert.

Two of these could be easily discovered by turning on compiler warnings.

Also, don't cast malloc

Body:
I wrote this C code from a pointers practice video and the problem I am having is that after integrating head as a local main variable over a global variable declared before main(), the program is no longer entering the for loop and I can't seem to figure out why.
The interesting part is that I delete the head=NULL, the loop seems to be executing. Does anyone know where the problem with assigning NULL to head is?

Here is my code:

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

struct Node{
    int data;
    struct Node* next;
};

struct Node* Insert(struct Node* head, int data){
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    (*new_node).data = data;
    (*new_node).next = head;

    head = new_node;
}

void Print(struct Node* head){
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp = head;

    while(temp!=NULL){
        printf("%d", (*temp).data);
        temp = (*temp).next;
    }

    printf("\n");
}

int main(){
    struct Node* head = NULL;

    int n, i, x;
    printf("%s", "How large do you want your array to be?\n");
    scanf("%d", &n);

    for(i; i<n; i++){
        printf("Enter a number:\n");
        scanf("%d",&x);
        head = Insert(head, x);
        Print(head);
    }
    return 0;
}

Body:
I can see a couple of problems with your code:

struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp = head;

should be

struct Node* temp = head;

Then we have

for(i; i<n; i++)

that should be

for(i=0; i<n; i++)

This can be the cause of your problem, since this is undefined behavior.

Another thing that can cause trouble is that you don't do return head as a final statement in Insert.

Two of these could be easily discovered by turning on compiler warnings.

Also, don't cast malloc