问:
sudo: command not found when I ssh into server
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

```<code>-bash: sudo: command not found
</code>```

I desperately need some deliberate help

答:
try to install your sudo using by first logging in as a root(su - ) and then try to install **apt-get or yum sudo **. Make sure your path variable is set so that you would be able to get binary.

which sudo

echo $PATH

Body:
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

-bash: sudo: command not found

I desperately need some deliberate help


来源: stackexchange

问:
PHP POST variables missing value when form submission is made from Chrome on a mac
I have a php form in a website checkout section that sends an email after the checkout process, and also saves the order in the database. Values entered in one field of the form, which is a text area for comments/instructions, is losing the value entered on submitting the form. The order is being saved correctly, but this field is blank, even if value is entered.
This is happening only in Chrome, and works perfect on Firefox.
Any inputs on what could be happening plz .. </p>

答:
We need a specific example of your problem.  As written, your question gives us no starting point.  We need an example of the form element and afflicted sub elements.  We also need to know what versions of Chrome, Firefox, and what platform you are working on.

Alternatively, you might consider dropping print_r($_POST); echo "
"; in as the first output when you process the form.  Do it before everything, even your session setup (expect an error to be generated.  Session hates being second.).  If the value is empty here, there is a problem with either how you've constructed the HTML (which is why we need to see it) or with the version of Chrome you're using (which is very unlikely).

If you find that first print_r displays the correct value, you need to move it inch-by-inch along your code path until you discover where the value is lost.

ContentLicense: CC BY-SA 3.0

Body:
We need a specific example of your problem.  As written, your question gives us no starting point.  We need an example of the form element and afflicted sub elements.  We also need to know what versions of Chrome, Firefox, and what platform you are working on.

Alternatively, you might consider dropping print_r($_POST); echo "<p>"; in as the first output when you process the form.  Do it before everything, even your session setup (expect an error to be generated.  Session hates being second.).  If the value is empty here, there is a problem with either how you've constructed the HTML (which is why we need to see it) or with the version of Chrome you're using (which is very unlikely).

If you find that first print_r displays the correct value, you need to move it inch-by-inch along your code path until you discover where the value is lost.


问:
PHP & MySQL - Deleting users problem
For some reason if a user does not have data in the info or pid MySQL tables I can't delete the user form any other table like the user table is there some way I can have the user
deleted even if the user has not entered data into the other tables except the user table?

Here is part of the code for deleting members.

```<code>    if(($months >= 3) && ($row['deletion'] == 1)){

        $dqc = mysqli_query($mysqli,"DELETE FROM info WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dqc){ print mysqli_error($mysqli); }

        $dpq = mysqli_query($mysqli,"DELETE FROM pid WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dpq){ print mysqli_error($mysqli); }

        $duq = mysqli_query($mysqli,"DELETE FROM users WHERE user_id = '" . $row['user_id'] . "'");
        if(!$duq){ print mysqli_error($mysqli); }
    }
</code>```

答: Sounds like you may have some dependency issues regarding foreign key constraints. What are the relationships like between the user, info and pid tables? Depending on the relationships you may want to re-order your delete statements.</p>

ContentLicense: CC BY-SA 2.5

Title: PHP & MySQL - Deleting users problem

Body:
For some reason if a user does not have data in the info or pid MySQL tables I can't delete the user form any other table like the user table is there some way I can have the user
deleted even if the user has not entered data into the other tables except the user table?

