问:
How to export edgelist from Grakn without using client APIs
I'm trying to export edges from grakn. I can do that with Python client like so:

edge_query = "match $c2c($c1, $c2) isa c2c; $c1 has id $id1; $c2 has id $id2;get $id1,$id2;"
with open(f"grakn.edgelist","w") as outfile:
    with GraknClient(uri="localhost:48555") as client:
        with client.session(keyspace=KEYSPACE) as session:
            with session.transaction().read() as read_transaction:
                answer_iterator = read_transaction.query(edge_query)
                for answer in tqdm(answer_iterator):
                    id1 = answer.get("id1")
                    id2 = answer.get("id2")
                    outfile.write(f"{id1.value()} {id2.value()} \n")
```

Edit: For each Relation, I want to export entities pairwise. The output can be a pair of Grakn IDs.
I can ignore the attributes of relation or entities.

Exporting to edges seems like a common task. Is there a better way(more elegant, faster, more efficient) to do it in Grakn?

答:
This works as long as the relation type c2c always has two roleplayers. However, this will produce two edges for every $c1, $c2, which is probably not what you want.

Let's take a pair of Things, with ids V123 and V456. If they satisfy $c2c($c1, $c2) isa c2c; with $c1 = V123 and $c2 = V456 then they will also satisfy the same pattern as $c1 = V456 and $c2 = V123. Grakn will return all combinations of $c1, $c2 that satisfy your query, so you'll get two answers back for this one c2c relation.

Assuming this isn't what you want, if $c1 and $c2 play different roles in the relation c2c (likely implying there is direction to the edge) then try changing the query, adding the roles, to:

```<code>edge_query = "match $c2c(role1: $c1, role2: $c2) isa c2c; $c1 has id $id1; $c2 has id $id2; get $id1,$id2;"
</code>```

If they both play the same role (implying undirected edges), then we need to do something different in our logic. Either store edges as a set of sets of ids to remove duplicates without much effort, or perhaps consider using the Python ConceptAPI, something like this:

```<code>relation_query = "match $rc2c isa c2c;get;"

with open(f"grakn.edgelist","w") as outfile:
    with GraknClient(uri="localhost:48555") as client:
        with client.session(keyspace=KEYSPACE) as session:
            with session.transaction().read() as read_transaction:
                answer_iterator = read_transaction.query(relation_query)
                for answer in answer_iterator:
                    relation_concept = answer.get("rc2c")
                    role_players_map = relation_concept.role_players_map()

                    role_player_ids = set()
                    for role, thing in role_players_map.items():
                        # Here you can do any logic regarding what things play which roles
                        for t in thing:
                            role_player_ids.add(t.id) # Note that you can retrieve a concept id from the concept object, you don't need to ask for it in the query
                    outfile.write(", ".join(role_player_ids) + "\n")
</code>```

Of course, I have no idea what you're doing with the resulting edgelist, but for completeness, the more Grakn-esque way would be to treat the Relation as a first-class citizen since it represents a hyperedge in the Grakn knowledge model, in this case we would treat the Roles of the relation as edges. This means we aren't stuck when we have ternary or N-ary relations. We can do this by changing the query:

```<code>match $c2c($c) isa c2c; get;
</code>```

Then in the result we get the id of the $c2c and of the $c.

Body:
I'm trying to export edges from grakn. I can do that with Python client like so:

edge_query = "match $c2c($c1, $c2) isa c2c; $c1 has id $id1; $c2 has id $id2;get $id1,$id2;"
with open(f"grakn.edgelist","w") as outfile:
    with GraknClient(uri="localhost:48555") as client:
        with client.session(keyspace=KEYSPACE) as session:
            with session.transaction().read() as read_transaction:
                answer_iterator = read_transaction.query(edge_query)
                for answer in tqdm(answer_iterator):
                    id1 = answer.get("id1")
                    id2 = answer.get("id2")
                    outfile.write(f"{id1.value()} {id2.value()} \n")

Edit: For each Relation, I want to export entities pairwise. The output can be a pair of Grakn IDs.
I can ignore the attributes of relation or entities.

Exporting to edges seems like a common task. Is there a better way(more elegant, faster, more efficient) to do it in Grakn?

Body:
This works as long as the relation type c2c always has two roleplayers. However, this will produce two edges for every $c1, $c2, which is probably not what you want.

Let's take a pair of Things, with ids V123 and V456. If they satisfy $c2c($c1, $c2) isa c2c; with $c1 = V123 and $c2 = V456 then they will also satisfy the same pattern as $c1 = V456 and $c2 = V123. Grakn will return all combinations of $c1, $c2 that satisfy your query, so you'll get two answers back for this one c2c relation.

Assuming this isn't what you want, if $c1 and $c2 play different roles in the relation c2c (likely implying there is direction to the edge) then try changing the query, adding the roles, to:

edge_query = "match $c2c(role1: $c1, role2: $c2) isa c2c; $c1 has id $id1; $c2 has id $id2; get $id1,$id2;"

If they both play the same role (implying undirected edges), then we need to do something different in our logic. Either store edges as a set of sets of ids to remove duplicates without much effort, or perhaps consider using the Python ConceptAPI, something like this:

relation_query = "match $rc2c isa c2c;get;"

with open(f"grakn.edgelist","w") as outfile:
    with GraknClient(uri="localhost:48555") as client:
        with client.session(keyspace=KEYSPACE) as session:
            with session.transaction().read() as read_transaction:
                answer_iterator = read_transaction.query(relation_query)
                for answer in answer_iterator:
                    relation_concept = answer.get("rc2c")
                    role_players_map = relation_concept.role_players_map()

                    role_player_ids = set()
                    for role, thing in role_players_map.items():
                        # Here you can do any logic regarding what things play which roles
                        for t in thing:
                            role_player_ids.add(t.id) # Note that you can retrieve a concept id from the concept object, you don't need to ask for it in the query
                    outfile.write(", ".join(role_player_ids) + "\n")

Of course, I have no idea what you're doing with the resulting edgelist, but for completeness, the more Grakn-esque way would be to treat the Relation as a first-class citizen since it represents a hyperedge in the Grakn knowledge model, in this case we would treat the Roles of the relation as edges. This means we aren't stuck when we have ternary or N-ary relations. We can do this by changing the query:

match $c2c($c) isa c2c; get;

Then in the result we get the id of the $c2c and of the $c.


来源: stackexchange

问:
What is the need of serialization of objects in Java?
Can anyone tell me what is the need of Serialization of objects in Java and give me an example scenario to explain the need? (I already understand what serialization is, I just want to understand when you'd use it and how'd use it?).</p>

答:
Serialization is needed when there is a problem in sending data from one class to another.
Where the other class is on a different location or Hard Disk. i.e. in Distributed Systems

The reverse operation of serialisation is called deserialization

The String Class and all wrapper classes implement serializable interface by default

Serializable interface is also marker interface which provides the capability of Serialization to your class. So, we should implement a serializable interface if we want to send the state of an object over the network

ContentLicense: CC BY-SA 4.0


问:
In pandas, how should one add age-range columns?
Let's say I've got a simple DataFrame that details when people have been playing music through their lives, like this:

```<code>import pandas as pd

df = pd.DataFrame(
    [[15,  8,  7],
     [20, 10, 10],
     [35, 15, 20],
     [50, 12, 38]],
    columns=['current age', 'age started playing music', 'years playing music'])
</code>```

How should one add additional columns that break down the number of years playing music they've had in each decade of their lives? For example, if the columns added were 0-10, 10-20, 20-30 etc., then the first person would have had 2 years of playing music in their first decade, 5 in their second, 0 in their third etc.

答:
I suggest to create a function that will return a list with the number of years played per decade and then apply it to your dataframe

```<code>import numpy as np

# Create list with numbers of years played in a decade
def get_years_playing_music_decade(current_age, age_start):
    if age_start > current_age: # should not be possible
        return None
    # convert age to list of booleans
    # was he playing on its i-th Year of living
    # Example : age_start = 3 is a list [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 ...]
    age_start_lst = [0] * age_start + (100-age_start) * [1]
    # was he living on its i-th Year of living
    current_age_lst = [1] * current_age + (100-current_age) * [0]
    # combination of living and playing
    playing_music_lst = [1 if x==y else 0 for x, y in zip(age_start_lst, current_age_lst)]
    # group by 10y
    playing_music_lst_10y = [sum(playing_music_lst[(10*i):((10*i)+10)]) for i in range(0, 10)]
    return playing_music_lst_10y

get_years_playing_music_decade(current_age=33, age_start=12)
# [0, 8, 10, 3, 0, 0, 0, 0, 0, 0]

# create columns 0-10 .. 90-100
colnames=list()
for i in range(10):
    colnames += [str(10*i) + '-' + str(10*(i+1))]

# apply defined function to the dataframe
df[colnames] = pd.DataFrame(df.apply(lambda x: get_years_playing_music_decade(
    int(x['current age']), int(x['age started playing music'])), axis=1).values.tolist())
</code>```

Body:
Let's say I've got a simple DataFrame that details when people have been playing music through their lives, like this:

import pandas as pd

df = pd.DataFrame(
    [[15,  8,  7],
     [20, 10, 10],
     [35, 15, 20],
     [50, 12, 38]],
    columns=['current age', 'age started playing music', 'years playing music'])

How should one add additional columns that break down the number of years playing music they've had in each decade of their lives? For example, if the columns added were 0-10, 10-20, 20-30 etc., then the first person would have had 2 years of playing music in their first decade, 5 in their second, 0 in their third etc.

Body:
I suggest to create a function that will return a list with the number of years played per decade and then apply it to your dataframe

import numpy as np

# Create list with numbers of years played in a decade
def get_years_playing_music_decade(current_age, age_start):
    if age_start > current_age: # should not be possible
        return None
    # convert age to list of booleans
    # was he playing on its i-th Year of living
    # Example : age_start = 3 is a list [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 ...]
    age_start_lst = [0] * age_start + (100-age_start) * [1]
    # was he living on its i-th Year of living
    current_age_lst = [1] * current_age + (100-current_age) * [0]
    # combination of living and playing
    playing_music_lst = [1 if x==y else 0 for x, y in zip(age_start_lst, current_age_lst)]
    # group by 10y
    playing_music_lst_10y = [sum(playing_music_lst[(10*i):((10*i)+10)]) for i in range(0, 10)]
    return playing_music_lst_10y

get_years_playing_music_decade(current_age=33, age_start=12)
# [0, 8, 10, 3, 0, 0, 0, 0, 0, 0]

# create columns 0-10 .. 90-100
colnames=list()
for i in range(10):
    colnames += [str(10*i) + '-' + str(10*(i+1))]

# apply defined function to the dataframe
df[colnames] = pd.DataFrame(df.apply(lambda x: get_years_playing_music_decade(
    int(x['current age']), int(x['age started playing music'])), axis=1).values.tolist())


问:
Compare a list of strings with each other in R
I am trying to compare a list of strings with each other using the function levenshteinSim() from package 'RecordLinkage'. However, I am having a very hard time to figure out how I can incorporate my list of strings into the function as it only takes two arguments str1 and str2. I am trying to find the most optimal way as my list contains 4k strings. Any help is much appreciated!

Below is some sample data:

```<code>sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')
</code>```

答:
Getting the levenshtein distance or levenshtein similarity is pretty straightforward without the RecordLinkage package, which was recently removed from CRAN.

In base R:

```<code>sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')
adist(sample)
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    0    3    3    4    4    4
#> [2,]    3    0    3    3    4    3
#> [3,]    3    3    0    4    5    4
#> [4,]    4    3    4    0    1    2
#> [5,]    4    4    5    1    0    1
#> [6,]    4    3    4    2    1    0
</code>```

Using the much faster stringdist package (which supports a bunch of alternative methods to levenshtein distance, check help("stringdist-metrics"))

```<code>stringdist::stringdistmatrix(sample, method = "lv", useNames = "strings")
#>         apple appeal apparel peel peer
#> appeal      3
#> apparel     3      3
#> peel        4      3       4
#> peer        4      4       5    1
#> pear        4      3       4    2    1
</code>```

If you want string similarly instead, you can use stringsim() or stringsimmatrix to get all comparisons at once (only available in the development version so far; devtools::install_github("markvanderloo/stringdist/pkg")):

```<code>stringdist::stringsimmatrix(sample, method = "lv", useNames = "strings")
#>             apple    appeal apparel      peel      peer      pear
#> apple   1.0000000 0.4000000     0.4 0.2000000 0.2000000 0.2000000
#> appeal  0.5000000 1.0000000     0.5 0.5000000 0.3333333 0.5000000
#> apparel 0.5714286 0.5714286     1.0 0.4285714 0.2857143 0.4285714
#> peel    0.0000000 0.2500000     0.0 1.0000000 0.7500000 0.5000000
#> peer    0.0000000 0.0000000     0.0 0.7500000 1.0000000 0.7500000
#> pear    0.0000000 0.2500000     0.0 0.5000000 0.7500000 1.0000000
</code>```

If you want to get this into a tidy format, you could do the following:

```<code>library(tidyverse)
stringdist::stringsimmatrix(sample, method = "lv", useNames = "strings") %>%
  as.matrix() %>%
  as_tibble(rownames = "word1") %>%
  pivot_longer(-word1, names_to = "word2", values_to = "distance")
#> # A tibble: 36 x 3
#>    word1  word2   distance
#>    <chr>  <chr>      <dbl>
#>  1 apple  apple      1
#>  2 apple  appeal     0.4
#>  3 apple  apparel    0.4
#>  4 apple  peel       0.200
#>  5 apple  peer       0.200
#>  6 apple  pear       0.200
#>  7 appeal apple      0.5
#>  8 appeal appeal     1
#>  9 appeal apparel    0.5
#> 10 appeal peel       0.5
#> # ... with 26 more rows
</code>```

Body:
I am trying to compare a list of strings with each other using the function levenshteinSim() from package 'RecordLinkage'. However, I am having a very hard time to figure out how I can incorporate my list of strings into the function as it only takes two arguments str1 and str2. I am trying to find the most optimal way as my list contains 4k strings. Any help is much appreciated!

Below is some sample data:

sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')

Body:
Getting the levenshtein distance or levenshtein similarity is pretty straightforward without the RecordLinkage package, which was recently removed from CRAN.

In base R:

sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')
adist(sample)
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    0    3    3    4    4    4
#> [2,]    3    0    3    3    4    3
#> [3,]    3    3    0    4    5    4
#> [4,]    4    3    4    0    1    2
#> [5,]    4    4    5    1    0    1
#> [6,]    4    3    4    2    1    0

Using the much faster stringdist package (which supports a bunch of alternative methods to levenshtein distance, check help("stringdist-metrics"))

stringdist::stringdistmatrix(sample, method = "lv", useNames = "strings")
#>         apple appeal apparel peel peer
#> appeal      3
#> apparel     3      3
#> peel        4      3       4
#> peer        4      4       5    1
#> pear        4      3       4    2    1

If you want string similarly instead, you can use stringsim() or stringsimmatrix to get all comparisons at once (only available in the development version so far; devtools::install_github("markvanderloo/stringdist/pkg")):

stringdist::stringsimmatrix(sample, method = "lv", useNames = "strings")
#>             apple    appeal apparel      peel      peer      pear
#> apple   1.0000000 0.4000000     0.4 0.2000000 0.2000000 0.2000000
#> appeal  0.5000000 1.0000000     0.5 0.5000000 0.3333333 0.5000000
#> apparel 0.5714286 0.5714286     1.0 0.4285714 0.2857143 0.4285714
#> peel    0.0000000 0.2500000     0.0 1.0000000 0.7500000 0.5000000
#> peer    0.0000000 0.0000000     0.0 0.7500000 1.0000000 0.7500000
#> pear    0.0000000 0.2500000     0.0 0.5000000 0.7500000 1.0000000

If you want to get this into a tidy format, you could do the following:

library(tidyverse)
stringdist::stringsimmatrix(sample, method = "lv", useNames = "strings") %>%
  as.matrix() %>%
  as_tibble(rownames = "word1") %>%
  pivot_longer(-word1, names_to = "word2", values_to = "distance")
#> # A tibble: 36 x 3
#>    word1  word2   distance
#>    <chr>  <chr>      <dbl>
#>  1 apple  apple      1
#>  2 apple  appeal     0.4
#>  3 apple  apparel    0.4
#>  4 apple  peel       0.200
#>  5 apple  peer       0.200
#>  6 apple  pear       0.200
#>  7 appeal apple      0.5
#>  8 appeal appeal     1
#>  9 appeal apparel    0.5
#> 10 appeal peel       0.5
#> # ... with 26 more rows


问:
Why does sklearn preprocessing LabelEncoder inverse_transform apply from only one column?
I have a random forest model built with sklearn. The model is built in one file, and I have a second file where I use joblib to load the model and apply it to new data. The data has categorical fields that are converted via sklearn's preprocessing LabelEncoder.fit_transform. Once the prediction is made, I am attempting to reverse this conversion with LabelEncoder.inverse_transform.

Here is the code:

```<code> #transform the categorical rf inputs
 df["method"] = le.fit_transform(df["method"])
 df["vendor"] = le.fit_transform(df["vendor"])
 df["type"] = le.fit_transform(df["type"])
 df["name"] = le.fit_transform(df["name"])
 dups["address"] = le.fit_transform(df["address"])

 #designate inputs for rf model
 inputs = ["amt","vendor","type","name","address","method"]

 #load rf model and run it on new data
 from sklearn.externals import joblib
 rf = joblib.load('rf.pkl')
 predict = rf.predict(df[inputs])

 #reverse LabelEncoder fit_transform
 df["method"] = le.inverse_transform(df["method"])
 df["vendor"] = le.inverse_transform(df["vendor"])
 df["type"] = le.inverse_transform(df["type"])
 df["name"] = le.inverse_transform(df["name"])
 df["address"] = le.inverse_transform(df["address"])

 #convert target to numeric to make it play nice with SQL Server
 predict = pd.to_numeric(predict)

 #add target field to df
 df["prediction"] = predict

 #write results to SQL Server table
 import sqlalchemy
 engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@UserDSN")
 df.to_sql('TABLE_NAME', engine, schema='SCHEMANAME', if_exists='replace', index=False)
</code>```

Without the inverse_transform piece, the results are as expected: numeric codes in place of categorical values. With the inverse_transform piece, the results are odd: the categorical values corresponding to the "address" field are returned for all categorical fields.

So if 1600 Pennsylvania Avenue is encoded as the number 1, all categorical values encoded as the number 1 (regardless of field) now return 1600 Pennsylvania Avenue. Why is inverse_transform picking one column from which to reverse all fit_transform codes?

答:
I know this is an old question, however for everyone who likes convenience:

apply, coupled with lambda can transform multiple/all columns with ease

```<code>df = df.apply(lambda col: le.fit_transform(col))
</code>```

I despise non-aliased, non-dynamic code (you should too) like so, unless really necessary:

```<code> df["method"] = le_method.fit_transform(df["method"])
 df["vendor"] = le_vendor.fit_transform(df["vendor"])
 df["type"] = le_type.fit_transform(df["type"])
 df["name"] = le_name.fit_transform(df["name"])
 df["address"] = le_address.fit_transform(df["address"])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a random forest model built with sklearn. The model is built in one file, and I have a second file where I use joblib to load the model and apply it to new data. The data has categorical fields that are converted via sklearn's preprocessing LabelEncoder.fit_transform. Once the prediction is made, I am attempting to reverse this conversion with LabelEncoder.inverse_transform.