Here is part of the code for deleting members.

    if(($months >= 3) && ($row['deletion'] == 1)){

        $dqc = mysqli_query($mysqli,"DELETE FROM info WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dqc){ print mysqli_error($mysqli); }

        $dpq = mysqli_query($mysqli,"DELETE FROM pid WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dpq){ print mysqli_error($mysqli); }

        $duq = mysqli_query($mysqli,"DELETE FROM users WHERE user_id = '" . $row['user_id'] . "'");
        if(!$duq){ print mysqli_error($mysqli); }
    }


问:
Subsetting by variables within grouped observations R
so if you do this you'll get a data frame similar to what I am working with

```<code>test <- Indometh[Indometh$time %in% c(1.00,3.00,6.00),]
dil <- c(50,500,5000)
test$dilution <- dil
test <- test[-c(3,7,11,17),]
test[14,4] <- 50
test$time <- gsub(1, "run_1", test$time)
test$time <- gsub(3, "run_3", test$time)
test$time <- gsub(6, "run_6", test$time)

   Subject  time conc dilution
        1 run_1 0.48       50
        1 run_3 0.12      500
        2 run_1 0.70       50
        2 run_3 0.32      500
        2 run_6 0.12     5000
        3 run_3 0.22      500
        3 run_6 0.08     5000
        4 run_1 0.89       50
        4 run_6 0.07     5000
        5 run_1 0.39       50
        5 run_3 0.13      500
        5 run_6 0.10     5000
        6 run_1 0.84       50
        6 run_6 0.10       50
</code>```

What I need to do is apply the following logic.

For each subject, if the dilution is 50 and there is any other dilution, keep the other dilutions.

If the dilution is 50 and there is only other dilution 50 available then keep all the dilution 50's for that subject.

so my resulting data frame should look like:

```<code>testres <- test[-c(1,3,8,10),]

 Subject  time conc dilution
       1 run_3 0.12      500
       2 run_3 0.32      500
       2 run_6 0.12     5000
       3 run_3 0.22      500
       3 run_6 0.08     5000
       4 run_6 0.07     5000
       5 run_3 0.13      500
       5 run_6 0.10     5000
       6 run_1 0.84       50
       6 run_6 0.10       50
</code>```

Thanks

PS: It was hard wording this question, any recommendations for how I could of titled this question better?

答:
Here is a solution using dplyr.

```<code>library(dplyr)

# Group the data frame by Subject
test2 <- test %>% group_by(Subject)

# Filter Subjects with all dilution == 50
test3 <- test2 %>% filter(all(dilution == 50))

# Filter out other records with dilution == 50
test4 <- test2 %>%
  filter(!all(dilution == 50)) %>%
  filter(dilution != 50)

# Combine the data frames
test_final <- test3 %>%
  bind_rows(test4) %>%
  ungroup() %>%
  mutate(Subject = as.numeric(as.character(Subject))) %>%
  arrange(Subject)
</code>```

Body:
so if you do this you'll get a data frame similar to what I am working with

test <- Indometh[Indometh$time %in% c(1.00,3.00,6.00),]
dil <- c(50,500,5000)
test$dilution <- dil
test <- test[-c(3,7,11,17),]
test[14,4] <- 50
test$time <- gsub(1, "run_1", test$time)
test$time <- gsub(3, "run_3", test$time)
test$time <- gsub(6, "run_6", test$time)

   Subject  time conc dilution
        1 run_1 0.48       50
        1 run_3 0.12      500
        2 run_1 0.70       50
        2 run_3 0.32      500
        2 run_6 0.12     5000
        3 run_3 0.22      500
        3 run_6 0.08     5000
        4 run_1 0.89       50
        4 run_6 0.07     5000
        5 run_1 0.39       50
        5 run_3 0.13      500
        5 run_6 0.10     5000
        6 run_1 0.84       50
        6 run_6 0.10       50

What I need to do is apply the following logic.

For each subject, if the dilution is 50 and there is any other dilution, keep the other dilutions.

If the dilution is 50 and there is only other dilution 50 available then keep all the dilution 50's for that subject.

so my resulting data frame should look like:

testres <- test[-c(1,3,8,10),]

 Subject  time conc dilution
       1 run_3 0.12      500
       2 run_3 0.32      500
       2 run_6 0.12     5000
       3 run_3 0.22      500
       3 run_6 0.08     5000
       4 run_6 0.07     5000
       5 run_3 0.13      500
       5 run_6 0.10     5000
       6 run_1 0.84       50
       6 run_6 0.10       50

Thanks

PS: It was hard wording this question, any recommendations for how I could of titled this question better?

Body:
Here is a solution using dplyr.

library(dplyr)

# Group the data frame by Subject
test2 <- test %>% group_by(Subject)

# Filter Subjects with all dilution == 50
test3 <- test2 %>% filter(all(dilution == 50))

# Filter out other records with dilution == 50
test4 <- test2 %>%
  filter(!all(dilution == 50)) %>%
  filter(dilution != 50)

# Combine the data frames
test_final <- test3 %>%
  bind_rows(test4) %>%
  ungroup() %>%
  mutate(Subject = as.numeric(as.character(Subject))) %>%
  arrange(Subject)


问:
Illegal string offset Warning PHP
I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

```<code>Array
(
    [host] => 127.0.0.1
    [port] => 11211
)
</code>```

When I try to access it like this I get strange warnings

```<code> print $memcachedConfig['host'];
 print $memcachedConfig['port'];

 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...
</code>```

I really don't want to just edit my php.ini and re-set the error level.

答:
In my case, I solved it when I changed in function that does sql query
after: return json_encode($array)
then: return $array

ContentLicense: CC BY-SA 4.0

Title: Illegal string offset Warning PHP

Body:
I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

When I try to access it like this I get strange warnings

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];

 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

I really don't want to just edit my php.ini and re-set the error level.


问:
How to shape a nested struct into another without nested loops?
How can I inject A and B's selected values into children C below?

decoder.go (Playground link)

```<code>package main

import (
    "fmt"
)

type Input struct {
    A []A
}

type A struct {
    AID int
    B []B
}

type B struct {
    BID int
    C []C
}

type C struct {
    // I want to inject only AID and BID here
    // But, without injecting A and B directly
    //   (without recursively)
    CID int
}

func main() {
    res := Input{
        A: []A {
            A {
                AID: 1,
                B: []B {
                    B{ BID: 11, C: []C{{ 111 }, { 111 }}},
                    B{ BID: 12, C: []C{{ 121 }, { 122 }}},
                },
            },
            A {
                AID: 2,
                B: []B {
                    B{ BID: 21, C: []C{{ 211 }, { 211 }}},
                    B{ BID: 22, C: []C{{ 221 }, { 222 }}},
                },
            },
        },
    }

    // I want to inject AID and BID into C
    // WITHOUT nested loops like this:
    for _, a := range res.A {
        for _, b := range a.B {
            for _, c := range b.C {
                fmt.Println(a.AID, b.BID, c.CID)
            }
        }
    }
}
</code>```

答:
If you don't want to use nested loop, one solution is using recursive call and reflection to inject the attributes/properties into a struct. In the following implementation, attributes/properties to be injected is wrapped in a struct implement Injectable interface. Working example can be found at Go Playground.

Define the interface.

```<code>type Injectable interface {
    InjectTo(v interface{})
}
</code>```

Define data structure that holds properties/attributes to be injected, e.g.

```<code>type Property struct {
    AID int
    BID int
}

type C struct {
    // The properties will be injected here
    Property
    CID int
}
</code>```

Implement InjectTo using reflection and recursive call.

```<code>//Method must be pointer receiver since p will be used
//as temporary placeholder for parent properties/attributes.
func (p *Property) injectRecursive(v reflect.Value, it reflect.Type, pv reflect.Value) {
    switch v.Kind() {
    case reflect.Struct:
        vt := v.Type()
        //Embedded struct is a 'value' type implement Injectable
        if vt.Implements(it) {
            //Inject value to embedded struct
            ot := pv.Type()
            for k := 0; k < pv.NumField(); k++ {
                name := ot.Field(k).Name
                f := v.FieldByName(name)
                if f.CanSet() {
                    f.Set(pv.Field(k))
                }
            }
        } else {
            for k := 0; k < v.NumField(); k++ {
                fv := v.Field(k)

                //Match by field name.
                //For more robust and generic solution
                //consider using other approach, e.g. tag
                f := pv.FieldByName(vt.Field(k).Name)
                if f.CanSet() {
                    f.Set(fv)
                } else {
                    p.injectRecursive(fv, it, pv)
                }
            }
        }
    case reflect.Slice, reflect.Array:
        for k := 0; k < v.Len(); k++ {
            p.injectRecursive(v.Index(k), it, pv)
        }
    case reflect.Ptr:
        if v.IsValid() {
            p.injectRecursive(v.Elem(), it, pv)
        }
    }
}

//InjectTo must be Value (not pointer) receiver
func (p Property) InjectTo(s interface{}) {
    sv := reflect.Indirect(reflect.ValueOf(s))
    pv := reflect.Indirect(reflect.ValueOf(&p))
    it := reflect.TypeOf((*Injectable)(nil)).Elem()
    p.injectRecursive(sv, it, pv)
}
</code>```

You can inject the properties by:

```<code>res := Input{...}
prop := Property{}
prop.InjectTo(&res)
</code>```

Body:
How can I inject A and B's selected values into children C below?

decoder.go (Playground link)

package main

import (
    "fmt"
)

type Input struct {
    A []A
}

type A struct {
    AID int
    B []B
}

type B struct {
    BID int
    C []C
}

type C struct {
    // I want to inject only AID and BID here
    // But, without injecting A and B directly
    //   (without recursively)
    CID int
}

func main() {
    res := Input{
        A: []A {
            A {
                AID: 1,
                B: []B {
                    B{ BID: 11, C: []C{{ 111 }, { 111 }}},
                    B{ BID: 12, C: []C{{ 121 }, { 122 }}},
                },
            },
            A {
                AID: 2,
                B: []B {
                    B{ BID: 21, C: []C{{ 211 }, { 211 }}},
                    B{ BID: 22, C: []C{{ 221 }, { 222 }}},
                },
            },
        },
    }

    // I want to inject AID and BID into C
    // WITHOUT nested loops like this:
    for _, a := range res.A {
        for _, b := range a.B {
            for _, c := range b.C {
                fmt.Println(a.AID, b.BID, c.CID)
            }
        }
    }
}

Body:
If you don't want to use nested loop, one solution is using recursive call and reflection to inject the attributes/properties into a struct. In the following implementation, attributes/properties to be injected is wrapped in a struct implement Injectable interface. Working example can be found at Go Playground.

Define the interface.

type Injectable interface {
    InjectTo(v interface{})
}

Define data structure that holds properties/attributes to be injected, e.g.

type Property struct {
    AID int
    BID int
}

type C struct {
    // The properties will be injected here
    Property
    CID int
}

Implement InjectTo using reflection and recursive call.

//Method must be pointer receiver since p will be used
//as temporary placeholder for parent properties/attributes.
func (p *Property) injectRecursive(v reflect.Value, it reflect.Type, pv reflect.Value) {
    switch v.Kind() {
    case reflect.Struct:
        vt := v.Type()
        //Embedded struct is a 'value' type implement Injectable
        if vt.Implements(it) {
            //Inject value to embedded struct
            ot := pv.Type()
            for k := 0; k < pv.NumField(); k++ {
                name := ot.Field(k).Name
                f := v.FieldByName(name)
                if f.CanSet() {
                    f.Set(pv.Field(k))
                }
            }
        } else {
            for k := 0; k < v.NumField(); k++ {
                fv := v.Field(k)

                //Match by field name.
                //For more robust and generic solution
                //consider using other approach, e.g. tag
                f := pv.FieldByName(vt.Field(k).Name)
                if f.CanSet() {
                    f.Set(fv)
                } else {
                    p.injectRecursive(fv, it, pv)
                }
            }
        }
    case reflect.Slice, reflect.Array:
        for k := 0; k < v.Len(); k++ {
            p.injectRecursive(v.Index(k), it, pv)
        }
    case reflect.Ptr:
        if v.IsValid() {
            p.injectRecursive(v.Elem(), it, pv)
        }
    }
}

//InjectTo must be Value (not pointer) receiver
func (p Property) InjectTo(s interface{}) {
    sv := reflect.Indirect(reflect.ValueOf(s))
    pv := reflect.Indirect(reflect.ValueOf(&p))
    it := reflect.TypeOf((*Injectable)(nil)).Elem()
    p.injectRecursive(sv, it, pv)
}

You can inject the properties by:

res := Input{...}
prop := Property{}
prop.InjectTo(&res)


答:
Using dplyr as well but a bit shorter:

```<code>library(dplyr)
test %>%
    group_by(Subject) %>%
    mutate(all50 = all(dilution == 50)) %>%
    filter((all50 & dilution == 50) | (! all50 & dilution != 50))
</code>```

Output:

```<code># A tibble: 10 x 5
   Subject   time  conc dilution all50
     <int> <fctr> <dbl>    <int> <lgl>
 1       1  run_3  0.12      500 FALSE
 2       2  run_3  0.32      500 FALSE
 3       2  run_6  0.12     5000 FALSE
 4       3  run_3  0.22      500 FALSE
 5       3  run_6  0.08     5000 FALSE
 6       4  run_6  0.07     5000 FALSE
 7       5  run_3  0.13      500 FALSE
 8       5  run_6  0.10     5000 FALSE
 9       6  run_1  0.84       50  TRUE
10       6  run_6  0.10       50  TRUE
</code>```

Title: Subsetting by variables within grouped observations R

Body:
Using dplyr as well but a bit shorter:

library(dplyr)
test %>%
    group_by(Subject) %>%
    mutate(all50 = all(dilution == 50)) %>%
    filter((all50 & dilution == 50) | (! all50 & dilution != 50))

Output:

# A tibble: 10 x 5
   Subject   time  conc dilution all50
     <int> <fctr> <dbl>    <int> <lgl>
 1       1  run_3  0.12      500 FALSE
 2       2  run_3  0.32      500 FALSE
 3       2  run_6  0.12     5000 FALSE
 4       3  run_3  0.22      500 FALSE
 5       3  run_6  0.08     5000 FALSE
 6       4  run_6  0.07     5000 FALSE
 7       5  run_3  0.13      500 FALSE
 8       5  run_6  0.10     5000 FALSE
 9       6  run_1  0.84       50  TRUE
10       6  run_6  0.10       50  TRUE


问:
Extract text between characters, strings or brackets

I have following types of data :

```<code>pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})
</code>```

Expected Output

```<code>pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})
</code>```

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

```<code>for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)
</code>```

答:
You can apply the following expression to your hashtags :

```<code>df['Hashtags'] = sum([x if x else [" "] for x
                      in ast.literal_eval(''.join(df['Hashtags'])\
                                            .replace('][', '],['))],\
                     [])
</code>```

Result:

```<code>[' ', 'AAPHealthCare4All', 'CBI', 'Delhi', 'Emergency']
</code>```

However, the number of rows in the dataframe will change, and the indexes will not be preserved. You may be using dataframes incorrectly.

Body:
I have following types of data :

pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})

Expected Output

pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)

Body:
You can apply the following expression to your hashtags :

df['Hashtags'] = sum([x if x else [" "] for x
                      in ast.literal_eval(''.join(df['Hashtags'])\
                                            .replace('][', '],['))],\
                     [])

Result:

[' ', 'AAPHealthCare4All', 'CBI', 'Delhi', 'Emergency']

However, the number of rows in the dataframe will change, and the indexes will not be preserved. You may be using dataframes incorrectly.


问:
Order of evaluation
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

```<code>struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};
</code>```

If yes I personally would prefer this way to the more conventional:

```<code>    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}
</code>```

答:
If you want to do this, then do it the way everybody understands immediately without having to browse the standard:

```<code>MemoryManager()
  // no initialization here
{
  lastPair_ = currentPair_ = firstPair_ = nullptr;
}
</code>```

However, I don't really see what this buys you over

```<code>MemoryManager()
  : lastPair_(), currentPair_(), firstPair_()
{}
</code>```

which does exactly the same in only about half a dozen more characters.

Title: Order of evaluation

Body:
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};

If yes I personally would prefer this way to the more conventional:

    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}

Body:
If you want to do this, then do it the way everybody understands immediately without having to browse the standard:

MemoryManager()
  // no initialization here
{
  lastPair_ = currentPair_ = firstPair_ = nullptr;
}

However, I don't really see what this buys you over

MemoryManager()
  : lastPair_(), currentPair_(), firstPair_()
{}

which does exactly the same in only about half a dozen more characters.