Here is the code:

 #transform the categorical rf inputs
 df["method"] = le.fit_transform(df["method"])
 df["vendor"] = le.fit_transform(df["vendor"])
 df["type"] = le.fit_transform(df["type"])
 df["name"] = le.fit_transform(df["name"])
 dups["address"] = le.fit_transform(df["address"])

 #designate inputs for rf model
 inputs = ["amt","vendor","type","name","address","method"]

 #load rf model and run it on new data
 from sklearn.externals import joblib
 rf = joblib.load('rf.pkl')
 predict = rf.predict(df[inputs])

 #reverse LabelEncoder fit_transform
 df["method"] = le.inverse_transform(df["method"])
 df["vendor"] = le.inverse_transform(df["vendor"])
 df["type"] = le.inverse_transform(df["type"])
 df["name"] = le.inverse_transform(df["name"])
 df["address"] = le.inverse_transform(df["address"])

 #convert target to numeric to make it play nice with SQL Server
 predict = pd.to_numeric(predict)

 #add target field to df
 df["prediction"] = predict

 #write results to SQL Server table
 import sqlalchemy
 engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@UserDSN")
 df.to_sql('TABLE_NAME', engine, schema='SCHEMANAME', if_exists='replace', index=False)

Without the inverse_transform piece, the results are as expected: numeric codes in place of categorical values. With the inverse_transform piece, the results are odd: the categorical values corresponding to the "address" field are returned for all categorical fields.

So if 1600 Pennsylvania Avenue is encoded as the number 1, all categorical values encoded as the number 1 (regardless of field) now return 1600 Pennsylvania Avenue. Why is inverse_transform picking one column from which to reverse all fit_transform codes?

Body:
I know this is an old question, however for everyone who likes convenience:

apply, coupled with lambda can transform multiple/all columns with ease

df = df.apply(lambda col: le.fit_transform(col))

I despise non-aliased, non-dynamic code (you should too) like so, unless really necessary:

 df["method"] = le_method.fit_transform(df["method"])
 df["vendor"] = le_vendor.fit_transform(df["vendor"])
 df["type"] = le_type.fit_transform(df["type"])
 df["name"] = le_name.fit_transform(df["name"])
 df["address"] = le_address.fit_transform(df["address"])


问:
What is the default Precision and Scale for a Number in Oracle?
When creating a column of type NUMBER in Oracle, you have the option of not specifying a precision or scale.  What do these default do if you don't specify them?</p>

答:
Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

```<code>SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79
</code>```

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

OwnerDisplayName: Matt

Body:
Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

OwnerDisplayName: Quassnoi


问:
Choosing dependency version in maven and maven plugin
I have a maven plugin which is using hsqldb 1.8.0.10. In my pom.xml from the plugin, it is declared like this:

```<code><dependency>
    <groupId>hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>1.8.0.10</version>
</dependency>
</code>```

But if I run that plugin from another maven project, and that project has a newer version of hsqldb (for instance 1.9.0), how can I configure my plugin that he will use the newest version of hsqldb, without changing it's pom.xml?

And is it possible to do this the other way around as well? If my other maven project uses hsqldb 1.7.0 (for instance), that he will use the 1.8.0.10 version which is specified in the maven plugin itself?

I hope someone can answer my question.

Kind regards,

Walle

答: use properties place holder for the version, say ${hsqldb.version} then declare in different project pom the version you want to put in it</p>

Body:
I have a maven plugin which is using hsqldb 1.8.0.10. In my pom.xml from the plugin, it is declared like this:

<dependency>
    <groupId>hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>1.8.0.10</version>
</dependency>

But if I run that plugin from another maven project, and that project has a newer version of hsqldb (for instance 1.9.0), how can I configure my plugin that he will use the newest version of hsqldb, without changing it's pom.xml?

And is it possible to do this the other way around as well? If my other maven project uses hsqldb 1.7.0 (for instance), that he will use the 1.8.0.10 version which is specified in the maven plugin itself?

I hope someone can answer my question.

Kind regards,

Walle


问:
How pip manages same packages over different environments for space efficiency
I am using a huge pip environment env1, and I would like to create a new one (env2) that only has one different package, the rest is the same as env1.

Is it necessary to reinstall all packages again in env2?
Will it take the same space in my hard drive as env1 or pip manages automatically the space efficiency via something like symbolic links for same packages over all environments?

My objective is to reduce the space that takes the second environment as much as possible.

Just in case I created the environments with:

```<code>python3 -m venv env1
python3 -m venv env2
</code>```

答:
Is it necessary to reinstall all packages again in env2?

Yes.

Will it take the same space in my hard drive as env1

Yes.

or pip manages automatically the space efficiency

No. There is no way to symlink from other environments because they could be different — different Python versions, different package versions, different compilation flags.

Another problem: how would pip find env1 from env2? pip doesn't track existing environments, they could be anywhere.

Yet another problem: what you gonna do in env env2 if you delete env1? The symlinks in env2 would become dangling.

Short resume: disk space is cheaper than solving major problems from trying to manage space.

Body:
I am using a huge pip environment env1, and I would like to create a new one (env2) that only has one different package, the rest is the same as env1.

Is it necessary to reinstall all packages again in env2?
Will it take the same space in my hard drive as env1 or pip manages automatically the space efficiency via something like symbolic links for same packages over all environments?

My objective is to reduce the space that takes the second environment as much as possible.

Just in case I created the environments with:

python3 -m venv env1
python3 -m venv env2


问:
Is realm query order consistent?
When querying a realm db without explicit ordering can I rely on a given order in the results? Is it insertion order? Primary key? Last updated? Example below:

var results = Realm.All<MyRecord>().Where(i => i.MyProp == "in the wild wild west");
foreach (var result in results)
{
  // do a thing with the record
}
```

I need a consistent order but I would rather not add overhead by "being explicit" with the order as this will add search overhead, so long as realm is consistent in its results (provided no change on the db) I am happy to work with a default order given by realm.

答:
I would not rely on Realm 'natural ordering' for anything. More importantly if data is ever inserted or modified, that ordering goes out the window.

So two things

List properties are guaranteed to preserve their order of insertion.

so you can bank on that. Part of the issue also stems from reading the data back in with no set ordering:

For performance reasons, Results insertion order is not guaranteed to
  be preserved.

Meaning that when you read in results, there's no guaranteed order unless you define it.

Title: Is realm query order consistent?

Body:
When querying a realm db without explicit ordering can I rely on a given order in the results? Is it insertion order? Primary key? Last updated? Example below:

var results = Realm.All<MyRecord>().Where(i => i.MyProp == "in the wild wild west");
foreach (var result in results)
{
  // do a thing with the record
}

I need a consistent order but I would rather not add overhead by "being explicit" with the order as this will add search overhead, so long as realm is consistent in its results (provided no change on the db) I am happy to work with a default order given by realm.


问:
Download folder in python
I try download this zip. I used selenium and requests, but neither of them works and I don't know why.
Thank you for your advice.</p>

```<code>from selenium import webdriver
import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
driver = webdriver.Chrome('drivers\chromedriver.exe')
driver.get(url)

requests.get(url)
</code>```

答:
requests.get() downloads the entity into memory. This needs to be explicitly written to a file using open.

Example:

```<code>import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
filename = 'c:/users/user/downloads/csv.zip'

filebody = requests.get(url)
open(filename, 'wb').write(filebody.content)
</code>```

Title: Download folder in python

Body:
I try download this zip. I used selenium and requests, but neither of them works and I don't know why.
Thank you for your advice.

from selenium import webdriver
import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
driver = webdriver.Chrome('drivers\chromedriver.exe')
driver.get(url)

requests.get(url)

Body:
requests.get() downloads the entity into memory. This needs to be explicitly written to a file using open.

Example:

import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
filename = 'c:/users/user/downloads/csv.zip'

filebody = requests.get(url)
open(filename, 'wb').write(filebody.content)


问:
Why is this query taking so long?
This query is appearing in my slow log on a mysql system,

```<code># Query_time: 37  Lock_time: 0  Rows_sent: 5  Rows_examined: 405199
select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created,
application_price.retail_price, euroapps.count FROM application_price INNER JOIN
euroapps ON euroapps.id = application_price.application_id WHERE
application_price.storefront_id = '143441' AND application_price.retail_price <= 0
ORDER BY created DESC LIMIT 5;
</code>```

You see it examines 405,199 rows, could that be the cause of the long query time?

A similar query never shows up in my slow log, that query is:

```<code>select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created,
application_price.retail_price, euroapps.count FROM application_price INNER JOIN
euroapps ON euroapps.id = application_price.application_id WHERE
application_price.storefront_id = '$store' AND application_price.retail_price > 0
ORDER BY created DESC LIMIT 5
</code>```

Here is the output of explain:

```<code>mysql> explain select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created, application_price.retail_price, euroapps.count FROM application_price INNER JOIN euroapps ON euroapps.id = application_price.application_id WHERE application_price.storefront_id = '143441' AND application_price.retail_price <= 0 ORDER BY created DESC LIMIT 5;
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
| id | select_type | table             | type   | possible_keys                    | key                      | key_len | ref                                         | rows   | Extra                                                     |
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
|  1 | SIMPLE      | application_price | range  | PRIMARY,idx_storedfront_price_id | idx_storedfront_price_id | 9       | NULL                                        | 110491 | Using where; Using index; Using temporary; Using filesort |
|  1 | SIMPLE      | euroapps          | eq_ref | PRIMARY                          | PRIMARY                  | 4       | itunesapps.application_price.application_id |      1 |                                                           |
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)
</code>```

答:
You ought to look at the execution plan, that will help narrow down the cause.
http://dev.mysql.com/doc/refman/5.5/en/execution-plan-information.html</p>

Title: Why is this query taking so long?

Body:
This query is appearing in my slow log on a mysql system,

# Query_time: 37  Lock_time: 0  Rows_sent: 5  Rows_examined: 405199
select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created,
application_price.retail_price, euroapps.count FROM application_price INNER JOIN
euroapps ON euroapps.id = application_price.application_id WHERE
application_price.storefront_id = '143441' AND application_price.retail_price <= 0
ORDER BY created DESC LIMIT 5;

You see it examines 405,199 rows, could that be the cause of the long query time?

A similar query never shows up in my slow log, that query is:

select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created,
application_price.retail_price, euroapps.count FROM application_price INNER JOIN
euroapps ON euroapps.id = application_price.application_id WHERE
application_price.storefront_id = '$store' AND application_price.retail_price > 0
ORDER BY created DESC LIMIT 5

Here is the output of explain:

mysql> explain select euroapps.id, euroapps.name, euroapps.imageurl, euroapps.created, application_price.retail_price, euroapps.count FROM application_price INNER JOIN euroapps ON euroapps.id = application_price.application_id WHERE application_price.storefront_id = '143441' AND application_price.retail_price <= 0 ORDER BY created DESC LIMIT 5;
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
| id | select_type | table             | type   | possible_keys                    | key                      | key_len | ref                                         | rows   | Extra                                                     |
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
|  1 | SIMPLE      | application_price | range  | PRIMARY,idx_storedfront_price_id | idx_storedfront_price_id | 9       | NULL                                        | 110491 | Using where; Using index; Using temporary; Using filesort |
|  1 | SIMPLE      | euroapps          | eq_ref | PRIMARY                          | PRIMARY                  | 4       | itunesapps.application_price.application_id |      1 |                                                           |
+----+-------------+-------------------+--------+----------------------------------+--------------------------+---------+---------------------------------------------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)


问:
shared_ptrs being deleted twice
I want to store shared pointers to the Object class in a vector:

Test code:

```<code>#include <vector>
#include <iostream>
#include <memory>

using namespace std;   // only for brevity

class Object
{
public:
  int n;
  Object(int n) : n(n) { cout << "Object("  << n <<")\n"; }
  ~Object() { cout << "~Object(" << n << "))\n"; n = 0xdddddddd; }

};

void Test()
{
  std::shared_ptr<Object> p1(make_shared<Object>(Object(123)));
  std::vector<shared_ptr<Object>> v;

  cout << "before push_back\n";
  v.push_back(std::make_shared<Object>(Object(2)));
  v.push_back(p1);
  cout << "after push_back\n";

  cout << "Vector content:\n";
  for (auto& p : v)
    cout << "  " << p->n << "\n"; ;
}

int main()
{
  Test();
  cout << "after Test()\n";
}
</code>```

The output is

```<code>Object(123)
~Object(123))        <<< why is the destructor called here?
before push_back
Object(2)
~Object(2))          <<< why is the destructor called here?
after push_back
Vector content:
  2
  123
~Object(2))          <<< destructor called again
~Object(123))
after Test()
</code>```

I don't understand why the destructors are called twice.

OTOH the vector content is what I want.

答:
I don't understand why the destructors are called twice.

Because of creating unnecessary temporary objects here:

std::shared_ptr<Object> p1(make_shared<Object>(Object(123)));
                                               ^^^
                                               temporary object
```

<p>and here:</p>

<pre class="lang-cpp prettyprint-override"><code>v.push_back(std::make_shared<Object>(Object(2)));
                                     ^^^
                                     temporary object
</code>```

It should instead be

std::shared_ptr<Object> p1(make_shared<Object>(123));
```

<p>and</p>

<pre class="lang-cpp prettyprint-override"><code>v.push_back(std::make_shared<Object>(2));
</code>```

Why?

Because std::make_shared constructs an object of type T and wraps it in a std::shared_ptr using args as the parameter list for the constructor of T. And in your code, you are making one extra object which immediately gets destroyed, thus calling the destructor.

Why don't you see Object(int n); constructor being called for temporary object?

Object(int n); constructor is indeed being called for the temporary object, but since the object held by the std::shared_ptr is created through copy constructor (so, by copying the temporary object) you won't see call to Object(int n); for it but call to Object(Object const& other);.

In the demo, you can see first Object(int n); constructor being called for the temporary object and then the call to copy constructor Object(Object const& other); for the actual object being referenced by the std::shared_ptr.

Title: shared_ptrs being deleted twice

Body:
I want to store shared pointers to the Object class in a vector:

Test code:

#include <vector>
#include <iostream>
#include <memory>

using namespace std;   // only for brevity

class Object
{
public:
  int n;
  Object(int n) : n(n) { cout << "Object("  << n <<")\n"; }
  ~Object() { cout << "~Object(" << n << "))\n"; n = 0xdddddddd; }

};

void Test()
{
  std::shared_ptr<Object> p1(make_shared<Object>(Object(123)));
  std::vector<shared_ptr<Object>> v;

  cout << "before push_back\n";
  v.push_back(std::make_shared<Object>(Object(2)));
  v.push_back(p1);
  cout << "after push_back\n";

  cout << "Vector content:\n";
  for (auto& p : v)
    cout << "  " <
n << "\n"; ;
}

int main()
{
  Test();
  cout << "after Test()\n";
}

The output is

Object(123)
~Object(123))        <<< why is the destructor called here?
before push_back
Object(2)
~Object(2))          <<< why is the destructor called here?
after push_back
Vector content:
  2
  123
~Object(2))          <<< destructor called again
~Object(123))
after Test()

I don't understand why the destructors are called twice.

OTOH the vector content is what I want.

Body:
I don't understand why the destructors are called twice.

Because of creating unnecessary temporary objects here:

std::shared_ptr<Object> p1(make_shared<Object>(Object(123)));
                                               ^^^
                                               temporary object

and here:

v.push_back(std::make_shared<Object>(Object(2)));
                                     ^^^
                                     temporary object

It should instead be

std::shared_ptr<Object> p1(make_shared<Object>(123));

and

v.push_back(std::make_shared<Object>(2));

Why?

Because std::make_shared constructs an object of type T and wraps it in a std::shared_ptr using args as the parameter list for the constructor of T. And in your code, you are making one extra object which immediately gets destroyed, thus calling the destructor.

Why don't you see Object(int n); constructor being called for temporary object?

Object(int n); constructor is indeed being called for the temporary object, but since the object held by the std::shared_ptr is created through copy constructor (so, by copying the temporary object) you won't see call to Object(int n); for it but call to Object(Object const& other);.

In the <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tLgDZSW9ABk8tTADljAI0zEunUgAdUCwuto9QxNzb19/Olt7JyNXd05PJRU1OgYCZmICIONTAGZFZUxVALSMgijHFzcPRXTM7JD8hTryu0rY6oSASkVUA2JkDgByKVy7ZEMsAGpxXJ0ANyKiYlnscQAGAEFR8cnMGbn1ZuJMZiNVje3JMdoJg2nZnSNMIxIATwuty4M/USnaM6YBReZiDKbNdCzWRfLYTZgKBRTADyzj4S0u4gA7NDNl4DM5WHhkCBLlMpnYCP8oaTkailhAKf8ulMQP8ILRmVjpFM0AZKY9HjNJJIUWjVBApJIyQK5v8DjoBcKuuIAKw6WiSqEzTEAERpovpBtUPLozSkZimqAICDczNZtAgVptxAAdBztdzefy5oLJUbKU63BLhdKfbLaPLFZJlWqNcKtVi9VsyQA/f0QTnYk18yOyyVpuniyW5nRymWlyVdGPqzW5bkR2Y6qbrAAe6HbHfbCd1GK%2BPbrvc281QeHQUwAKkCCBmMdiaRCQCAFAgMph0AB9LwEFZzf2rKZeTgQIzMADWmHXy9XkN3hYIqwg6c41yryoHyfBBHQi8WqhIjyvE4Ny3HcdD3XI1ggqZ5mpGFNjJL0SyFSRXBoE4Dx%2BBB12cUFT1VGt43feDoJdPFl2w3CIAXEAT3PS8VyAx5wOwR87wgaMq1g4j5lIzCKOQU8IEPN8cQQvpvQVPNhWYKgCDcDDyJwgT8LjSQuJpRDy2QgA1JYSBNegtAIElY1rUSpjQqYIGYPlUHNA8WWg5UPzEnMtOLZCkK8ABaVYGzDCt41MwjuXUns4MZE87BnPtzMnZoZyI1yJN9aTZPk%2BLp2rVSwp1IYelYEAhhVIZSFMIZ1lK1AioVGQ5HBPoBn2UZOFK4yKvynpTxAFVJBdMxckxdZMRVTFOAADnWTgVTMWahCK7hSvKyrSGqoZSoUEB1lIdrKp6OBYBgRAUFQIwvDwdgyAoCA0DOi7qmABQAS8ZcrVIKgLrk4hNogZwipW5w7AyN4ita0hbueegkVoVgQY60gsBPUR2H%2B0r8BOYpFk2%2BHMBbIo%2BWGFaKWUVGhDwZxiGBvQsFBtriDwIxaZ6Gh6CYNgOB4fhBGEUQUDkOQyecTbIB6VAtwCbHvIhRsJDqmQEg2wpig0CArAaUxPCsCoYjiQQfD8FJAn0HI9fCQ3taqeICmSEoWnVwQkiWW2ygtjoreaMp7cSFpXd1zgegURrBi4AqipKsrSbWltxrMbyzG4KZgGQZArO3AxaFPZkIFwQh9Ja0gpj0O7LqFXJ/cL/mZDa1Gq1IbrBpdFV5qGRbSEZlVtuWqqio2radpr0gDuO8S8QIchKFu87LsENdc6tlnGBYFHOYAd0prwmeb8Ou9WoqWqmFfCAQKZo9j%2BPE%2BT1PiHTzPq462ubWYLB3AzZvW/bzvI57xQ%2B92zq65ANwTELpchmEkAATkkNwSQ41ODgPGtwXIuReCFSGLkJaX91r93vqHIYkgMHwzWnfPaPRFjfQCIAoAA%3D" rel="nofollow noreferrer">demo, you can see first Object(int n); constructor being called for the temporary object and then the call to copy constructor Object(Object const& other); for the actual object being referenced by the std::shared_ptr.


问:
How do I handle process recreation in android when application startup relies on a network call?
Say I have a custom application in class in my Android app that makes a network call, asynchronously, on startup.  Then I have a Main activity that needs the results of the network call on startup.  I can handle this with a Splash activity that waits on app startup. But when the process is recreated, we go straight to the Main activity, which expects the results of the network call to be there, and it crashes.

See the code below for an example.

What's the best way to handle this?  I want to keep the splash screen for normal startup situations.  But in the second situation, where the app is recreated, I'm not sure how to handle it.  Is there a way to show the splash screen again, and wait, before returning to the recreated Main activity?

class MyApplication : Application() {

    private val scope = CoroutineScope(Dispatchers.Main)

    companion object {
        lateinit var version: Integer
        var startupFinishedListener: (() -> Unit)? = null
    }

    override fun onCreate() {
        super.onCreate()
        scope.launch {
            version = getVersionFromNetwork() //Fake suspending network call
            startupFinishedListener?.invoke()
        }
    }
}
```