问:
R wild single character in replace sub
how I can refer to any single character in R>? in my case it would be 3 any chars. I bit overwhelmed with its power, so many help around !) In my case I need to replace any 3 characters in pos 25-27 with "XXX".  I successfully used this code to replace specific chars, tried to use %,* instead of abc with no avail.  Tx much</p>

```<code>d <- c("alpha 1 bravo 0 charlie_abc v3")
sub("^(.{24})abc", "\\1XXX", d)
   [1] "alpha 1 bravo 0 charlie_XXX v3"
</code>```

答:
Here are two ways, using pattern "^(.{24}).{3}" or using substring :

```<code>d <- c("alpha 1 bravo 0 charlie_abc v3")
sub("^(.{24}).{3}", "\\1XXX", d)
#> [1] "alpha 1 bravo 0 charlie_XXX v3"

d <- c("alpha 1 bravo 0 charlie_abc v3")
substring(d, 25, 27) <- "XXX"
d
#> [1] "alpha 1 bravo 0 charlie_XXX v3"
</code>```

Title: R wild single character in replace sub

Body:
how I can refer to any single character in R>? in my case it would be 3 any chars. I bit overwhelmed with its power, so many help around !) In my case I need to replace any 3 characters in pos 25-27 with "XXX".  I successfully used this code to replace specific chars, tried to use %,* instead of abc with no avail.  Tx much

d <- c("alpha 1 bravo 0 charlie_abc v3")
sub("^(.{24})abc", "\\1XXX", d)
   [1] "alpha 1 bravo 0 charlie_XXX v3"

Body:
Here are two ways, using pattern "^(.{24}).{3}" or using substring :

d <- c("alpha 1 bravo 0 charlie_abc v3")
sub("^(.{24}).{3}", "\\1XXX", d)
#> [1] "alpha 1 bravo 0 charlie_XXX v3"

d <- c("alpha 1 bravo 0 charlie_abc v3")
substring(d, 25, 27) <- "XXX"
d
#> [1] "alpha 1 bravo 0 charlie_XXX v3"


问:
Laravel pass variable from controller query to model function
I have a function on my model that check active status in equipment_station table,

originally it only checked one status, now i need to pass a parameter to the model with active or inactive values, I've tried this with no success.

controller:

model :

How can i change the parameter in the model, I send status from controller as inactive or active.

thanks in advance

答:
You could you query scope

```<code>public function scopeActive($query, $active)
{
   return $query->where('active', $active);
}
</code>```

then you can call it in your model

```<code>Estacion::active(true)->get();
</code>```

Body:
You could you query scope

public function scopeActive($query, $active)
{
   return $query->where('active', $active);
}

then you can call it in your model

Estacion::active(true)->get();


问:
Golang docker library image cannot find go tool in $PATH
I opened an issue on docker-library/golang#164, because I think this is a bug. However, I thought I'd also ask on StackOverflow to see if anyone else (besides project contributors) have encountered this or have any ideas?

First things first, the version numbers:

```<code>$ docker version
Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Fri Mar 24 00:00:50 2017
 OS/Arch:      linux/amd64
 Experimental: true

$ docker-compose version
docker-compose version 1.11.2, build dfed245
docker-py version: 2.1.0
CPython version: 2.7.12
OpenSSL version: OpenSSL 1.0.2j  26 Sep 2016
</code>```

I'm getting the following error:

```<code>Cannot start service web: oci runtime error: container_linux.go:247: starting container process caused "exec: \"go\": executable file not found in $PATH"
</code>```

And this is my Dockerfile:

```<code>FROM golang:1.8

WORKDIR /go/src/gigem
COPY . /go/src/gigem

RUN go build
RUN go install

CMD ["gigem"]
</code>```

I'm also using Compose (and I'll include the yml, but the error occurs with/without compose):

```<code>version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./data:/var/lib/postgresql/data
  web:
    build: .
    volumes:
      - .:/go/src/gigem
    ports:
      - "3000:3000"
    depends_on:
      - db
</code>```

And all that's in my Go program is:

```<code>package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Docker!")
  })

  fmt.Println("Running!")
  fmt.Println(http.ListenAndServe("0.0.0.0:3000", nil))
}
</code>```

I'm not quite sure why go is not being found in the $PATH.

答:
I recently tested your Dockerfile and main.go, and I did not find any errors.

I think you should try to pull golang: 1.8 again usingdocker build --pull .

I modified your Dockerfile adding two new lines to debug the image, try:

```<code>FROM golang: 1.8

WORKDIR / go / src / gigem
COPY. / Go / src / gigem

RUN echo $ PATH
RUN which go
RUN go build
RUN go install

CMD ["gigem"]
</code>```

Echo $ PATH andwhich go will show you if the binary go is inside the PATH

Body:
I opened an issue on docker-library/golang#164, because I think this is a bug. However, I thought I'd also ask on StackOverflow to see if anyone else (besides project contributors) have encountered this or have any ideas?

First things first, the version numbers:

$ docker version
Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Fri Mar 24 00:00:50 2017
 OS/Arch:      linux/amd64
 Experimental: true

$ docker-compose version
docker-compose version 1.11.2, build dfed245
docker-py version: 2.1.0
CPython version: 2.7.12
OpenSSL version: OpenSSL 1.0.2j  26 Sep 2016

I'm getting the following error:

Cannot start service web: oci runtime error: container_linux.go:247: starting container process caused "exec: \"go\": executable file not found in $PATH"

And this is my Dockerfile:

FROM golang:1.8

WORKDIR /go/src/gigem
COPY . /go/src/gigem

RUN go build
RUN go install

CMD ["gigem"]

I'm also using Compose (and I'll include the yml, but the error occurs with/without compose):

version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./data:/var/lib/postgresql/data
  web:
    build: .
    volumes:
      - .:/go/src/gigem
    ports:
      - "3000:3000"
    depends_on:
      - db

And all that's in my Go program is:

package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Docker!")
  })

  fmt.Println("Running!")
  fmt.Println(http.ListenAndServe("0.0.0.0:3000", nil))
}

I'm not quite sure why go is not being found in the $PATH.

Body:
I recently tested your Dockerfile and main.go, and I did not find any errors.

I think you should try to pull golang: 1.8 again usingdocker build --pull .

I modified your Dockerfile adding two new lines to debug the image, try:

FROM golang: 1.8

WORKDIR / go / src / gigem
COPY. / Go / src / gigem

RUN echo $ PATH
RUN which go
RUN go build
RUN go install

CMD ["gigem"]

Echo $ PATH andwhich go will show you if the binary go is inside the PATH


问:
How I could replace and array element by array index in ruby?
I have an array like this I use

```<code>       inputx.scan(/.*?\n/)
</code>```

for create array this is a representation of my array

```<code>      element 1 => [car;dog;soda]
       element 2 => [bunny;pc;laptop]
   element 3  => [hand;sword;shield]
</code>```

this is my text file I use scan  method for create array      inputx.scan(/.*?\n/)

```<code>     car;dog;soda

       bunny;pc;laptop

     hand;sword;shield
</code>```

I need to replace each comma by number of array for obtain this

this is my expected output

in this output I replace ";" by "nthelementnumber;" example 1;

```<code>      car1;dog1;soda

        bunny2;pc2;laptop

       hand3;sword3;shield
</code>```

Please help me

答:
It's a bit hard to tell what exactly your array looks like, but I'm going to take a guess:

```<code>element = ['car;dog;soda',
           'bunny;pc;laptop',
           'hand;sword;shield']
</code>```

If that's correct, you can get  the output you are looking for with something like:

```<code>element.each_index {|i| element[i] = element[i].gsub(';', "#{i+1};")}
</code>```

The each_index iterator gives you each index (unsurprisingly). Then you can use each index to manipulate each value in the array.

Body:
I have an array like this I use

       inputx.scan(/.*?\n/)

for create array this is a representation of my array

      element 1 => [car;dog;soda]
       element 2 => [bunny;pc;laptop]
   element 3  => [hand;sword;shield]

this is my text file I use scan  method for create array      inputx.scan(/.*?\n/)

     car;dog;soda

       bunny;pc;laptop

     hand;sword;shield

I need to replace each comma by number of array for obtain this

this is my expected output

in this output I replace ";" by "nthelementnumber;" example 1;

      car1;dog1;soda

        bunny2;pc2;laptop

       hand3;sword3;shield

Please help me

Body:
It's a bit hard to tell what exactly your array looks like, but I'm going to take a guess:

element = ['car;dog;soda',
           'bunny;pc;laptop',
           'hand;sword;shield']

If that's correct, you can get  the output you are looking for with something like:

element.each_index {|i| element[i] = element[i].gsub(';', "#{i+1};")}

The each_index iterator gives you each index (unsurprisingly). Then you can use each index to manipulate each value in the array.


问:
CSS and IE8: How can I get the CSS color property to work consistently on submit inputs in IE8?
I am using an input type='submit' with CSS rules applied that make the background a gradated dark blue and the font color white. I cannot get this input to render consistently in IE 8. In some parts of my site, it looks just fine, with its lovely white type. In other parts, the color assigned to the body trumps the white applied by the CSS rules.

I've done a fair bit of research on this and can't find a solution that works. The one I did find on CSS Tricks recommended adding the css using jQuery. I tried this. I successfully added an inline style, but IE8 still trumped my white. I've switched in and out of Compatibility View, still no dice. 0

Why?

Here is the pertinent markup and CSS.

CSS

```<code>body {
    color:#222;
    font-size: 12px;
    width:100%;
    background:#8A7967 url(images/bg_body.png) top left repeat-x;
}

.buttonBigBlue,
input[type="submit"] {
  color:#FFF!important;
  -webkit-border-radius:12px;
  -moz-border-radius: 12px;
  border-radius:12px;
  padding:3px 9px;
  text-transform:uppercase;
  font-weight:bold;
  text-align:center;
  vertical-align:middle;
  border:1px solid #74a1a9;
  cursor:pointer;
  background: #678382; /* for non-css3 browsers */
  background:-webkit-gradient(linear, left top, left bottom, from(#77A7B1), to(#678382));
  background:-moz-linear-gradient(top,  #77A7B1,  #678382);
  filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382'); /* IE6,IE7 */
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382')"; /* IE8 */
}
</code>```

MARKUP

```<code><input type="submit" class="buttonBigBlue" id="login" value="Login" name="login">
</code>```

This button displays with #222 text in IE8.

```<code><input type="submit" class="buttonBigBlue" id="saveChanges" value="Save Changes" name="saveChanges">
</code>```

This button displays with #FFF text in IE8

UPDATE after further investigation.

The containing div for the inputs that won't display properly is called #loginBox. It's styles are these:

```
#loginBox {
    width:300px;
    margin:25px auto;
    padding: 25px 30px 30px;
    border:1px solid #c9b9a8;
    -webkit-border-radius:9px;
    -moz-border-radius: 9px;
    border-radius:9px 9px 9px 9px;
    -webkit-box-shadow:rgba(0,0,0,.3) 4px 4px 6px;
    -moz-box-shadow: 4px 4px 6px rgba(0,0,0,.3);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845')";
    /* For IE 5.5 - 7*/
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845');
    min-height:160px;
    background-color:#fff;
    box-shadow: 4px 4px 6px rgba(0,0,0,.3);
}
```

When I remove the -ms-filter and filter rules that set the box shadow, the input text returns to white.

答: Revise your CSS, you likely have some CSS rule that overrides this. Your sippet works perfectly standalone.

Body:
I am using an input type='submit' with CSS rules applied that make the background a gradated dark blue and the font color white. I cannot get this input to render consistently in IE 8. In some parts of my site, it looks just fine, with its lovely white type. In other parts, the color assigned to the body trumps the white applied by the CSS rules.

I've done a fair bit of research on this and can't find a solution that works. The one I did find on CSS Tricks recommended adding the css using jQuery. I tried this. I successfully added an inline style, but IE8 still trumped my white. I've switched in and out of Compatibility View, still no dice. 0

Why?

Here is the pertinent markup and CSS.

CSS

body {
    color:#222;
    font-size: 12px;
    width:100%;
    background:#8A7967 url(images/bg_body.png) top left repeat-x;
}

.buttonBigBlue,
input[type="submit"] {
  color:#FFF!important;
  -webkit-border-radius:12px;
  -moz-border-radius: 12px;
  border-radius:12px;
  padding:3px 9px;
  text-transform:uppercase;
  font-weight:bold;
  text-align:center;
  vertical-align:middle;
  border:1px solid #74a1a9;
  cursor:pointer;
  background: #678382; /* for non-css3 browsers */
  background:-webkit-gradient(linear, left top, left bottom, from(#77A7B1), to(#678382));
  background:-moz-linear-gradient(top,  #77A7B1,  #678382);
  filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382'); /* IE6,IE7 */
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382')"; /* IE8 */
}

MARKUP

<input type="submit" class="buttonBigBlue" id="login" value="Login" name="login">

This button displays with #222 text in IE8.

<input type="submit" class="buttonBigBlue" id="saveChanges" value="Save Changes" name="saveChanges">

This button displays with #FFF text in IE8

UPDATE after further investigation.

The containing div for the inputs that won't display properly is called #loginBox. It's styles are these:

#loginBox {
    width:300px;
    margin:25px auto;
    padding: 25px 30px 30px;
    border:1px solid #c9b9a8;
    -webkit-border-radius:9px;
    -moz-border-radius: 9px;
    border-radius:9px 9px 9px 9px;
    -webkit-box-shadow:rgba(0,0,0,.3) 4px 4px 6px;
    -moz-box-shadow: 4px 4px 6px rgba(0,0,0,.3);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845')";
    /* For IE 5.5 - 7*/
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845');
    min-height:160px;
    background-color:#fff;
    box-shadow: 4px 4px 6px rgba(0,0,0,.3);
}

When I remove the -ms-filter and filter rules that set the box shadow, the input text returns to white.


问:
How to make the java wait for x seconds and then execute
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

```<code>package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}
</code>```

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

答:
Just put method into your button click function

```<code>public void buttonOnClick(View v) {
      //call method here
}
</code>```

If you want to use RxJava

```<code>Disposable di = Observable.timer(2, TimeUnit.SECONDS)
   .subscribe(timer->{
        //next action after 2 seconds
   },throwable->{
       // throw exception
   });
</code>```

To destroy disposable use, di.dispose();

if Use Runnable and Handler

```<code>Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
         //next action after 2 seconds
    }
}, 2*1000);
</code>```

to stop the handler use, handler.removeCallbacksAndMessages(null);

Body:
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

Body:
Just put method into your button click function

public void buttonOnClick(View v) {
      //call method here
}

If you want to use RxJava

Disposable di = Observable.timer(2, TimeUnit.SECONDS)
   .subscribe(timer->{
        //next action after 2 seconds
   },throwable->{
       // throw exception
   });

To destroy disposable use, di.dispose();

if Use Runnable and Handler

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
         //next action after 2 seconds
    }
}, 2*1000);

to stop the handler use, handler.removeCallbacksAndMessages(null);


问:
Simple MVC Timer- Swift
I know this is a super basic question, I am trying to refactor my code atm and am running into trouble with the timer. All I am trying to do is just get a simple countdown timer to print to the console

Here is my code snippet right now

VC------

```<code>var seconds = 60

override func viewDidLoad() {
    super.viewDidLoad()
    self.modelInstance.gameTimerMethod(timeParam: self.seconds)
}
</code>```

MODEL-----

```<code>func gameTimerMethod(timeParam : Int)  {
    gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(secondsParam:)), userInfo: timeParam, repeats: true)
    print (timeParam)
}

func decreaseGameTimer(secondsParam: Int) {
    var printNumber = secondsParam
    printNumber -= 1
    print (printNumber)
}
</code>```

Ideally what I want this to do in the console is simply countdown from 60 for now at a rate of one number per second. Although the console is logging at a rate of one number per second, it is for some reason repeatedly logging the number 105553117734207, instead of a 60 seconds countdown.

Thanks!

答:
The value passed to decreaseGameTimer is the Timer instance.  It has a property userInfo that has a reference to the object passed to the Timer constructor.

Create a class to hold your count, and then pass an instance of that class to the timer's userInfo:

```<code>class Model {

    class TimerInfo {
        var count: Int

        // Pointer to function or closure to call when value changes
        var callback: ((Int) -> Void)?

        init(start: Int, callback: @escaping (Int) -> Void) {
            count = start
            self.callback = callback
        }

        deinit {
            print("TimerInfo deinit")
        }
    }

    @objc func decreaseGameTimer(_ timer: Timer) {
        if let userInfo = timer.userInfo as? TimerInfo {
            userInfo.count -= 1

            // call callback with new value
            userInfo.callback?(userInfo.count)

            print(userInfo.count)
            if userInfo.count == 0 {
                print("done")
                timer.invalidate()
            }
        }
    }

    func gameTimerMethod(timeParam: Int, callback: @escaping (Int) -> Void) {
        _ = Timer.scheduledTimer(timeInterval: 1, target: self,
                                 selector: #selector(decreaseGameTimer),
                                 userInfo: TimerInfo(start: timeParam, callback: callback),
                                 repeats: true)
    }
}
</code>```

Then you'd call it like this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // The closure that follows the gameTimerMethod call is using trailing
    // closure syntax.  It gets passed to gameTimerMethod as the second
    // parameter named callback.  This closure will get called every
    // second until the timer finishes.

    self.modelInstance.gameTimerMethod(timeParam: self.seconds) { value in
        self.label.text = "\(value)"
    }

    // Just for fun, lets run a second one at the same time
    self.modelInstance.gameTimerMethod(timeParam: 10) { value in
        self.label2.text = "\(value)"
    }
}
</code>```

Title: Simple MVC Timer- Swift

Body:
I know this is a super basic question, I am trying to refactor my code atm and am running into trouble with the timer. All I am trying to do is just get a simple countdown timer to print to the console

Here is my code snippet right now

VC------

var seconds = 60

override func viewDidLoad() {
    super.viewDidLoad()
    self.modelInstance.gameTimerMethod(timeParam: self.seconds)
}

MODEL-----

func gameTimerMethod(timeParam : Int)  {
    gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(secondsParam:)), userInfo: timeParam, repeats: true)
    print (timeParam)
}

func decreaseGameTimer(secondsParam: Int) {
    var printNumber = secondsParam
    printNumber -= 1
    print (printNumber)
}

Ideally what I want this to do in the console is simply countdown from 60 for now at a rate of one number per second. Although the console is logging at a rate of one number per second, it is for some reason repeatedly logging the number 105553117734207, instead of a 60 seconds countdown.

Thanks!

Body:
The value passed to decreaseGameTimer is the Timer instance.  It has a property userInfo that has a reference to the object passed to the Timer constructor.

Create a class to hold your count, and then pass an instance of that class to the timer's userInfo:

class Model {

    class TimerInfo {
        var count: Int

        // Pointer to function or closure to call when value changes
        var callback: ((Int) -> Void)?

        init(start: Int, callback: @escaping (Int) -> Void) {
            count = start
            self.callback = callback
        }

        deinit {
            print("TimerInfo deinit")
        }
    }

    @objc func decreaseGameTimer(_ timer: Timer) {
        if let userInfo = timer.userInfo as? TimerInfo {
            userInfo.count -= 1

            // call callback with new value
            userInfo.callback?(userInfo.count)

            print(userInfo.count)
            if userInfo.count == 0 {
                print("done")
                timer.invalidate()
            }
        }
    }

    func gameTimerMethod(timeParam: Int, callback: @escaping (Int) -> Void) {
        _ = Timer.scheduledTimer(timeInterval: 1, target: self,
                                 selector: #selector(decreaseGameTimer),
                                 userInfo: TimerInfo(start: timeParam, callback: callback),
                                 repeats: true)
    }
}

Then you'd call it like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // The closure that follows the gameTimerMethod call is using trailing
    // closure syntax.  It gets passed to gameTimerMethod as the second
    // parameter named callback.  This closure will get called every
    // second until the timer finishes.

    self.modelInstance.gameTimerMethod(timeParam: self.seconds) { value in
        self.label.text = "\(value)"
    }

    // Just for fun, lets run a second one at the same time
    self.modelInstance.gameTimerMethod(timeParam: 10) { value in
        self.label2.text = "\(value)"
    }
}


问:
Get error year by using NSDateFormatter transform NSDate to NSString
```<code>NSDate *date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = NSLocalizedString(@"yyyy-MM-dd", nil);
return [formatter stringFromDate:date];
</code>```

Today is "2017-06-09", but the result is "0029-06-09" on the user's iphone. How can I fix it?

答:
What is the "yyyy-MM-dd" localized string for ?

Or you can just set:

formatter.dateFormat = @"yyyy-MM-dd";

Body:
NSDate *date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = NSLocalizedString(@"yyyy-MM-dd", nil);
return [formatter stringFromDate:date];

Today is "2017-06-09", but the result is "0029-06-09" on the user's iphone. How can I fix it?


问:
python multiple project practice
So I have multiple projects like

```<code>DevelFolder/
   ├──MyuniversalModule/
      ├── .git
      ├── __init__.py
      └── mymodule.py
   ├──project01/
      └── myproject01.py
   └──project02/
      └── myproject02.py