<pre class="lang-kotlin prettyprint-override"><code>class SplashScreen : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.splash)
        MyApplication.startupFinishedListener = {
            startMainActivity()
        }
    }

    fun startMainActivity() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }
}
</code>```

class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)

        //This line will crash if we are coming from an activity recreation
        Timber.d("Version is: ${MyApplication.version}")
    }
}
```

I would prefer not to solve this by doing work in onResume in all of my activities instead of onCreate().  Ideally I could tell Android to launch my Splash activity before it launches the restored activity.

答:
"This looks like an Architectural Problem."

Calling an API into application class and registering it's listener to your activities is a bad idea!

There are few options for you to handle your requirement:

If the data you want is really that important in MainActivity, you can call the API in MainActivity onCreate() itself with some loading indicator before your actual data is loaded.

What will happen if process restarts in this case?

Your MainActivity will recreate and call the API again. So, you're good.

If you're required to have that data as soon as your MainActivity starts, without waiting, you need to do caching. Call your API in splash activity and save the data to a file, shared preference or database. Then access cached data in your MainActivity.

What will happen if process restarts in this case?

Since you've already cached your data into a persitent storage, it'll be there even after process restart. So, you're good to get your data back.

Bonus

If you don't want to use your cached data everytime you open your app, just clear the cache in your SplashActivity and call the API everytime to have the latest data with you before moving to MainActivity.

Body:
Say I have a custom application in class in my Android app that makes a network call, asynchronously, on startup.  Then I have a Main activity that needs the results of the network call on startup.  I can handle this with a Splash activity that waits on app startup. But when the process is recreated, we go straight to the Main activity, which expects the results of the network call to be there, and it crashes.

See the code below for an example.

What's the best way to handle this?  I want to keep the splash screen for normal startup situations.  But in the second situation, where the app is recreated, I'm not sure how to handle it.  Is there a way to show the splash screen again, and wait, before returning to the recreated Main activity?

class MyApplication : Application() {

    private val scope = CoroutineScope(Dispatchers.Main)

    companion object {
        lateinit var version: Integer
        var startupFinishedListener: (() -> Unit)? = null
    }

    override fun onCreate() {
        super.onCreate()
        scope.launch {
            version = getVersionFromNetwork() //Fake suspending network call
            startupFinishedListener?.invoke()
        }
    }
}

class SplashScreen : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.splash)
        MyApplication.startupFinishedListener = {
            startMainActivity()
        }
    }

    fun startMainActivity() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }
}

class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)

        //This line will crash if we are coming from an activity recreation
        Timber.d("Version is: ${MyApplication.version}")
    }
}

I would prefer not to solve this by doing work in onResume in all of my activities instead of onCreate().  Ideally I could tell Android to launch my Splash activity before it launches the restored activity.


问:
How to return value from function which has Observable subscription inside?
I dont know how to extract value from Observable to be returned by function in which Observable is present. I need just a value from it to be returned, nothing else.

Current version which works

```<code>function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            console.log(data)
        }
    )
}
getValueFromObservable()
</code>```

I need this to work, function to return value, and then:

```<code>function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())
</code>```

What am I doing wrong here?

答:
```<code>function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())
</code>```

In above case console.log runs before the promise is resolved so no value is displayed, change it to following

```<code>function getValueFromObservable() {
    return this.store
}

getValueFromObservable()
 .subscribe((data: any) => {
    // do something here with data
    console.log(data);
});
</code>```

other solution is when you need data inside getValueFromObservable to return the observable using of operator and subscribe to the function.

```<code> function getValueFromObservable() {
        return this.store.subscribe((data: any) => {
            // do something with data here
            console.log(data);
            //return again observable.
            return of(data);
       })
    }

    getValueFromObservable()
     .subscribe((data: any) => {
        // do something here with data
        console.log(data);
    });
</code>```

Body:
I dont know how to extract value from Observable to be returned by function in which Observable is present. I need just a value from it to be returned, nothing else.

Current version which works

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            console.log(data)
        }
    )
}
getValueFromObservable()

I need this to work, function to return value, and then:

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())

What am I doing wrong here?

Body:
function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())

In above case console.log runs before the promise is resolved so no value is displayed, change it to following

function getValueFromObservable() {
    return this.store
}

getValueFromObservable()
 .subscribe((data: any) => {
    // do something here with data
    console.log(data);
});

other solution is when you need data inside getValueFromObservable to return the observable using of operator and subscribe to the function.

 function getValueFromObservable() {
        return this.store.subscribe((data: any) => {
            // do something with data here
            console.log(data);
            //return again observable.
            return of(data);
       })
    }

    getValueFromObservable()
     .subscribe((data: any) => {
        // do something here with data
        console.log(data);
    });


问:
Why setState(hook) in function component cause an infinite loop?
Here is the code:

import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  setA(2)
  return (

{a}

  );
}
```

Error. Too many re-renders. React limits the number of renders to prevent an infinite loop.

Why it can cause an infinite loop?

I think the reason is that function component just as a render function, so it will cause infinite loop when setState in render functions.

Is there any official explanation?

答:
On each state update React will re-render the component and run all the function body, as the  setA(2) is not enclosed in any hook or function and is a part of the function/component body. React will execute this on each render cycle. This make an infinite loop.

On Component mount React will set the state and go for the component update as the state updated, again there is state update React will again re-render the component. This cycle will continue until react reaches  the re-render limit.

You could avoid this by wrap the state update in hook.

```<code>import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  useEffect(() => {
    setA(2)
  },[]);

  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}

</code>```

Body:
Here is the code:

import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  setA(2)
  return (

{a}

  );
}

Error. Too many re-renders. React limits the number of renders to prevent an infinite loop.

Why it can cause an infinite loop?

I think the reason is that function component just as a render function, so it will cause infinite loop when setState in render functions.

Is there any official explanation?

Body:
On each state update React will re-render the component and run all the function body, as the  setA(2) is not enclosed in any hook or function and is a part of the function/component body. React will execute this on each render cycle. This make an infinite loop.

On Component mount React will set the state and go for the component update as the state updated, again there is state update React will again re-render the component. This cycle will continue until react reaches  the re-render limit.

You could avoid this by wrap the state update in hook.

import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  useEffect(() => {
    setA(2)
  },[]);

  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}


问:
Method to change self-closing tags to explicit tags in Javascript?
Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript?
For example:

```<code><span class="label"/>
</code>```

converted to :

```<code><span class ="label"></span>
</code>```

I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.

And this html is in a string

In fact, I don't want to parse HTML, I just want to find the ""and replace it with ""

答:
Thanks all, I finally use the silly method to change the self-closing tags, maybe it'll help someone like me:

```<code>var splitSpan = textHTML.split(">");
var i=0;
for(i=0;i<splitSpan.length-1;i++){
    var lengthSpan = splitSpan[i].length;
    var subSpan = splitSpan[i].substring(1,5);
    var endSpan = splitSpan[i].charAt(lengthSpan-1);

    if(subSpan=="span" && endSpan=="/")
    {
        splitSpan[i]=setCharAt(splitSpan[i],lengthSpan-1,'>');
        splitSpan[i]=splitSpan[i]+"</span>";
    }
    else
    {
        splitSpan[i]=splitSpan[i]+">";
    }
}
</code>```

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}
```

Body:
Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript?
For example:

converted to :

I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.

And this html is in a string

In fact, I don't want to parse HTML, I just want to find the ""and replace it with ""

Body:
Thanks all, I finally use the silly method to change the self-closing tags, maybe it'll help someone like me:

var splitSpan = textHTML.split(">");
var i=0;
for(i=0;i<splitSpan.length-1;i++){
    var lengthSpan = splitSpan[i].length;
    var subSpan = splitSpan[i].substring(1,5);
    var endSpan = splitSpan[i].charAt(lengthSpan-1);

    if(subSpan=="span" && endSpan=="/")
    {
        splitSpan[i]=setCharAt(splitSpan[i],lengthSpan-1,'>');
        splitSpan[i]=splitSpan[i]+"</span>";
    }
    else
    {
        splitSpan[i]=splitSpan[i]+">";
    }
}

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}


问:
Django CSRF Cookie Not Set
I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the code below:

views.py:

def deposit(request, account_num):
    if request.method == 'POST':
        account = get_object_or_404(account_info, acct_number=account_num)
        form_ = AccountForm(request.POST or None, instance=account)
        form = BalanceForm(request.POST)
        info = str(account_info.objects.filter(acct_number=account_num))
        inf = info.split()

        if form.is_valid():

            # cd=form.cleaned_data
            now = datetime.datetime.now()
            cmodel = form.save()
            cmodel.acct_number = account_num

            # RepresentsInt(cmodel.acct_number)
            cmodel.bal_change = "%0.2f" % float(cmodel.bal_change)
            cmodel.total_balance = "%0.2f" % (float(inf[1]) + float(cmodel.bal_change))
            account.balance = "%0.2f" % float(cmodel.total_balance)
            cmodel.total_balance = "%0.2f" % float(cmodel.total_balance)

            # cmodel.bal_change=cmodel.bal_change
            cmodel.issued = now.strftime("%m/%d/%y %I:%M:%S %p")
            account.recent_change = cmodel.issued
            cmodel.save()
            account.save()

            return HttpResponseRedirect("/history/" + account_num + "/")

        else:
            return render_to_response('history.html',
                                      {'account_form': form},
                                      context_instance=RequestContext(request))

```
<p>Template file:</p>
<pre class="lang-html prettyprint-override"><code><form action="/deposit/{{ account_num }}/" method="post">
    <table>
        <tr>
            {{ account_form.bal_change }}

            <input type="submit" value="Deposit"/>
        </tr>
        {% csrf_token %}
    </table>
</form>
</code>```

I'n stuck, I already cleared the cookie, used other browser but still csrf cookie not set.

答:
If you're using DRF, check if your urlpatterns are correct, maybe you forgot .as_view():

So that how mine code looked like:

```<code>urlpatterns += path('resource', ResourceView)
</code>```

And that's how it should like:

```<code>urlpatterns += path('resource', ResourceView.as_view())
</code>```

Title: Django CSRF Cookie Not Set

Body:
I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the code below:

views.py:

def deposit(request, account_num):
    if request.method == 'POST':
        account = get_object_or_404(account_info, acct_number=account_num)
        form_ = AccountForm(request.POST or None, instance=account)
        form = BalanceForm(request.POST)
        info = str(account_info.objects.filter(acct_number=account_num))
        inf = info.split()

        if form.is_valid():

            # cd=form.cleaned_data
            now = datetime.datetime.now()
            cmodel = form.save()
            cmodel.acct_number = account_num

            # RepresentsInt(cmodel.acct_number)
            cmodel.bal_change = "%0.2f" % float(cmodel.bal_change)
            cmodel.total_balance = "%0.2f" % (float(inf[1]) + float(cmodel.bal_change))
            account.balance = "%0.2f" % float(cmodel.total_balance)
            cmodel.total_balance = "%0.2f" % float(cmodel.total_balance)

            # cmodel.bal_change=cmodel.bal_change
            cmodel.issued = now.strftime("%m/%d/%y %I:%M:%S %p")
            account.recent_change = cmodel.issued
            cmodel.save()
            account.save()

            return HttpResponseRedirect("/history/" + account_num + "/")

        else:
            return render_to_response('history.html',
                                      {'account_form': form},
                                      context_instance=RequestContext(request))

Template file:

<form action="/deposit/{{ account_num }}/" method="post">

            {{ account_form.bal_change }}

            <input type="submit" value="Deposit"/>

        {% csrf_token %}

</form>

I'n stuck, I already cleared the cookie, used other browser but still csrf cookie not set.

Body:
If you're using DRF, check if your urlpatterns are correct, maybe you forgot .as_view():

So that how mine code looked like:

urlpatterns += path('resource', ResourceView)

And that's how it should like:

urlpatterns += path('resource', ResourceView.as_view())


问:
Confused with the idea of informatica
I know that Informatica is a software that extract data from data sources (database or flat file) and convert them to the same data types respectively so it will be easier for the source definition to map and load data to the target definition (database or flat file). What if the source definition and the target definition are loaded with different tables like (Like tables without the same columns) will it still work?

I have a few questions regarding to informatica..

Informatica :

```<code> Source Definition - Upload data from a flat file or data from tables in the database
 Source Qualifier - It is normally created with the source definition which is to be used to manipulate the imported data to match with the data type in informatica, which later to be linked with the target definition.
 Target Definition - It is created to store the only filtered columns needed for the target structure.
</code>```

答:
Short answer: YES

```<code>That is why we have Informatica. To transform data from different sources to be transfered to different targets.
e.g.
from file to oracle_db.
from oracle_db to mysql. etc
from oracle_db to csv file and to email attachment etc
</code>```

Example: Data from different sources to one target

Title: Confused with the idea of informatica

Body:
I know that Informatica is a software that extract data from data sources (database or flat file) and convert them to the same data types respectively so it will be easier for the source definition to map and load data to the target definition (database or flat file). What if the source definition and the target definition are loaded with different tables like (Like tables without the same columns) will it still work?

I have a few questions regarding to informatica..

Informatica :

 Source Definition - Upload data from a flat file or data from tables in the database
 Source Qualifier - It is normally created with the source definition which is to be used to manipulate the imported data to match with the data type in informatica, which later to be linked with the target definition.
 Target Definition - It is created to store the only filtered columns needed for the target structure.

Body:
Short answer: YES

That is why we have Informatica. To transform data from different sources to be transfered to different targets.
e.g.
from file to oracle_db.
from oracle_db to mysql. etc
from oracle_db to csv file and to email attachment etc

Example: Data from different sources to one target


答:
This is because you have to destroy the temporary values.

The std::make_shared function takes any amount of parameter and construct a value of the given type with it.

You construct a Object and pass it to std::make_shared, which in its turn construct a value using new. Then, the temporaries are destroyed. Later, the shared pointers also are destroyed.

Simply change this in your code:

```<code>std::shared_ptr<Object> p1(make_shared<Object>(123));

// ...

v.push_back(std::make_shared<Object>(2));
</code>```

And you'll see only one destructor for each values.

Title: shared_ptrs being deleted twice

Body:
This is because you have to destroy the temporary values.

The std::make_shared function takes any amount of parameter and construct a value of the given type with it.

You construct a Object and pass it to std::make_shared, which in its turn construct a value using new. Then, the temporaries are destroyed. Later, the shared pointers also are destroyed.

Simply change this in your code:

std::shared_ptr<Object> p1(make_shared<Object>(123));

// ...

v.push_back(std::make_shared<Object>(2));

And you'll see only one destructor for each values.


问:
Alignment in textflow
I'm placing a textflow with UTF-16 text in PHP (PDF_create_textflow,PDF_fit_textflow) which works fine.

How do I get justified Text "" without seeing the BOM sign (Up Arrow) in the Document?

Any other way I could style text justified rather than with inline option alignment?

```<code>$compo_txt = html_entity_decode($compo_txt, ENT_QUOTES, 'UTF-8');
$compo_txt = "<alignment=justify>".$compo_txt;
$compo_txt = iconv("UTF-8", "UTF-16", $compo_txt);
$len = strlen($compo_txt);
$compo_flow = PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true");

$flow_warning = PDF_fit_textflow(
    $p, $compo_flow, $compo_x + $compo_w,
    $compo_y, $compo_x, $compo_y - $compo_h,
    'orientate=' . $compo_o
);
</code>```

答:
alignment work of course as inline option, but due to the used textlen option, this will not work in your case.

Textlen is explained in the PDFlib 9.2.0 API reference with the following words:

(Integer or keyword; required for text fragments with fixedtextformat=false and textformat=utf16xx in non-Unicode aware languages) Number of bytes or (in Unicode-capable languages) characters before the next inline option list (see »Inline option lists for Textflows«, page 103).

(I added the bold highlighting)

As you specify as textlen the length of the complete textstring, no inline option will be processed.

The main question: Why do you use textformat=utf16? Why not just use textformat=utf8 (or stringformat=utf8) if you already have utf8 strings? And you can also use option charref, so that character references are processed.

When you set stringformat=utf8 and charref=true (see PDFlib 9.2 Tutorial, chapter "5.2.2 Language Bindings with UTF-8 Support") you can use the simplify your code:

PDF_set_option($p, "stringformat=utf8 charref=true");

$compo_txt = "<alignment=justify>".$compo_txt;
$compo_flow = PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode embedding=true");

$flow_warning = PDF_fit_textflow(
    $p, $compo_flow, $compo_x + $compo_w,
    $compo_y, $compo_x, $compo_y - $compo_h,
    'orientate=' . $compo_o
);
```

Title: Alignment in textflow

Body:
I'm placing a textflow with UTF-16 text in PHP (PDF_create_textflow,PDF_fit_textflow) which works fine.

How do I get justified Text "" without seeing the BOM sign (Up Arrow) in the Document?

Any other way I could style text justified rather than with inline option alignment?

$compo_txt = html_entity_decode($compo_txt, ENT_QUOTES, 'UTF-8');
$compo_txt = "<alignment=justify>".$compo_txt;
$compo_txt = iconv("UTF-8", "UTF-16", $compo_txt);
$len = strlen($compo_txt);
$compo_flow = PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true");

$flow_warning = PDF_fit_textflow(
    $p, $compo_flow, $compo_x + $compo_w,
    $compo_y, $compo_x, $compo_y - $compo_h,
    'orientate=' . $compo_o
);


答: Because you are setting a new value to the state with setA(2), so each time the component is rendered the state receives a new value, forcing the component to render again

Title: Why setState(hook) in function component cause an infinite loop?


问:
Node child_process trying to use /usr/bin/zsh and failing as it does not exist
Since recently, many npm commands have been failing for me with an error message similar to this one:

```<code>npm ERR! code ELIFECYCLE
npm ERR! syscall spawn /usr/bin/zsh
npm ERR! file /usr/bin/zsh
npm ERR! path /usr/bin/zsh
npm ERR! errno ENOENT
npm ERR! myProj@0.1.0 preinstall: `npm run myCommand`
npm ERR! spawn /usr/bin/zsh ENOENT
npm ERR!
npm ERR! Failed at the myProj@0.1.0 preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
</code>```

So far I have found out, that this error is probably caused by /usr/bin/zsh not existing. zsh is located under /bin/zsh on my system.

The content of the script causing this error is:

```<code>const { exec } = require('child_process');
exec('npm -v', (err, stdout) => {
  if (err) throw err;
  if (parseFloat(stdout) < 5) {
    // NOTE: This can happen if you have a dependency which lists an old version of npm in its own dependencies.
    throw new Error(`[ERROR] You need npm version @>=5 but you have ${stdout}`);
  }
});
</code>```

the verbose stack contains:

```<code>17 verbose stack spawn /usr/bin/zsh ENOENT
17 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
17 verbose stack     at onErrorNT (internal/child_process.js:415:16)
17 verbose stack     at process._tickCallback (internal/process/next_tick.js:63:19)
</code>```

So most likely child_process is trying to call /usr/bin/zsh. But I have no Idea why and how to fix this. Any Ideas?

This problem seems to be similar to this one: Trying to run concurrently (npm ERR! code ELIFECYCLE npm ERR!)

Complete reinstall of node, npm and nvm did not help. The error also occurs when using yarn.

Another debugging problem:

I cannot find internal/child_process.js or internal/process/next_tick.js anywhere.

Edit: I have found out, that this error ocurrs regardless of the script that is being run.

If i run a script npm run x which is defined in package.json as "x"="npm run y". That will fail. But if I run npm run y directly, it works.

答:
I have now overridden two OSX security measures to hacky-fix this issue:

disable SIP (system integrity protocol) by rebooting into recovery (holding CMD + R), opening Utilities -> Terminal, and running csrutil disable

removing the write protection of /usr/bin by running:

sudo mount -uw /
killall Finder

Creating the symlink ln -s /usr/bin/zsh /bin/zsh

Now the error is gone. But its cause and a proper fix is still unknown

Body:
Since recently, many npm commands have been failing for me with an error message similar to this one:

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn /usr/bin/zsh
npm ERR! file /usr/bin/zsh
npm ERR! path /usr/bin/zsh
npm ERR! errno ENOENT
npm ERR! myProj@0.1.0 preinstall: `npm run myCommand`
npm ERR! spawn /usr/bin/zsh ENOENT
npm ERR!
npm ERR! Failed at the myProj@0.1.0 preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

So far I have found out, that this error is probably caused by /usr/bin/zsh not existing. zsh is located under /bin/zsh on my system.

The content of the script causing this error is:

const { exec } = require('child_process');
exec('npm -v', (err, stdout) => {
  if (err) throw err;
  if (parseFloat(stdout) < 5) {
    // NOTE: This can happen if you have a dependency which lists an old version of npm in its own dependencies.
    throw new Error(`[ERROR] You need npm version @>=5 but you have ${stdout}`);
  }
});

the verbose stack contains:

17 verbose stack spawn /usr/bin/zsh ENOENT
17 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
17 verbose stack     at onErrorNT (internal/child_process.js:415:16)
17 verbose stack     at process._tickCallback (internal/process/next_tick.js:63:19)

So most likely child_process is trying to call /usr/bin/zsh. But I have no Idea why and how to fix this. Any Ideas?

This problem seems to be similar to this one: Trying to run concurrently (npm ERR! code ELIFECYCLE npm ERR!)

Complete reinstall of node, npm and nvm did not help. The error also occurs when using yarn.

Another debugging problem:

I cannot find internal/child_process.js or internal/process/next_tick.js anywhere.

Edit: I have found out, that this error ocurrs regardless of the script that is being run.

If i run a script npm run x which is defined in package.json as "x"="npm run y". That will fail. But if I run npm run y directly, it works.


问:
How to detect shake gesture in swiftUI
In apple's documentation, I did not find any gesture related to shake for swiftUI. So how to detect it?

I am very new to swift programming and this question really bothers me for a long time.

In UIKit If I want to detect shake gesture is quite simple and straight forward. In swiftUI, there are bunch of gestures like tap drag rotation, however I cannot find shake gesture in official documentation or anyone who asked. Is this possible in swiftUI to achieve the same result? Or they just forget to add it into the swiftUI framework...

If it's not possible in swiftUI, then how am I going to import the motionEnded function in UIKit to the swiftUI view that I want to detect shake motion?

答:
iOS 13, Swift 5... a solution that works with SwiftUI based in jk2K answer, with this obviously this is in the ContentView.swift file.

```<code>let messagePublisher = PassthroughSubject<String, Never>()