</code>```

Now, In my 2 projects I would like to import "MyuniversalModule" which I have been developing separately and it is still work in progress and i will be changing it for needs of my projects. After finishing those projects, I will add this module but at this moment I would like to develop and test it separately, as it may be used in multiple places.

I was searching for solutions, like importing from parent directory

```<code>from ... import module
</code>```

or

```<code>import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
</code>```

or

```<code>import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
</code>```

But what is the best practise of working in such situation ?

答:
Relative imports are usually only used for submodules which are unique to your project. If you have a module which will be shared by multiple projects, a common practice is to package it separately as a pip package, and then in each new project use

```<code>pip install local/path/to/my/other/package
</code>```

to install it as a requirement. You can also use pip install git+ssh to install from a private git server.

Title: python multiple project practice

Body:
So I have multiple projects like

DevelFolder/
   ├──MyuniversalModule/
      ├── .git
      ├── __init__.py
      └── mymodule.py
   ├──project01/
      └── myproject01.py
   └──project02/
      └── myproject02.py

Now, In my 2 projects I would like to import "MyuniversalModule" which I have been developing separately and it is still work in progress and i will be changing it for needs of my projects. After finishing those projects, I will add this module but at this moment I would like to develop and test it separately, as it may be used in multiple places.

I was searching for solutions, like importing from parent directory

from ... import module

or

import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

or

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))

But what is the best practise of working in such situation ?

Body:
Relative imports are usually only used for submodules which are unique to your project. If you have a module which will be shared by multiple projects, a common practice is to package it separately as a pip package, and then in each new project use

pip install local/path/to/my/other/package

to install it as a requirement. You can also use pip install git+ssh to install from a private git server.


问:
Cannot open an html file from python in a web browser - notepad opens instead
In python I am trying to plot a graph with the pygal package

```<code>import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()
</code>```

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

```<code>url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)
</code>```

Anyone any thoughts?

答:
See the following from the webbrowser module documentation:

Note that on some platforms, trying to open a filename using this
  function, may work and start the operating system’s associated
  program.

Most likely the associated program for .html files on your system is notepad, not your browser.

Body:
In python I am trying to plot a graph with the pygal package

import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)

Anyone any thoughts?


问:
class vs type in Flow
In Flow, why would one use a class versus a type?</p>

```<code>type Point = {x: number; y: number};
class Point = {x: number; y: number};
</code>```

答:
As seen in the documentation, flow treats objects and classes differently. (And even if you are transpiring to ES5, flow checking happens before that.)

A class is compared by name. An object type is compared by structure.

In fact, the type alias is just a shorter way of writing the type structure annotation. It is like a variable containing the longer expression.

```<code>type A = {wow: number}
type B = {wow: number}

let a:A = {wow: 1}
let b:B = {wow: 2}
; [a, b] = [b, a] // fine
console.log(a, b) // > { wow: 2 } { wow: 1 }

class C {
  constructor (x: number) { this.wow = x }
  wow: number
}
class D {
  constructor (x: number) { this.wow = x }
  wow: number
}
let c:C = new C(3)
let d:D = new D(4)

c = d // ERROR: D This type is incompatible with C
d = b // ERROR: object type This type is incompatible with D
</code>```

As you can see, two classes with identical structure are not compatible.

NOTE: There are ways to make different classes compatible, eg Union Types or Interfaces

Title: class vs type in Flow

Body:
In Flow, why would one use a class versus a type?

type Point = {x: number; y: number};
class Point = {x: number; y: number};

Body:
As seen in the documentation, flow treats objects and classes differently. (And even if you are transpiring to ES5, flow checking happens before that.)

A class is compared by name. An object type is compared by structure.

In fact, the type alias is just a shorter way of writing the type structure annotation. It is like a variable containing the longer expression.

type A = {wow: number}
type B = {wow: number}

let a:A = {wow: 1}
let b:B = {wow: 2}
; [a, b] = [b, a] // fine
console.log(a, b) // > { wow: 2 } { wow: 1 }

class C {
  constructor (x: number) { this.wow = x }
  wow: number
}
class D {
  constructor (x: number) { this.wow = x }
  wow: number
}
let c:C = new C(3)
let d:D = new D(4)

c = d // ERROR: D This type is incompatible with C
d = b // ERROR: object type This type is incompatible with D

As you can see, two classes with identical structure are not compatible.

NOTE: There are ways to make different classes compatible, eg Union Types or Interfaces


问:
SWIG Python bindings for OpenCV 2.0 with MacPorts
Y'all,

I've been at to for 3 days trying to get OpenCV Python binds happening, and I have (the full epic struggle is documented here) but despite turning the SWIG flag on in CMake after installing swig via macports, I'm not getting any SWIG action :(

My cmake command looks like:

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/opt/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_SWIG_PYTHON_SUPPORT=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON -D BUILD_TESTS=ON -D PYTHON_INCLUDE_DIR=/opt/local/Library/Frameworks/Headers -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_SWIG_PYTHON_SUPPORT=ON -D CMAKE_CXX_COMPILER=/usr/bin/g++-4.2 -D CMAKE_C_COMPILER=/usr/bin/gcc-4.2 ..
</code>```

which pulls this error:

```<code>-- Looking for libavformat/avformat.h
-- Looking for libavformat/avformat.h - not found
-- Looking for ffmpeg/avformat.h
-- Looking for ffmpeg/avformat.h - not found
</code>```

SO I guess its not finding the one i have at:

```<code>/opt/local/include/libavformat/avformat.h
</code>```

How do I tell it about that? With something like

```<code>-D CMAKE_CXX_FLAGS="-I/opt/local/include" -D CMAKE_SHARED_LINKER_FLAGS="-L/opt/local/lib"
</code>```

???

I'm using OSX 10.5.8, Python 2.6 via Macports and compiling the latest OpenCV-trunk.

答:
If you're ok with the newer (non-SWIG) bindings, which imho are better anyway, you can just install directly via MacPorts:

```<code>sudo port install opencv +python26
</code>```

or

```<code>sudo port install opencv +python27
</code>```

as appropriate.

See also How to install OpenCV for python

Body:
Y'all,

I've been at to for 3 days trying to get OpenCV Python binds happening, and I have (the full epic struggle is documented here) but despite turning the SWIG flag on in CMake after installing swig via macports, I'm not getting any SWIG action :(

My cmake command looks like:

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/opt/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_SWIG_PYTHON_SUPPORT=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON -D BUILD_TESTS=ON -D PYTHON_INCLUDE_DIR=/opt/local/Library/Frameworks/Headers -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_SWIG_PYTHON_SUPPORT=ON -D CMAKE_CXX_COMPILER=/usr/bin/g++-4.2 -D CMAKE_C_COMPILER=/usr/bin/gcc-4.2 ..

which pulls this error:

-- Looking for libavformat/avformat.h
-- Looking for libavformat/avformat.h - not found
-- Looking for ffmpeg/avformat.h
-- Looking for ffmpeg/avformat.h - not found

SO I guess its not finding the one i have at:

/opt/local/include/libavformat/avformat.h

How do I tell it about that? With something like

-D CMAKE_CXX_FLAGS="-I/opt/local/include" -D CMAKE_SHARED_LINKER_FLAGS="-L/opt/local/lib"

???

I'm using OSX 10.5.8, Python 2.6 via Macports and compiling the latest OpenCV-trunk.

Body:
If you're ok with the newer (non-SWIG) bindings, which imho are better anyway, you can just install directly via MacPorts:

sudo port install opencv +python26

or

sudo port install opencv +python27

as appropriate.

See also How to install OpenCV for python


问:
Get JSON and Parse it in Swift?
I am getting json file from url with httpget request. Then, I want to print all tags that comes from json to the screen. I use this code for doing that however, I couldnot get in this way. Can you help me?

Swift 3 code:

```<code>let url:URL = URL(string: "https://api.hurriyet.com.tr/v1/articles...deleted...")!
let session = URLSession.shared

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let task = session.dataTask(with: request as URLRequest) {
    (data, response, error) in

    guard let data = data, let _:URLResponse = response, error == nil else {
        print("error")
        return
    }

    let dataString =  String(data: data, encoding: String.Encoding.utf8)

    for tags in data{
        for tag in tags["Tags"]{
            print(tag)
        }
    }

}

task.resume()
</code>```

Example json output and dataString variable's output also:

"[{"Tags":["fırat","kalkanı
  operasyonu","gazetehaberleri"]},{"Tags":["yüksek
  yargı","adliye","gazetehaberleri"]},{"Tags":["foo","Hüseyin Avni
  Mutlu","Hüseyin Çapkın","gazetehaberleri"]}]"

答:
Your json output response is in format Array of Dictionary [[String: Any]]

So the simple way to parse it is

```<code>do {
    // parse from data to array of dictionaries
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
        print(parsedData)
    }
}
catch {
    print(error)
}
</code>```

Title: Get JSON and Parse it in Swift?

Body:
I am getting json file from url with httpget request. Then, I want to print all tags that comes from json to the screen. I use this code for doing that however, I couldnot get in this way. Can you help me?

Swift 3 code:

let url:URL = URL(string: "https://api.hurriyet.com.tr/v1/articles...deleted...")!
let session = URLSession.shared

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let task = session.dataTask(with: request as URLRequest) {
    (data, response, error) in

    guard let data = data, let _:URLResponse = response, error == nil else {
        print("error")
        return
    }

    let dataString =  String(data: data, encoding: String.Encoding.utf8)

    for tags in data{
        for tag in tags["Tags"]{
            print(tag)
        }
    }

}

task.resume()

Example json output and dataString variable's output also:

"[{"Tags":["fırat","kalkanı
  operasyonu","gazetehaberleri"]},{"Tags":["yüksek
  yargı","adliye","gazetehaberleri"]},{"Tags":["foo","Hüseyin Avni
  Mutlu","Hüseyin Çapkın","gazetehaberleri"]}]"

Body:
Your json output response is in format Array of Dictionary [[String: Any]]

So the simple way to parse it is

do {
    // parse from data to array of dictionaries
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
        print(parsedData)
    }
}
catch {
    print(error)
}