class ContentMode {

...

}

extension UIWindow {
 open override func motionEnded(_ motion: UIEvent.EventSubtype, with event:   UIEvent?) {
    if motion == .motionShake {
        print("Device shaken")
        messagePublisher.send("Stop Shaking Me")
    }
  }
}
</code>```

You can than use this to pick it up in your UI

```<code>.onReceive(messagePublisher) { (message) in
  // message = "Stop Shaking Me"
}
</code>```

Title: How to detect shake gesture in swiftUI

Body:
iOS 13, Swift 5... a solution that works with SwiftUI based in jk2K answer, with this obviously this is in the ContentView.swift file.

let messagePublisher = PassthroughSubject<String, Never>()

class ContentMode {

...

}

extension UIWindow {
 open override func motionEnded(_ motion: UIEvent.EventSubtype, with event:   UIEvent?) {
    if motion == .motionShake {
        print("Device shaken")
        messagePublisher.send("Stop Shaking Me")
    }
  }
}

You can than use this to pick it up in your UI

.onReceive(messagePublisher) { (message) in
  // message = "Stop Shaking Me"
}


问:
Kubernetes-dashboard empty : every resources are forbidden
It seems I have a very common problem but I cannot figure it out.

On a new kubernetes cluster (v1.17) I'm trying to install Kubernetes-dashboard.

For this I followed the official steps, starting by installing the dashboard :

```<code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml
</code>```

Then I created the ServiceAccount

```<code>apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard
</code>```

And the ClusterRoleBinding

```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard
</code>```

Everything is running smoothly and all the objets get created (I can get them and everything looks alright)

After running kubectl proxy the dashboard is accessible at this URL :

```<code>http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/
</code>```

Then I enter the token I got with this command :

```<code>kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user-token | awk '{print $1}')
</code>```

I can login, but the dashboard is empty. The notifications panel is full of

[OBJECT] is forbidden: User "system:serviceaccount:kubernetes-dashboard:admin-user" cannot list resource "[OBJECT]" in API group "extensions" in the namespace "default"

Replace [OBJECT] with every kubernetes object and you have a good overview of my notifications panel ;)

The admin-user has obviously not enough rights to access the objects.

Questions

Did I miss something ?

How can I debug this situation ?

Thank you for your help !

Edit: That was an outage from my cloud provider. I don't know what happened nor how they solved it but they did something and everything is working now.

答:
role binding give this error?

The ClusterRoleBinding "kubernetes-dashboard" is invalid: roleRef: Invalid value: rbac.RoleRef{APIGroup:"rbac.authorization.k8s.io", Kind:"ClusterRole", Name:"cluster-admin"}: cannot change roleRef

Body:
It seems I have a very common problem but I cannot figure it out.

On a new kubernetes cluster (v1.17) I'm trying to install Kubernetes-dashboard.

For this I followed the official steps, starting by installing the dashboard :

kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml

Then I created the ServiceAccount

apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard

And the ClusterRoleBinding

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard

Everything is running smoothly and all the objets get created (I can get them and everything looks alright)

After running kubectl proxy the dashboard is accessible at this URL :

http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

Then I enter the token I got with this command :

kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user-token | awk '{print $1}')

I can login, but the dashboard is empty. The notifications panel is full of

[OBJECT] is forbidden: User "system:serviceaccount:kubernetes-dashboard:admin-user" cannot list resource "[OBJECT]" in API group "extensions" in the namespace "default"

Replace [OBJECT] with every kubernetes object and you have a good overview of my notifications panel ;)

The admin-user has obviously not enough rights to access the objects.

Questions

Did I miss something ?

How can I debug this situation ?

Thank you for your help !

Edit: That was an outage from my cloud provider. I don't know what happened nor how they solved it but they did something and everything is working now.


问:
Elastic search query on indices with some date range
I have below scenario:

I have following indices in elastic search.

index-2016.04.10

index-2016.04.11

index-2016.04.12

index-2016.04.15

index-2016.04.16

index-2016.04.18

Now suppose , I want to search some data in elastic search between dates - 2016.04.11 to 2016.04.16.
My questions are:

Do we have any way to run a single query and define some filter parameters so that the search will happen only in the indices between these two dates ?

If not, then how can we optimize the search query If we need to search the data in some range of indices ?

Java implementation.

Please help..

答:
You can use aliasses and then query to alias like an index.

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-add-alias.html#indices-add-alias


问:
ActiveWorkbook.SaveAs parameter set-up
When I use ActiveWorkbook.SaveAs to overwrite a file the massage window comes up Yes or no.

How can I set up ActiveWorkbook.SaveAs to overwrite the already saved file whithout additional pushing yes or no?

答:
You can turn off the alert using Application.DisplayAlerts property.

When using the SaveAs method for workbooks to overwrite an existing file, the Confirm Save As dialog box has a default of No, while the Yes response is selected by Excel when the DisplayAlerts property is set to False. The Yes response overwrites the existing file.

Don't forget to turn them on again after you turned them off.

```<code>Application.DisplayAlerts = False
ThisWorkbook.SaveAs
Application.DisplayAlerts = True
</code>```

Off Topic

Note that in most cases ActiveWorkbook is not what you need but ThisWorkbook.

ActiveWorkbook is the workbook that has focus / is on top (this can easily change with a single mouse click.

ThisWorkook is the workbook the current VBA code is in (this will never change).

Therefore ThisWorkbook is more reliable. And ActiveWorkbook is rarely needed (eg. if you write an add-in).

Title: ActiveWorkbook.SaveAs parameter set-up

Body:
You can turn off the alert using Application.DisplayAlerts property.

When using the SaveAs method for workbooks to overwrite an existing file, the Confirm Save As dialog box has a default of No, while the Yes response is selected by Excel when the DisplayAlerts property is set to False. The Yes response overwrites the existing file.

Don't forget to turn them on again after you turned them off.

Application.DisplayAlerts = False
ThisWorkbook.SaveAs
Application.DisplayAlerts = True

Off Topic

Note that in most cases ActiveWorkbook is not what you need but ThisWorkbook.

ActiveWorkbook is the workbook that has focus / is on top (this can easily change with a single mouse click.

ThisWorkook is the workbook the current VBA code is in (this will never change).

Therefore ThisWorkbook is more reliable. And ActiveWorkbook is rarely needed (eg. if you write an add-in).


问:
Python removing word if subset of other word in list
A simple puzzle but I cannot wrap my head around it:

In words:
I have a list of words.  If in my list, the word is a "subset" of another value in list, then remove.

```<code>Input:  ['car', 'car-10', 'truck-20']
Output:  ['car-10', 'truck-20']
</code>```

We have removed 'car' because it is a subset of 'car-10'.  'car-10' is not a subset of 'car'

```<code>Input:  ['car', 'car-10', 'car-100']
Output:  ['car-100']
</code>```

We have removed 'car' and 'car-10' because it is a subset of 'car-100'.

The one I am really trying to solve,  don't use numbers:

```<code>Input: ['car-strong', 'car', 'truck-weak']
Output: ['car-strong', 'truck-weak']
</code>```

We might have 'truck', 'bananas', 'apple',  and things would be 'apple-10'.

Note that the "type" (car, truck, apple etc) is always the beginning of the word.

The typical list to parse is around 5-10 elements long.  (brute forceable i guess?)

But there are around 200,000 of these short lists to "clean"... is also the issue.

答:
This is a solution that should work for all kind input formats:</p>

```<code>input = ['car-strong', 'car', 'truck-weak']
delete = []