问:
Pandorable way to reference a column of a filtered dataframe
I have a Dataframe that looks like this:

```<code>>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129
</code>```

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

```<code>df[df['Source'] == 'USB']['Log']
</code>```

Is there a better way to do this?

答:
In some cases the ][ isn't really good style because it's a sign that you're not taking full advantage of multidimensional slicing that NumPy and Pandas provide. But in other cases it's perfectly fine (like in your case) because you do completly different (and incompatible) operations.

The [df['Source'] == 'USB'] does a boolean array indexing and the ['Log'] makes a column lookup.

My opinion: No need to change anything here.

Body:
I have a Dataframe that looks like this:

>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

df[df['Source'] == 'USB']['Log']

Is there a better way to do this?


问:
How to consume OSGI service from non-component class
I have an object that is created during the course of a request, and I'd like that object to call a service. However, when the framework calls the bind methods, it binds to its own instance of the class, not the one I want to bind to.

```<code>public class A {
   final X x;
   final Y y;

   public A(Z z) {
        this.x = z.x;
        this.y = z.y;
   }

   public String doStuff() {
        //do stuff
        //call a service
   }
}

public class B extends RestAPIServlet {

    public String method(@SlingRequest SlingHttpServletRequest request, @SlingResponse SlingHttpServletResponse response) {
        Z z = new ObjectMapper().readValue(request.getReader(), Z.class);
        return new A(z).doStuff();
    }
}

public class C extends TagSupport {

    public int doStartTag() {
        Z z = getZFromProperties();
        String res = new A(z).doStuff();
        pageContext.setAttribute("res", res);
        return super.doStartTag();
    }
}
</code>```

Is there some way to call a service directly from A? Is there a preferred pattern for code reuse in the situation where you have a tag and a servlet performing the same work?

I've been asked not to make the tag/servlet implement a common interface to give A the service, nor to use a Supplier to give it access to the service through the tag/servlet.

答:
BundleContext can be retrieved using the FrameworkUtil helper class and that, in turn, can be used to get to the service that you want to use. Here is an example:

```<code>BundleContext bundleContext = FrameworkUtil.getBundle(A.class).getBundleContext();
ServiceReference serviceRef = bundleContext.getServiceReference(MyService.class.getName());
MyService myService = (MyService) bundleContext.getService(serviceRef);
</code>```

Body:
I have an object that is created during the course of a request, and I'd like that object to call a service. However, when the framework calls the bind methods, it binds to its own instance of the class, not the one I want to bind to.

public class A {
   final X x;
   final Y y;

   public A(Z z) {
        this.x = z.x;
        this.y = z.y;
   }

   public String doStuff() {
        //do stuff
        //call a service
   }
}

public class B extends RestAPIServlet {

    public String method(@SlingRequest SlingHttpServletRequest request, @SlingResponse SlingHttpServletResponse response) {
        Z z = new ObjectMapper().readValue(request.getReader(), Z.class);
        return new A(z).doStuff();
    }
}

public class C extends TagSupport {

    public int doStartTag() {
        Z z = getZFromProperties();
        String res = new A(z).doStuff();
        pageContext.setAttribute("res", res);
        return super.doStartTag();
    }
}

Is there some way to call a service directly from A? Is there a preferred pattern for code reuse in the situation where you have a tag and a servlet performing the same work?

I've been asked not to make the tag/servlet implement a common interface to give A the service, nor to use a Supplier to give it access to the service through the tag/servlet.

Body:
BundleContext can be retrieved using the FrameworkUtil helper class and that, in turn, can be used to get to the service that you want to use. Here is an example:

BundleContext bundleContext = FrameworkUtil.getBundle(A.class).getBundleContext();
ServiceReference serviceRef = bundleContext.getServiceReference(MyService.class.getName());
MyService myService = (MyService) bundleContext.getService(serviceRef);


问:
react-native :app:installDebug FAILED
Install APK debug to my device failed.

```<code>jianglinghuadeMacBook-Pro:hello jianglinghua$ react-native run-android
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug...
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
:app:preBuild UP-TO-DATE
......
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'MI NOTE LTE - 6.0.1'
Unable to install /Users/jianglinghua/Desktop/hello/android/app/build/outputs/apk/app-debug.apk
com.android.ddmlib.InstallException: Failed to establish session
    at com.android.ddmlib.Device.installPackages(Device.java:894)
    ........
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
:app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to establish session

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 13.945 secs
</code>```

Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/android-setup.html

I look at my devices

```<code>jianglinghuadeMacBook-Pro:hello jianglinghua$ adb devices
List of devices attached
98333978    device
</code>```

答:
Go to android/build.gradle, change

classpath 'com.android.tools.build:gradle:2.2.3'
 to

classpath 'com.android.tools.build:gradle:1.2.3'

Then, go to
android/gradle/wrapper/gradle-wrapper.properties,
change distributionURL to https://services.gradle.org/distributions/gradle-2.2-all.zip

Run again.

Title: react-native :app:installDebug FAILED

Body:
Install APK debug to my device failed.

jianglinghuadeMacBook-Pro:hello jianglinghua$ react-native run-android
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug...
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
:app:preBuild UP-TO-DATE
......
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'MI NOTE LTE - 6.0.1'
Unable to install /Users/jianglinghua/Desktop/hello/android/app/build/outputs/apk/app-debug.apk
com.android.ddmlib.InstallException: Failed to establish session
    at com.android.ddmlib.Device.installPackages(Device.java:894)
    ........
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
:app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to establish session

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 13.945 secs

Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/android-setup.html

I look at my devices

jianglinghuadeMacBook-Pro:hello jianglinghua$ adb devices
List of devices attached
98333978    device


问:
Why is this div jumping across the screen when I change the transform origin to right?
I have some divs that create a book link that opens up when hovered over, I'm trying to make my the book look more 3d by adding another red div with the class of .book-side to the left of the book and rotating it 90 degrees with a transform, with some perspective to make it look more boxy. I did this and noticed the edges of .bookside were going past the height of the book slightly. I figured this was because I set transform-origin was left, so it was rotating on its y axis towards book and not away form it. When I try to fix this by changing the transform-origin to right, .book-side jumps half way across the screen, I have also notices if I rotate it and set top to 0, it ends up in the middle of the top edge of its parent .front-of-book-front. I'm also having to use negative numbers to get it aligned with the top egde of its parent, something that normally you can do by simply setting top to 0, why do I have this odd behavior and how can I fix it?

html is in the jsfiddle, if you look closely towards the bottom of the of the book spine you can see the .book-side goes past the book a bit.
https://jsfiddle.net/ouwrhpwy/2/

```<code>    .front-of-book-front,
    .back-of-book-front,
    .book-front,
    .book-back,
    .book{
        width: 100px;
        height: 160px;
        position: relative;
        perspective: 1000px;
    }
    .book{
         margin: 52px auto;
         transition: transform 1s ease-in-out 0s;
        }
    .book-front{
            position: relative;
            transform-style: preserve-3d;
            transform-origin: left;
            transition: transform 1s ease-in-out 0s;
            box-shadow: 0px 3px 5px 2px rgba(0,0,0,.5);
             }
    .front-of-book-front{
            background-image: url("images/mainCover.jpg");
            background-repeat: no-repeat;
            background-size: cover;
            background-position: 47%;
            backface-visibility: hidden;
            perspective: 300px;
            perspective-origin: -150px;
            }
    .front-of-book-front:before{
        content: "Seraph Chronicles: Evangelion";
        text-shadow: 2px 2px 1px rgba(0,0,0,.5);
        font-size: .5em;
        line-height: 15px;
        color: white;
        width: 119px;
        height: 15px;
        background-color: rgba(255,165,0,.5);
        position: absolute;
        text-align: center;
        transform: translate(8px,93px) rotate(90deg);
    }
    .front-of-book-front:after{
        content: "";
        width: 75px;
        height: 12px;
        background-color: rgba(255,165,0,.5);
        position: absolute;
        transform: translate(0px,19px);
      }
     .bar{
        width: 80px;
        height: 8px;
        background-color: rgba(0,0,0,.8);
        font-size: .3em;
        color: white;
        text-align: right;
        transform: rotate(90deg) translate(36px,-45px);
         }

    .bar p{
        padding: 2px 3px 0 0 ;
        display: block;
    }
    .back-of-book-front{
        backface-visibility: hidden;
        background-color: rgb(240,234,214);
        transform: rotateY(180deg);
        position: absolute;
        top: 0;
    }
    .book-front:hover{
        transform: rotatey(-180deg);
            }
    .book:hover{
        transform: rotate(10deg);
                }

    .book-back{
        position: absolute;
        top:0;
        background-color: rgb(240,234,214);
        z-index: -1;
        box-shadow: 3px 3px 5px 0 rgba(0,0,0,.5);
        text-align: justify;
    }
    .book-side{
        width: 160px;
        height: 10px;
        background-color: red;hsl(1,0%,45%);
        position: absolute;
        left: -2px;//why the negative numbers?
        top:-5px;//why cant I simply just set it to 0?
        transform: rotate(90deg) rotateX(90deg);
        transform-origin: left;//when set to right it jump half way across the srceen
        font-size: .5em;
        color: white;
        text-align: center;
    }
    .book-side p{
        margin: 0;
        padding:0;
    }
    .book-back p{
        font-size: .1em;
        margin: 2.5em 1.5em;
                }
</code>```

答:
By tweaking the size and positioning a bit, you can get the .book-side to fit properly.

Here's a jsFiddle of your book, with the following adjustments to .book-side:

width: 158px;
height: 8px;
top: -3px

Body:
I have some divs that create a book link that opens up when hovered over, I'm trying to make my the book look more 3d by adding another red div with the class of .book-side to the left of the book and rotating it 90 degrees with a transform, with some perspective to make it look more boxy. I did this and noticed the edges of .bookside were going past the height of the book slightly. I figured this was because I set transform-origin was left, so it was rotating on its y axis towards book and not away form it. When I try to fix this by changing the transform-origin to right, .book-side jumps half way across the screen, I have also notices if I rotate it and set top to 0, it ends up in the middle of the top edge of its parent .front-of-book-front. I'm also having to use negative numbers to get it aligned with the top egde of its parent, something that normally you can do by simply setting top to 0, why do I have this odd behavior and how can I fix it?

html is in the jsfiddle, if you look closely towards the bottom of the of the book spine you can see the .book-side goes past the book a bit.
https://jsfiddle.net/ouwrhpwy/2/

    .front-of-book-front,
    .back-of-book-front,
    .book-front,
    .book-back,
    .book{
        width: 100px;
        height: 160px;
        position: relative;
        perspective: 1000px;
    }
    .book{
         margin: 52px auto;
         transition: transform 1s ease-in-out 0s;
        }
    .book-front{
            position: relative;
            transform-style: preserve-3d;
            transform-origin: left;
            transition: transform 1s ease-in-out 0s;
            box-shadow: 0px 3px 5px 2px rgba(0,0,0,.5);
             }
    .front-of-book-front{
            background-image: url("images/mainCover.jpg");
            background-repeat: no-repeat;
            background-size: cover;
            background-position: 47%;
            backface-visibility: hidden;
            perspective: 300px;
            perspective-origin: -150px;
            }
    .front-of-book-front:before{
        content: "Seraph Chronicles: Evangelion";
        text-shadow: 2px 2px 1px rgba(0,0,0,.5);
        font-size: .5em;
        line-height: 15px;
        color: white;
        width: 119px;
        height: 15px;
        background-color: rgba(255,165,0,.5);
        position: absolute;
        text-align: center;
        transform: translate(8px,93px) rotate(90deg);
    }
    .front-of-book-front:after{
        content: "";
        width: 75px;
        height: 12px;
        background-color: rgba(255,165,0,.5);
        position: absolute;
        transform: translate(0px,19px);
      }
     .bar{
        width: 80px;
        height: 8px;
        background-color: rgba(0,0,0,.8);
        font-size: .3em;
        color: white;
        text-align: right;
        transform: rotate(90deg) translate(36px,-45px);
         }

    .bar p{
        padding: 2px 3px 0 0 ;
        display: block;
    }
    .back-of-book-front{
        backface-visibility: hidden;
        background-color: rgb(240,234,214);
        transform: rotateY(180deg);
        position: absolute;
        top: 0;
    }
    .book-front:hover{
        transform: rotatey(-180deg);
            }
    .book:hover{
        transform: rotate(10deg);
                }

    .book-back{
        position: absolute;
        top:0;
        background-color: rgb(240,234,214);
        z-index: -1;
        box-shadow: 3px 3px 5px 0 rgba(0,0,0,.5);
        text-align: justify;
    }
    .book-side{
        width: 160px;
        height: 10px;
        background-color: red;hsl(1,0%,45%);
        position: absolute;
        left: -2px;//why the negative numbers?
        top:-5px;//why cant I simply just set it to 0?
        transform: rotate(90deg) rotateX(90deg);
        transform-origin: left;//when set to right it jump half way across the srceen
        font-size: .5em;
        color: white;
        text-align: center;
    }
    .book-side p{
        margin: 0;
        padding:0;
    }
    .book-back p{
        font-size: .1em;
        margin: 2.5em 1.5em;
                }


问:
draw one or more plots in the same window
I want compare two curves, it's possible with R to draw a plot and then draw another plot over it ? how ?

thanks.

答:
With base R, you can plot your one curve and then add the second curve with the lines() argument. Here's a quick example:

```<code>x <- 1:10
y <- x^2
y2 <- x^3

plot(x,y, type = "l")
lines(x, y2, col = "red")
</code>```

Alternatively, if you wanted to use ggplot2, here are two methods - one plots different colors on the same plot, and the other generates separate plots for each variable. The trick here is to "melt" the data into long format first.

```<code>library(ggplot2)

df <- data.frame(x, y, y2)

df.m <- melt(df, id.var = "x")

qplot(x, value, data = df.m, colour = variable, geom = "line")

qplot(x, value, data = df.m, geom = "line")+ facet_wrap(~ variable)
</code>```

Body:
With base R, you can plot your one curve and then add the second curve with the lines() argument. Here's a quick example:

x <- 1:10
y <- x^2
y2 <- x^3

plot(x,y, type = "l")
lines(x, y2, col = "red")

Alternatively, if you wanted to use ggplot2, here are two methods - one plots different colors on the same plot, and the other generates separate plots for each variable. The trick here is to "melt" the data into long format first.

library(ggplot2)

df <- data.frame(x, y, y2)

df.m <- melt(df, id.var = "x")

qplot(x, value, data = df.m, colour = variable, geom = "line")

qplot(x, value, data = df.m, geom = "line")+ facet_wrap(~ variable)


问:
QtCreator build mode: Profile
I've just upgraded to the latest QtCreator IDE and found out that among old two build modes {release, debug} there is a third one: Profile. Could someone point me to the explanation of difference between this new mode and the old ones?

I guess it should be related to Valgrind function profiler that usually takes Release builds only.

答:
From Qt Documentation.

A profile configuration is an optimized release build that is
  delivered with separate debug information. It is best suited for
  analyzing applications.

On Windows. It will create pdb alone with release version exe. Run faster and can still debug with symbols using Just-In-Time Debugger

Title: QtCreator build mode: Profile


问:
CodeIgniter encrypt decode not working
I was using CodeIgniter encrypt library and everything was working fine, but now I've moved the project to a new server and it simple stoped working.

This simple test:

```<code>$this->load->library('encrypt');
$str = '12345';
$key = 'my-secret-key';
$encrypted = $this->encrypt->encode($str, $key);
var_dump($encrypted);
var_dump($this->encrypt->decode($encrypted, $key));
die();
</code>```

Its returning:

```<code>string(76) "v9kMgDy+MUHgu5ug6N2qWms0/6tJ+a9N86kmpNvwkKI4nU8yL93kkAH1bmhn57ADh8WGB64i18E="
A PHP Error was encountered

Severity: Warning

Message: mcrypt_decrypt(): Received initialization vector of size 38, but size 32 is required for this encryption mode

Filename: libraries/Encrypt.php

Line Number: 346

string(0) ""
</code>```

(The PHP Error/Warning appears only sometimes)

Thanks

答:
Always use an exact length key (128, 192 or 256 bit for AES and an an exact length IV (128-bits or 16-bytes for AES), otherwise you will get an error or some unknown padding will be added.

The error is quite clear:

Received initialization vector of size 38, but size 32 is required for this encryption mode

The IV is an incorrect length.

Of course there is the issue that the provided code does not have an IV.

Also the error messages states the expected IV length is 32 bytes, that is not AES. Mose likely it is Rijndael with a 256-bit key. This is a common error using mcrypt where the argument is the block size not the key size.  The key size is based on the size of the passed key.

MCRYPT_RIJNDAEL_256 is Rijndael with a 256-bit block size which is not AES,

MCRYPT_RIJNDAEL_128 is Rijndael with a 128-bit block size which is AES

Title: CodeIgniter encrypt decode not working

Body:
I was using CodeIgniter encrypt library and everything was working fine, but now I've moved the project to a new server and it simple stoped working.

This simple test:

$this->load->library('encrypt');
$str = '12345';
$key = 'my-secret-key';
$encrypted = $this->encrypt->encode($str, $key);
var_dump($encrypted);
var_dump($this->encrypt->decode($encrypted, $key));
die();

Its returning:

string(76) "v9kMgDy+MUHgu5ug6N2qWms0/6tJ+a9N86kmpNvwkKI4nU8yL93kkAH1bmhn57ADh8WGB64i18E="
A PHP Error was encountered

Severity: Warning

Message: mcrypt_decrypt(): Received initialization vector of size 38, but size 32 is required for this encryption mode

Filename: libraries/Encrypt.php

Line Number: 346

string(0) ""

(The PHP Error/Warning appears only sometimes)

Thanks


问:
javascript regex search from end of string to begining
Is it possible to use regex to search from end of string to beginning?

for example i have a string: "a2bba2b"

I know i need the last occurrence of /a2/ and it seems highly inefficient to make machine go trough whole string which can be quite long. I know the needle will  be somewhere near the end of string(haystack), so i would like to reverse the order simply tell the script to search from end to beginning to save some resources.
Regex seems like a way to go match more complicated string.And it is way easier to write complex regex than your own search function.

So is there a way maybe a flag or something to reverse searching order to match regex from end to start of input string. Does any of the modern languages support something like that? if not why?

答: How about string reverse your string and your regex? then get the first occurence?</p>


问:
JAXB marshalling: treat empty object like it's null
I want to explain my issue with a simple example:

Foo:

```<code>@SomeXMLAnnotations
public class Foo {
    // Bar is just a random class with its own XML annotations
    @XmlElement(required = true)
    Bar someBarObj;

    boolean chosen = true;
    boolean required = true;

    public Foo(){
        chosen = false;
    }

    public Foo(Bar someBarObj){
        this.someBarObj = someBarObj;
    }
}
</code>```

MyClass:

```<code>@SomeXMLAnnotations
public class MyClass {

    @XmlElement(required = false)
    Foo anyFooObj;

    @XmlElement(required = true)
    Foo anyFooObjRequired;

    public MyClass (){ }

    public MyClass (Foo anyFooObj, Foo anyFooObjRequired){
        this.anyFooObj = anyFooObj;
        if(anyFooObj == null)
            this.anyFooObj = new Foo();
        /*
         * This is the reason why i can't let 'anyFooObj' be 'null'.
         * So 'anyFooObj' MUST be initialized somehow.
         * It's needed for some internal logic, not JAXB.
         */
        anyFooObj.required = false;

        this.anyFooObjRequired = anyFooObjRequired;
    }
}
</code>```

Example Objects:

```<code>Foo fooRequired = new Foo(new Bar());
MyClass myObj = new MyClass(null, fooRequired);
</code>```

When i try to marshal myObj now, it throws an exception like this:

```<code>org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException;
cvc-complex-type.2.4.b: The content of element 'n0:anyFooObj ' is not complete.
One of '{"AnyNamespace":someBarObj}' is expected.
</code>```

This happens because anyFooObj is initialized but it's required, member
someBarObj isn't.

Possible Solution:

I know i could add this method to MyClass:

```<code>void beforeMarshal(Marshaller m){
    if(! anyFooObj.chosen)
        anyFooObj= null;
    }
}
</code>```

But I have a lot of classes and those classes have a lot of not required fields.
So this solution would take ages and doesn't look like a proper solution as well.

My Question:

Is there a way to tell JAXB that it should treat empty objects like they were null? Or that it should ignore an element when it's not properly set. Something like this for example:

```<code>@XmlElement(required = false, ingnoreWhenNotMarshallable = true)
Foo anyFooObj;
</code>```

NOTE:

I'm NOT the developer of the code. I just have to add JAXB to the project and make everything compatible with a given XSD file. I'm NOT allowed to change the relation between classes.

答:
I think you're trying to make the JAXB marshaller do something it's really not designed to do, so I'd say you're into hack territory here. I'd recommend pushing back on the requirements to try and avoid having this problem in the first place.

That said, if you have to do it then given your requirement to avoid writing code for each class/field, I think you'll want to use reflection for this - I've included an example below that reflectively inspects the values of all fields.

Useful extensions would be:

Have it consider getter methods too

Make the null-setting behaviour opt-in by requiring the field has an additional annotation - you could name it @JAXBNullIfEmpty

Example.java:

```<code>import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringWriter;
import java.lang.reflect.Field;

public class Example
{
    public abstract static class JAXBAutoNullifierForEmptyOptionalFields
    {
        void beforeMarshal(Marshaller x)
        {
            try
            {
                for (Field field : this.getClass().getFields())
                {
                    final XmlElement el = field.getAnnotation(XmlElement.class);

                    // If this is an optional field, it has a value & it has no fields populated then we should replace it with null
                    if (!el.required())
                    {
                        if (JAXBAutoNullifierForEmptyOptionalFields.class.isAssignableFrom(field.getType()))
                        {
                            final JAXBAutoNullifierForEmptyOptionalFields val = (JAXBAutoNullifierForEmptyOptionalFields) field.get(
                                    this);

                            if (val != null && !val.hasAnyElementFieldsPopulated())
                                field.set(this, null); // No fields populated, replace with null
                        }
                    }
                }
            }
            catch (IllegalAccessException e)
            {
                throw new RuntimeException("Error determining if class has all required fields: " + this, e);
            }
        }

        boolean hasAnyElementFieldsPopulated()
        {
            for (Field field : this.getClass().getFields())
            {
                try
                {
                    if (field.isAnnotationPresent(XmlElement.class))
                    {
                        // Retrieve value
                        final Object val = field.get(this);

                        // If the value is non-null then at least one field has been populated
                        if (val != null)
                        {
                            return true;
                        }
                    }
                }
                catch (IllegalAccessException e)
                {
                    throw new RuntimeException("Error determining if class has any populated JAXB fields: " + this, e);
                }
            }

            // There were no fields with a non-null value
            return false;
        }
    }

    @XmlRootElement
    public static class MyJAXBType extends JAXBAutoNullifierForEmptyOptionalFields
    {
        @XmlElement
        public String someField;

        @XmlElement
        public MyJAXBType someOtherField;

        public MyJAXBType()
        {
        }

        public MyJAXBType(final String someField, MyJAXBType someOtherField)
        {
            this.someField = someField;
            this.someOtherField = someOtherField;
        }
    }

    public static void main(String[] args) throws Exception
    {
        final Marshaller marshaller = JAXBContext.newInstance(MyJAXBType.class).createMarshaller();

        MyJAXBType innerValue = new MyJAXBType(); // Unpopulated inner value
        MyJAXBType value = new MyJAXBType("some text value", innerValue);

        final StringWriter sw = new StringWriter();

        marshaller.marshal(value, sw); // Omits "someOtherField"

        System.out.println(sw.toString());
    }
}
</code>```

Body:
I want to explain my issue with a simple example:

Foo:

@SomeXMLAnnotations
public class Foo {
    // Bar is just a random class with its own XML annotations
    @XmlElement(required = true)
    Bar someBarObj;

    boolean chosen = true;
    boolean required = true;

    public Foo(){
        chosen = false;
    }

    public Foo(Bar someBarObj){
        this.someBarObj = someBarObj;
    }
}

MyClass:

@SomeXMLAnnotations
public class MyClass {

    @XmlElement(required = false)
    Foo anyFooObj;

    @XmlElement(required = true)
    Foo anyFooObjRequired;

    public MyClass (){ }

    public MyClass (Foo anyFooObj, Foo anyFooObjRequired){
        this.anyFooObj = anyFooObj;
        if(anyFooObj == null)
            this.anyFooObj = new Foo();
        /*
         * This is the reason why i can't let 'anyFooObj' be 'null'.
         * So 'anyFooObj' MUST be initialized somehow.
         * It's needed for some internal logic, not JAXB.
         */
        anyFooObj.required = false;

        this.anyFooObjRequired = anyFooObjRequired;
    }
}

Example Objects:

Foo fooRequired = new Foo(new Bar());
MyClass myObj = new MyClass(null, fooRequired);

When i try to marshal myObj now, it throws an exception like this:

org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException;
cvc-complex-type.2.4.b: The content of element 'n0:anyFooObj ' is not complete.
One of '{"AnyNamespace":someBarObj}' is expected.

This happens because anyFooObj is initialized but it's required, member
someBarObj isn't.

Possible Solution:

I know i could add this method to MyClass:

void beforeMarshal(Marshaller m){
    if(! anyFooObj.chosen)
        anyFooObj= null;
    }
}

But I have a lot of classes and those classes have a lot of not required fields.
So this solution would take ages and doesn't look like a proper solution as well.

My Question:

Is there a way to tell JAXB that it should treat empty objects like they were null? Or that it should ignore an element when it's not properly set. Something like this for example:

@XmlElement(required = false, ingnoreWhenNotMarshallable = true)
Foo anyFooObj;

NOTE:

I'm NOT the developer of the code. I just have to add JAXB to the project and make everything compatible with a given XSD file. I'm NOT allowed to change the relation between classes.

Body:
I think you're trying to make the JAXB marshaller do something it's really not designed to do, so I'd say you're into hack territory here. I'd recommend pushing back on the requirements to try and avoid having this problem in the first place.

That said, if you have to do it then given your requirement to avoid writing code for each class/field, I think you'll want to use reflection for this - I've included an example below that reflectively inspects the values of all fields.

Useful extensions would be:

Have it consider getter methods too

Make the null-setting behaviour opt-in by requiring the field has an additional annotation - you could name it @JAXBNullIfEmpty

Example.java:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringWriter;
import java.lang.reflect.Field;

public class Example
{
    public abstract static class JAXBAutoNullifierForEmptyOptionalFields
    {
        void beforeMarshal(Marshaller x)
        {
            try
            {
                for (Field field : this.getClass().getFields())
                {
                    final XmlElement el = field.getAnnotation(XmlElement.class);

                    // If this is an optional field, it has a value & it has no fields populated then we should replace it with null
                    if (!el.required())
                    {
                        if (JAXBAutoNullifierForEmptyOptionalFields.class.isAssignableFrom(field.getType()))
                        {
                            final JAXBAutoNullifierForEmptyOptionalFields val = (JAXBAutoNullifierForEmptyOptionalFields) field.get(
                                    this);

                            if (val != null && !val.hasAnyElementFieldsPopulated())
                                field.set(this, null); // No fields populated, replace with null
                        }
                    }
                }
            }
            catch (IllegalAccessException e)
            {
                throw new RuntimeException("Error determining if class has all required fields: " + this, e);
            }
        }

        boolean hasAnyElementFieldsPopulated()
        {
            for (Field field : this.getClass().getFields())
            {
                try
                {
                    if (field.isAnnotationPresent(XmlElement.class))
                    {
                        // Retrieve value
                        final Object val = field.get(this);

                        // If the value is non-null then at least one field has been populated
                        if (val != null)
                        {
                            return true;
                        }
                    }
                }
                catch (IllegalAccessException e)
                {
                    throw new RuntimeException("Error determining if class has any populated JAXB fields: " + this, e);
                }
            }

            // There were no fields with a non-null value
            return false;
        }
    }

    @XmlRootElement
    public static class MyJAXBType extends JAXBAutoNullifierForEmptyOptionalFields
    {
        @XmlElement
        public String someField;

        @XmlElement
        public MyJAXBType someOtherField;

        public MyJAXBType()
        {
        }

        public MyJAXBType(final String someField, MyJAXBType someOtherField)
        {
            this.someField = someField;
            this.someOtherField = someOtherField;
        }
    }

    public static void main(String[] args) throws Exception
    {
        final Marshaller marshaller = JAXBContext.newInstance(MyJAXBType.class).createMarshaller();

        MyJAXBType innerValue = new MyJAXBType(); // Unpopulated inner value
        MyJAXBType value = new MyJAXBType("some text value", innerValue);

        final StringWriter sw = new StringWriter();

        marshaller.marshal(value, sw); // Omits "someOtherField"

        System.out.println(sw.toString());
    }
}