for idx,str in enumerate(input):
    for idx2,str2 in enumerate(input):
        if str in str2 and idx != idx2:
            delete.append(str)

for str in delete:
    input.remove(str)

print(input)
</code>```

Body:
A simple puzzle but I cannot wrap my head around it:

In words:
I have a list of words.  If in my list, the word is a "subset" of another value in list, then remove.

Input:  ['car', 'car-10', 'truck-20']
Output:  ['car-10', 'truck-20']

We have removed 'car' because it is a subset of 'car-10'.  'car-10' is not a subset of 'car'

Input:  ['car', 'car-10', 'car-100']
Output:  ['car-100']

We have removed 'car' and 'car-10' because it is a subset of 'car-100'.

The one I am really trying to solve,  don't use numbers:

Input: ['car-strong', 'car', 'truck-weak']
Output: ['car-strong', 'truck-weak']

We might have 'truck', 'bananas', 'apple',  and things would be 'apple-10'.

Note that the "type" (car, truck, apple etc) is always the beginning of the word.

The typical list to parse is around 5-10 elements long.  (brute forceable i guess?)

But there are around 200,000 of these short lists to "clean"... is also the issue.

Body:
This is a solution that should work for all kind input formats:

input = ['car-strong', 'car', 'truck-weak']
delete = []

for idx,str in enumerate(input):
    for idx2,str2 in enumerate(input):
        if str in str2 and idx != idx2:
            delete.append(str)

for str in delete:
    input.remove(str)

print(input)


问:
JDK 11+ and Javadoc
```<code>Exit code: 1 - javadoc: error - The code being documented uses packages in the unnamed module, but the packages defined in https://docs.oracle.com/en/java/javase/11/docs/api/ are in named modules.
</code>```

Has anyone been able to make javadoc work without having to change the source version to 1.8 (as suggested in other forums)? I'm using JDK v11.0.5 and the issue still present (also with JDK 12+).

Edit: This error originated from maven and thrown by the maven-javadoc-plugin. I have not been able to make it work for JDK 11+ even with the <source>8</source> configuration.

答:
As suggested in OpenJDK issue tracker this can be worked around with defining source on Javadoc plugin:</p>

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <configuration>
        <source>8</source>
    </configuration>
</plugin>
</code>```

Title: JDK 11+ and Javadoc

Body:
Exit code: 1 - javadoc: error - The code being documented uses packages in the unnamed module, but the packages defined in https://docs.oracle.com/en/java/javase/11/docs/api/ are in named modules.

Has anyone been able to make javadoc work without having to change the source version to 1.8 (as suggested in other forums)? I'm using JDK v11.0.5 and the issue still present (also with JDK 12+).

Edit: This error originated from maven and thrown by the maven-javadoc-plugin. I have not been able to make it work for JDK 11+ even with the <source>8</source> configuration.

Body:
As suggested in OpenJDK issue tracker this can be worked around with defining source on Javadoc plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <configuration>
        <source>8</source>
    </configuration>
</plugin>


问:
How to trigger watch AFTER I read array from db?
In my vue/cli 4/vuex opening page I need to fill select input with default value from

vuex store. To fill select input I need have selection items read from db and I have a problem that watch is triggered
BEFORE I read data from db in mount event.
I do as :

```<code>watch: {
    defaultAdSavedFilters: {
        handler: function (value) {
            console.log('WATCH defaultAdSavedFilters value::')
            console.log(value)
            if (!this.isEmpty(value.title)) {
                this.filter_title = value.title
            }
            if (!this.isEmpty(value.category_id)) {
                this.categoriesLabels.map((nexCategoriesLabel) => { // this.categoriesLabels IS EMPTY
                    if (nexCategoriesLabel.code === value.category_id) {
                        this.selection_filter_category_id = {code: value.category_id, label: nexCategoriesLabel.label};
                    }
                });

            }
        }
    }, //

}, // watch: {

mounted() {
    retrieveAppDictionaries('ads_list', ['ads_per_page', 'categoriesLabels']);  // REQUEST TO DB
    bus.$on('appDictionariesRetrieved', (response) => {
        if (response.request_key === 'ads_list') { // this is triggered AFTER watch
            this.ads_per_page = response.ads_per_page
            this.categoriesLabels = response.categoriesLabels
            // this.$forceUpdate() // IF UNCOMMENT THAT DOES NOT HELP
            Vue.$forceUpdate()  // THAT DOES NOT HELP
        }
    })
    this.loadAds(true)

}, // mounted() {
</code>```

I found this Can you force Vue.js to reload/re-render?
branch and tried some decisions, like

```<code>Vue.$forceUpdate()
</code>```

but that does not work.
If there is a right way to trigger watch defaultAdSavedFilters AFTER I read array from db ?

Modified BLOCK :
I use Vuex actions/mutations when I need to read / keep /use /update data of the logged user, like
defaultAdSavedFilters, which is defined as :

```<code>computed: {
    defaultAdSavedFilters: function () {
        return this.$store.getters.defaultAdSavedFilters
    },
</code>```

Data ads_per_page(used for pagionaion), categoriesLabels(used for selection input items) has nothing to do with
 logged user, that is why I do not use vuex for them, and I use retrieveAppDictionaries method to read them from the db
 and bus to listen to them, which is defined as :

```<code> import {bus} from '@/main'
</code>```

Sure I have data( block :

```<code>export default {
    data() {
        return {
            ...
            ads_per_page: 20,

            categoriesLabels: [],
            ...
        }
    },

"vue": "^2.6.10",
"vue-router": "^3.1.3",
"vuex": "^3.1.2"
</code>```

Thanks!

答:
Please add the data() method from you component. But I'm pretty sure it is NOT triggering because of the way you are assigning the result from the API call.

Try this:

```<code>mounted() {
    retrieveAppDictionaries('ads_list', ['ads_per_page', 'categoriesLabels']);  // REQUEST TO DB
    bus.$on('appDictionariesRetrieved', (response) => {
        if (response.request_key === 'ads_list') { // this is triggered AFTER watch
            this.ads_per_page = [ ...response.ads_per_page ]
            this.categoriesLabels = [ ...response.categoriesLabels ]
        }
    })
    this.loadAds(true)
}
</code>```

However, I don't understand what bus is doing for you and why you are NOT using Vuex actions/mutations

Body:
In my vue/cli 4/vuex opening page I need to fill select input with default value from

vuex store. To fill select input I need have selection items read from db and I have a problem that watch is triggered
BEFORE I read data from db in mount event.
I do as :

watch: {
    defaultAdSavedFilters: {
        handler: function (value) {
            console.log('WATCH defaultAdSavedFilters value::')
            console.log(value)
            if (!this.isEmpty(value.title)) {
                this.filter_title = value.title
            }
            if (!this.isEmpty(value.category_id)) {
                this.categoriesLabels.map((nexCategoriesLabel) => { // this.categoriesLabels IS EMPTY
                    if (nexCategoriesLabel.code === value.category_id) {
                        this.selection_filter_category_id = {code: value.category_id, label: nexCategoriesLabel.label};
                    }
                });

            }
        }
    }, //

}, // watch: {

mounted() {
    retrieveAppDictionaries('ads_list', ['ads_per_page', 'categoriesLabels']);  // REQUEST TO DB
    bus.$on('appDictionariesRetrieved', (response) => {
        if (response.request_key === 'ads_list') { // this is triggered AFTER watch
            this.ads_per_page = response.ads_per_page
            this.categoriesLabels = response.categoriesLabels
            // this.$forceUpdate() // IF UNCOMMENT THAT DOES NOT HELP
            Vue.$forceUpdate()  // THAT DOES NOT HELP
        }
    })
    this.loadAds(true)

}, // mounted() {

I found this Can you force Vue.js to reload/re-render?
branch and tried some decisions, like

Vue.$forceUpdate()

but that does not work.
If there is a right way to trigger watch defaultAdSavedFilters AFTER I read array from db ?

Modified BLOCK :
I use Vuex actions/mutations when I need to read / keep /use /update data of the logged user, like
defaultAdSavedFilters, which is defined as :

computed: {
    defaultAdSavedFilters: function () {
        return this.$store.getters.defaultAdSavedFilters
    },

Data ads_per_page(used for pagionaion), categoriesLabels(used for selection input items) has nothing to do with
 logged user, that is why I do not use vuex for them, and I use retrieveAppDictionaries method to read them from the db
 and bus to listen to them, which is defined as :

 import {bus} from '@/main'

Sure I have data( block :

export default {
    data() {
        return {
            ...
            ads_per_page: 20,

            categoriesLabels: [],
            ...
        }
    },

"vue": "^2.6.10",
"vue-router": "^3.1.3",
"vuex": "^3.1.2"

Thanks!

Body:
Please add the data() method from you component. But I'm pretty sure it is NOT triggering because of the way you are assigning the result from the API call.

Try this:

mounted() {
    retrieveAppDictionaries('ads_list', ['ads_per_page', 'categoriesLabels']);  // REQUEST TO DB
    bus.$on('appDictionariesRetrieved', (response) => {
        if (response.request_key === 'ads_list') { // this is triggered AFTER watch
            this.ads_per_page = [ ...response.ads_per_page ]
            this.categoriesLabels = [ ...response.categoriesLabels ]
        }
    })
    this.loadAds(true)
}

However, I don't understand what bus is doing for you and why you are NOT using Vuex actions/mutations


答:
brute force

```<code>l =['car', 'car-10', 'truck-20']
remove_me = [x for x in l
    if any([y.startswith(x) for y in l if x!=y])]
result = [x for x in l if x not in remove_me]
</code>```

For better performance, order the list alphabetically to find candidate 'superset' faster, e.g. along the lines of

Python: Remove elements from the list which are prefix of other

Title: Python removing word if subset of other word in list

Body:
brute force

l =['car', 'car-10', 'truck-20']
remove_me = [x for x in l
    if any([y.startswith(x) for y in l if x!=y])]
result = [x for x in l if x not in remove_me]

For better performance, order the list alphabetically to find candidate 'superset' faster, e.g. along the lines of

Python: Remove elements from the list which are prefix of other