问:
Merging feature branch based on another feature branch, back to master
As often the case withour team, changes on the next release need to start before the current release is completely tested and merged back into master, from which to start a new branch from for the next release.

So I can create a new feature branch based on the current feature-branch, and start work on the next release there.  The problem is that this sometimes gets messy if one doesnt remember that you actually still have another feature branch or something else changes that lead to merge conflicts.

Something like this.  So in this case, Feature-1 is being tested, but for one reason or another, we wont do a release from here, rather work will continue on Feature-2.  However, notice there is a commit that happened AFTER Feature-2 was created.   So, correct me if Im wrong, but one way to handle this if in fact Feature-1 was NOT going to be released, then ... assuming the head is pointed at /Feature2, will the following get the change from Feature-1 AND then everything back into master?

```<code>git merge Feature-1
git push origin Feature-2
git checkout master
git merge Feature-2
git push origin master
</code>```

答:
If you have one "feature branch" per release, they're not feature branches. (Unless you're doing continuous delivery, in which case you just release master.)

Feature branches should be about a single feature, preferably one that either isn't going to take very long, or isn't going to mess much with other code. Once that feature is done it should be tested, merged, and the branch deleted never to be used again.

Unless you explicitly need something in an incomplete feature branch, don't branch feature branches off other feature branches. With short, sharp feature branches this should rarely be an issue. Even then often it's just a bug fix or refactoring. Try to extract just the bit you need, get that merged, and continue on your way.

If you often find yourself needing to branch off other feature branches, your feature branches are doing too much.

That's your first problem. If you use feature branches correctly, this should be a rare a problem. Doing too much in one branch complicates everything.

Let's sort out how Git does branches. Unlike other version control systems, commits connect to other commits and branches are just labels. Branches have no life of their own. Your situation looks like this.

```<code>                    G - H - I [feature-2]
                   /
          D - E - F - K [feature-1]
         /
A - B - C [master]
</code>```

The kinks are entirely notional. We can also look at it like this.

```<code>                    K [feature-1]
                   /
          D - E - F - G - H - I [feature-2]
         /
A - B - C [master]
</code>```

Looked at this way it should be more clear what is in feature-2. All of master, most of feature-1 (which is untested), and all of feature-2. feature-2 cannot be done until feature-1 is done, and that sort of dependency is undesirable.

If you're working on top of a branch and want to stay up to date, the simplest thing to do is to git rebase upstream-branch. This will rewrite your commits as if they were written on top of the upstream-branch all along. This avoids a bunch of confusing notional merges.

```<code>Before
                    G - H - I [feature-2]
                   /
          D - E - F - K [feature-1]
         /
A - B - C [master]

git checkout feature-2
git rebase feature -1

After
                        G1 - H1 - I1 [feature-2]
                       /
          D - E - F - K [feature-1]
         /
A - B - C [master]
</code>```

feature-2 can then be safely pushed with git rebase --force-with-lease. People can safely update their copy of feature-2 if they pull with rebase, instead of merging. git pull --rebase or setting pull.rebase = merges in your Git config.

Again, this should be rare.

But, as above, feature-2 should probably never have been built on top of feature-1 at all. If they were small and independent features, it would look like this.

```<code>          D - E - F - K [feature-1]
         /
A - B - C [master]
         \
          G - H - I [feature-2]
</code>```

Now you can have multiple independent features being developed and tested simultaneously. When they're done, in any order, they're merged into master and deleted. master is always in a known good state and can be released at any time. Releases are tracked with tags, not branches.

```<code>git checkout master
git merge feature-2
git branch -d feature-2

          D - E - F - K [feature-1]
         /
A - B - C ---------- J [master]
         \         /
          G - H - I
</code>```

That's referred to as a "feature bubble".

Everyone else then rebases their feature branch on top of master to update, deals with any conflicts or breakage, and goes about their business.

```<code>git checkout master
git pull
git checkout feature-1
git rebase master

                       D1 - E1 - F1 - K1 [feature-1]
                      /
A - B - C ---------- J [master]
         \         /
          G - H - I
</code>```

Body:
As often the case withour team, changes on the next release need to start before the current release is completely tested and merged back into master, from which to start a new branch from for the next release.

So I can create a new feature branch based on the current feature-branch, and start work on the next release there.  The problem is that this sometimes gets messy if one doesnt remember that you actually still have another feature branch or something else changes that lead to merge conflicts.

Something like this.  So in this case, Feature-1 is being tested, but for one reason or another, we wont do a release from here, rather work will continue on Feature-2.  However, notice there is a commit that happened AFTER Feature-2 was created.   So, correct me if Im wrong, but one way to handle this if in fact Feature-1 was NOT going to be released, then ... assuming the head is pointed at /Feature2, will the following get the change from Feature-1 AND then everything back into master?

git merge Feature-1
git push origin Feature-2
git checkout master
git merge Feature-2
git push origin master

Body:
If you have one "feature branch" per release, they're not feature branches. (Unless you're doing continuous delivery, in which case you just release master.)

Feature branches should be about a single feature, preferably one that either isn't going to take very long, or isn't going to mess much with other code. Once that feature is done it should be tested, merged, and the branch deleted never to be used again.

Unless you explicitly need something in an incomplete feature branch, don't branch feature branches off other feature branches. With short, sharp feature branches this should rarely be an issue. Even then often it's just a bug fix or refactoring. Try to extract just the bit you need, get that merged, and continue on your way.

If you often find yourself needing to branch off other feature branches, your feature branches are doing too much.

That's your first problem. If you use feature branches correctly, this should be a rare a problem. Doing too much in one branch complicates everything.

Let's sort out how Git does branches. Unlike other version control systems, commits connect to other commits and branches are just labels. Branches have no life of their own. Your situation looks like this.

                    G - H - I [feature-2]
                   /
          D - E - F - K [feature-1]
         /
A - B - C [master]

The kinks are entirely notional. We can also look at it like this.

                    K [feature-1]
                   /
          D - E - F - G - H - I [feature-2]
         /
A - B - C [master]

Looked at this way it should be more clear what is in feature-2. All of master, most of feature-1 (which is untested), and all of feature-2. feature-2 cannot be done until feature-1 is done, and that sort of dependency is undesirable.

If you're working on top of a branch and want to stay up to date, the simplest thing to do is to git rebase upstream-branch. This will rewrite your commits as if they were written on top of the upstream-branch all along. This avoids a bunch of confusing notional merges.

Before
                    G - H - I [feature-2]
                   /
          D - E - F - K [feature-1]
         /
A - B - C [master]

git checkout feature-2
git rebase feature -1

After
                        G1 - H1 - I1 [feature-2]
                       /
          D - E - F - K [feature-1]
         /
A - B - C [master]

feature-2 can then be safely pushed with git rebase --force-with-lease. People can safely update their copy of feature-2 if they pull with rebase, instead of merging. git pull --rebase or setting pull.rebase = merges in your Git config.

Again, this should be rare.

But, as above, feature-2 should probably never have been built on top of feature-1 at all. If they were small and independent features, it would look like this.

          D - E - F - K [feature-1]
         /
A - B - C [master]
         \
          G - H - I [feature-2]

Now you can have multiple independent features being developed and tested simultaneously. When they're done, in any order, they're merged into master and deleted. master is always in a known good state and can be released at any time. Releases are tracked with tags, not branches.

git checkout master
git merge feature-2
git branch -d feature-2

          D - E - F - K [feature-1]
         /
A - B - C ---------- J [master]
         \         /
          G - H - I

That's referred to as a "feature bubble".

Everyone else then rebases their feature branch on top of master to update, deals with any conflicts or breakage, and goes about their business.

git checkout master
git pull
git checkout feature-1
git rebase master

                       D1 - E1 - F1 - K1 [feature-1]
                      /
A - B - C ---------- J [master]
         \         /
          G - H - I


来源: stackexchange

问:
Add a column to df with count of rows in separate df which meet multiple criteria
Have two df's, each with the same columns but differing row counts.

Want to add a column to df1 which counts the rows in df2 which match multiple (not all) column criteria of df1.

Preferably the fastest/most efficient way of doing this as I'll have N pairs of df's with N rows in each.

Psuedo:

count = where (df1.one == df2.one) AND
              (df1.two between (df2.two * 0.9 AND df2.two * 1.1)) AND
              (df1.three == df2.three) AND
              (df1.four == df2.four)
```

<p>I've tried lots of iterations of: </p>

<pre class="lang-py prettyprint-override"><code>df1['count'] = np.count_nonzero((df1.one==df2.one)&(con2)..)
               and df1['count'] = sum((con1)&(con2)..)
               and df1['count'] = len(df1.loc((con1)&(con2)..))
</code>```

using .isin() and .values etc but get Value errors basically telling me the df's aren't the same size. Have also tried resetting index's etc etc as per other answers I found on here.

I've seen some similar questions answered using merge and groupby but not sure if possible with the amount of criteria I have + how some of my criteria are "betweens" or range lookups.

Thanks in advance!

Example df's:

```<code>first = [(1001,'', 10, 'KK', 5),
         (1002,'A', 9, 'QK' , 7),
         (1003,'B', 11, 'QQ', 11)
        ]

second = [(1004,'', 10.5, 'KK', 5),
          (1005,'', 9.9, 'KK', 5),
          (1006,'', 10, 'KK', 5),
          (1007,'', 10, 'KQ', 5),
          (1008,'A', 7, 'QK' , 9),
          (1009,'A', 9.1, 'QK' , 7),
          (1010,'A', 9, 'QK' , 7),
          (1011,'A', 9, 'KK' , 7),
          (1012,'B', 12, 'KQ', 9),
          (1013,'B', 11, 'QQ', 11),
          (1014,'B', 11, 'QK', 12),
          (1015,'B', 1, 'QQ', 11)
         ]

df1 = pd.DataFrame(first, columns=['ID', 'one', 'two', 'three','four'])
df2 = pd.DataFrame(second, columns=['ID', 'one', 'two', 'three','four'])
</code>```

df1:

```<code>     ID one  two three  four
0  1001       10    KK     5
1  1002   A    9    QK     7
2  1003   B   11    QQ    11
</code>```

df2

```<code>      ID one   two three  four
0   1004      10.5    KK     5
1   1005       9.9    KK     5
2   1006      10.0    KK     5
3   1007      10.0    KQ     5
4   1008   A   7.0    QK     9
5   1009   A   9.1    QK     7
6   1010   A   9.0    QK     7
7   1011   A   9.0    KK     7
8   1012   B  12.0    KQ     9
9   1013   B  11.0    QQ    11
10  1014   B  11.0    QK    12
11  1015   B   1.0    QQ    11
</code>```

Desired output(df1):

```<code>     ID one  two three  four  count
0  1001       10    KK     5     3
1  1002   A    9    QK     7     2
2  1003   B   11    QQ    11     1
</code>```

答:
You could try this:</p>

```<code>def condition(x):
    return df2[(x.one == df2.one) & (x.three == df2.three) &
               (x.four == df2.four) & (x.two > (df2.two*0.9)) &
               (x.two < (df2.two*1.1))].shape[0]

df1['count'] = df1.apply(lambda x: condition(x), axis=1)

df1
    ID   one  two three  four  count
0  1001       10    KK     5      3
1  1002   A    9    QK     7      2
2  1003   B   11    QQ    11      1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Have two df's, each with the same columns but differing row counts.

Want to add a column to df1 which counts the rows in df2 which match multiple (not all) column criteria of df1.

Preferably the fastest/most efficient way of doing this as I'll have N pairs of df's with N rows in each.

Psuedo:

count = where (df1.one == df2.one) AND
              (df1.two between (df2.two * 0.9 AND df2.two * 1.1)) AND
              (df1.three == df2.three) AND
              (df1.four == df2.four)

I've tried lots of iterations of:

df1['count'] = np.count_nonzero((df1.one==df2.one)&(con2)..)
               and df1['count'] = sum((con1)&(con2)..)
               and df1['count'] = len(df1.loc((con1)&(con2)..))

using .isin() and .values etc but get Value errors basically telling me the df's aren't the same size. Have also tried resetting index's etc etc as per other answers I found on here.

I've seen some similar questions answered using merge and groupby but not sure if possible with the amount of criteria I have + how some of my criteria are "betweens" or range lookups.

Thanks in advance!

Example df's:

first = [(1001,'', 10, 'KK', 5),
         (1002,'A', 9, 'QK' , 7),
         (1003,'B', 11, 'QQ', 11)
        ]

second = [(1004,'', 10.5, 'KK', 5),
          (1005,'', 9.9, 'KK', 5),
          (1006,'', 10, 'KK', 5),
          (1007,'', 10, 'KQ', 5),
          (1008,'A', 7, 'QK' , 9),
          (1009,'A', 9.1, 'QK' , 7),
          (1010,'A', 9, 'QK' , 7),
          (1011,'A', 9, 'KK' , 7),
          (1012,'B', 12, 'KQ', 9),
          (1013,'B', 11, 'QQ', 11),
          (1014,'B', 11, 'QK', 12),
          (1015,'B', 1, 'QQ', 11)
         ]

df1 = pd.DataFrame(first, columns=['ID', 'one', 'two', 'three','four'])
df2 = pd.DataFrame(second, columns=['ID', 'one', 'two', 'three','four'])

df1:

     ID one  two three  four
0  1001       10    KK     5
1  1002   A    9    QK     7
2  1003   B   11    QQ    11

df2

      ID one   two three  four
0   1004      10.5    KK     5
1   1005       9.9    KK     5
2   1006      10.0    KK     5
3   1007      10.0    KQ     5
4   1008   A   7.0    QK     9
5   1009   A   9.1    QK     7
6   1010   A   9.0    QK     7
7   1011   A   9.0    KK     7
8   1012   B  12.0    KQ     9
9   1013   B  11.0    QQ    11
10  1014   B  11.0    QK    12
11  1015   B   1.0    QQ    11

Desired output(df1):

     ID one  two three  four  count
0  1001       10    KK     5     3
1  1002   A    9    QK     7     2
2  1003   B   11    QQ    11     1

Body:
You could try this:

def condition(x):
    return df2[(x.one == df2.one) & (x.three == df2.three) &
               (x.four == df2.four) & (x.two > (df2.two*0.9)) &
               (x.two < (df2.two*1.1))].shape[0]

df1['count'] = df1.apply(lambda x: condition(x), axis=1)

df1
    ID   one  two three  four  count
0  1001       10    KK     5      3
1  1002   A    9    QK     7      2
2  1003   B   11    QQ    11      1


问:
jQuery selector optimization

Be specific on the right-hand side of your selector, and less specific on the left.

```<code>// unoptimized
$('div.data .gonzalez');

// optimized
$('.data td.gonzalez');
</code>```

Quote Source

Could someone explain why the less specific left is faster as a CSS selector?

Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

Are there any speed gains using "similarly optimised" CSS selectors in CSS files?

答:
jQuery's Sizzle Engine parse selectors from right to left, so it's true. There are exceptions though, for example when the first operand is an ID. Then the search will operate in the context of the element with this ID. That's a particularity of the Sizzle Engine, but I don't know how querySelectorForAll is implemented.

An example:

```<code>$('div.data .gonzalez');
</code>```

Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data

ContentLicense: CC BY-SA 3.0

Title: jQuery selector optimization

Body:
Be specific on the right-hand side of your selector, and less specific on the left.

// unoptimized
$('div.data .gonzalez');

// optimized
$('.data td.gonzalez');

Quote Source

Could someone explain why the less specific left is faster as a CSS selector?

Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

Are there any speed gains using "similarly optimised" CSS selectors in CSS files?

Body:
jQuery's Sizzle Engine parse selectors from right to left, so it's true. There are exceptions though, for example when the first operand is an ID. Then the search will operate in the context of the element with this ID. That's a particularity of the Sizzle Engine, but I don't know how querySelectorForAll is implemented.

An example:

$('div.data .gonzalez');

Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data


Title: A visualization that can show four different type of data at the same time

Body:
I want to visualize my data which is as follows:

I have 5 different algorithms (alg1, alg2, alg3, alg4, and alg5)

I have three groups of users (g1, g2, and g3)

For each group, the algorithm is evaluated according to two metrics m1 and m2 (e.g. precision and profit for each group)

I want to visualize all of these in one plot that can show how these algorithms are performing with respect to the two metrics on all three user groups.

I was thinking of a scatter plot but not sure how these all can be incorporated in one scatter plot.

The results for metric m1 are like this: each value has three elements that correspond to three different user groups.

{'alg1': [662.0003391054959, 175.32345651614452, 72.03508238727193],
 'alg2': [923.6524005590929, 385.2151039219693, 190.71692280990948],
 'alg3': [1404.387917216172, 446.2766994367938, 213.12994410684388],
 'alg4': [-28.01225225765556, -73.09081443515035, -85.32203386999164],
 'alg5': [1117.9970322350164, 424.7898159256133, 208.7032559089046]}

and for metric m2:

{'alg1': [0.03111111111111112, 0.04362962962962987, 0.06071428571428592],
 'alg2': [0.0991111111111115, 0.10851851851851772, 0.14776785714285706],
 'alg3': [0.006074074074074077,
  0.02911111111111126,
  0.061904761904762164],
 'alg4': [0.0017777777777777776, 0.00362962962962963, 0.0038690476190476205],
 'alg5': [0.06148148148148173, 0.08140740740740716, 0.12187499999999994]}

Body:
You can identify algorithms by color and user groups by marker type. M1 and M2 metrics in the axis.

What do you think?

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

m1d = {'alg1_m1': [662.0003391054959, 175.32345651614452, 72.03508238727193],
 'alg2_m1': [923.6524005590929, 385.2151039219693, 190.71692280990948],
 'alg3_m1': [1404.387917216172, 446.2766994367938, 213.12994410684388],
 'alg4_m1': [-28.01225225765556, -73.09081443515035, -85.32203386999164],
 'alg5_m1': [1117.9970322350164, 424.7898159256133, 208.7032559089046]}

m2d = {'alg1_m2': [0.03111111111111112, 0.04362962962962987, 0.06071428571428592],
 'alg2_m2': [0.0991111111111115, 0.10851851851851772, 0.14776785714285706],
 'alg3_m2': [0.006074074074074077,
  0.02911111111111126,
  0.061904761904762164],
 'alg4_m2': [0.0017777777777777776, 0.00362962962962963, 0.0038690476190476205],
 'alg5_m2': [0.06148148148148173, 0.08140740740740716, 0.12187499999999994]}

m1 = pd.DataFrame.from_dict(m1d)
m2 = pd.DataFrame.from_dict(m2d)

f, ax = plt.subplots()
a = ax.scatter(m1['alg1_m1'],m2['alg1_m2'],color=['r','g','b'], marker='.')
b = ax.scatter(m1['alg2_m1'],m2['alg2_m2'],color=['r','g','b'], marker='v')
c = ax.scatter(m1['alg3_m1'],m2['alg3_m2'],color=['r','g','b'], marker='<')
d = ax.scatter(m1['alg4_m1'],m2['alg4_m2'],color=['r','g','b'], marker='>')
e = ax.scatter(m1['alg5_m1'],m2['alg5_m2'],color=['r','g','b'], marker='^')
ax.set_xlabel('M1')
ax.set_ylabel('M2')

red = mpatches.Patch(color='red', label='Group 1')
blue = mpatches.Patch(color='blue', label='Group 2')
green = mpatches.Patch(color='green', label='Group 3')

legend2 = plt.legend(handles=[red, blue, green], loc=1)
plt.legend((a,b,c,d,e),['alg1','alg2','alg3','alg4','alg5'], loc=7)
plt.gca().add_artist(legend2)

leg = ax.get_legend()
for i in range(0,5,1):
    leg.legendHandles[i].set_color('k')
plt.show()


问:
How set initial values to fields on form?
enter code hereI'm having some problems to solve a problem. I have a template, which allows the user to change some of their account settings. My goal is to initialize the form, with the user's default values, and he can keep or change them (by after submit form). However, until now the page does not render these values. I'm using a class based view, CreateView, for this purpose.

My code is listed below.

Here, is my CreateView.

```<code>class DetailUserInfoView(LoginRequiredMixin ,CreateView):
model = CustomUser.CustomUser
template_name = 'users/InfoUser.html'
login_url = settings.LOGOUT_REDIRECT_URL
context_object_name = 'user'
form_class = CustomUserChangeForm

def get_object(self):
    self.model = self.request.user
    return self.model

def get_initial(self):
    initial = super(DetailUserInfoView, self).get_initial()
    initial = initial.copy()
    initial[config.USERNAME] = self.request.user.username
    initial[config.FIRST_NAME] = self.request.user.first_name
    initial[config.LAST_NAME] = self.request.user.last_name
    return initial

def get_form_kwargs(self):
    kwargs = {'initial': self.get_initial()}
    return kwargs

def get_context_data(self, **kwargs): #GET OBJECT ACTS AFTER THAN GET_OBJECT --> EXAMPLE OF GET_CONTEXT_DATA, I DIDN'T NEED THIS
    context = super(DetailUserInfoView, self).get_context_data(**kwargs)
    context['username'] = self.request.user.username
    return context
</code>```

Here the form.

class CustomUserChangeForm(UserChangeForm):

```<code>class Meta(UserChangeForm.Meta):
    model = CustomUser.CustomUser
    fields = ('email', 'password', 'first_name', 'last_name', 'username', 'userType')
</code>```

And finally an extract of template.

```<code>    <div id="infoMayOverride">
        <form class="getOverridedValues" method="post">
            {% csrf_token %}
            <div id="usernameData">
                <label>{{ form.username.label_tag }}</label> <!--MODEL ON CREATEUSERVIEW IS CUSTOMUSER, AND NOW I NEED TO USE THIS FIELDS AND INHERITED FIELDS FROM USER CLASS-->
                <input type="text" id="usernameInput" value="{{ form.username }}">
            </div>
            <div id="firstNameData">
                <label>{{ form.first_name.label_tag }}</label>
                <input type="text" id="firstNameInput" value="{{ form.first_name }}">
            </div>
            <div id="lastNameData">
                <label>{{ form.last_name.label_tag }}</label>
                <input type="text" id="lastNameInput" value="{{ form.last_name }}">
            </div>
            <div id="divBtnChangeProfile">
                <input type="submit" class="btnChangeProfile" value="Atualizar Profile">
            </div>
        </form>
    </div>
</code>```

I'd appreciate it if you could help me. I am new to the Django environment, and have tried many approaches, and I have not yet been able to solve this problem.

--------------------------- Update ------------------------------------

Now, i can get initial values. But to view them i need to write on input form: form.username.initial, and with this i can't after submit form to update user values.

Anyone knows how to solve this type of problem??

答:
I finally got this problem solved. I will make my solution available, since it can help other people.

I had to make some changes to the code I provided behind.

Below is the code of view.

```<code>class DetailUserInfoView(LoginRequiredMixin, UpdateView):
model = CustomUser.CustomUser
template_name = 'users/InfoUser.html'
login_url = settings.LOGOUT_REDIRECT_URL
context_object_name = 'user'
form_class = CustomUserChangeForm

def get_object(self, queryset=None):
    return self.request.user

def get_form_kwargs(self):
    kwargs = super(DetailUserInfoView, self).get_form_kwargs()
    u = self.request.user
    kwargs['username_initial'] = u.username
    kwargs['fName_initial'] = u.first_name
    kwargs['lName_initial'] = u.last_name

    return kwargs

def get_context_data(self, **kwargs): #GET OBJECT ACTS AFTER THAN GET_OBJECT --> EXAMPLE OF GET_CONTEXT_DATA, I DIDN'T NEED THIS
    context = super(DetailUserInfoView, self).get_context_data(**kwargs)
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    context['form'] = form
    return context
</code>```

My form (with init function, to set initial values on form, and is called by def get_form_kwargs(self)).

```<code>class CustomUserChangeForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        username_initial = kwargs.pop('username_initial', None)
        fName_initial = kwargs.pop('fName_initial', None)
        lName_initial = kwargs.pop('lName_initial', None)
        super(CustomUserChangeForm, self).__init__(*args, **kwargs)
        self.fields['username'].initial = username_initial
        self.fields['first_name'].initial = fName_initial
        self.fields['last_name'].initial = lName_initial

    class Meta(UserChangeForm.Meta):
        model = CustomUser.CustomUser
        fields = ('username', 'email', 'first_name', 'last_name')
</code>```

And finnaly, in template I replace the tag input with {{ form.username }}.

I hope it can help someone who has the same problem.

Body:
enter code hereI'm having some problems to solve a problem. I have a template, which allows the user to change some of their account settings. My goal is to initialize the form, with the user's default values, and he can keep or change them (by after submit form). However, until now the page does not render these values. I'm using a class based view, CreateView, for this purpose.

My code is listed below.

Here, is my CreateView.

class DetailUserInfoView(LoginRequiredMixin ,CreateView):
model = CustomUser.CustomUser
template_name = 'users/InfoUser.html'
login_url = settings.LOGOUT_REDIRECT_URL
context_object_name = 'user'
form_class = CustomUserChangeForm

def get_object(self):
    self.model = self.request.user
    return self.model

def get_initial(self):
    initial = super(DetailUserInfoView, self).get_initial()
    initial = initial.copy()
    initial[config.USERNAME] = self.request.user.username
    initial[config.FIRST_NAME] = self.request.user.first_name
    initial[config.LAST_NAME] = self.request.user.last_name
    return initial

def get_form_kwargs(self):
    kwargs = {'initial': self.get_initial()}
    return kwargs

def get_context_data(self, **kwargs): #GET OBJECT ACTS AFTER THAN GET_OBJECT --> EXAMPLE OF GET_CONTEXT_DATA, I DIDN'T NEED THIS
    context = super(DetailUserInfoView, self).get_context_data(**kwargs)
    context['username'] = self.request.user.username
    return context

Here the form.

class CustomUserChangeForm(UserChangeForm):

class Meta(UserChangeForm.Meta):
    model = CustomUser.CustomUser
    fields = ('email', 'password', 'first_name', 'last_name', 'username', 'userType')

And finally an extract of template.

        <form class="getOverridedValues" method="post">
            {% csrf_token %}

                {{ form.username.label_tag }}
                <input type="text" id="usernameInput" value="{{ form.username }}">

                {{ form.first_name.label_tag }}
                <input type="text" id="firstNameInput" value="{{ form.first_name }}">

                {{ form.last_name.label_tag }}
                <input type="text" id="lastNameInput" value="{{ form.last_name }}">

                <input type="submit" class="btnChangeProfile" value="Atualizar Profile">

        </form>

I'd appreciate it if you could help me. I am new to the Django environment, and have tried many approaches, and I have not yet been able to solve this problem.

--------------------------- Update ------------------------------------

Now, i can get initial values. But to view them i need to write on input form: form.username.initial, and with this i can't after submit form to update user values.

Anyone knows how to solve this type of problem??

Body:
I finally got this problem solved. I will make my solution available, since it can help other people.

I had to make some changes to the code I provided behind.

Below is the code of view.

class DetailUserInfoView(LoginRequiredMixin, UpdateView):
model = CustomUser.CustomUser
template_name = 'users/InfoUser.html'
login_url = settings.LOGOUT_REDIRECT_URL
context_object_name = 'user'
form_class = CustomUserChangeForm

def get_object(self, queryset=None):
    return self.request.user

def get_form_kwargs(self):
    kwargs = super(DetailUserInfoView, self).get_form_kwargs()
    u = self.request.user
    kwargs['username_initial'] = u.username
    kwargs['fName_initial'] = u.first_name
    kwargs['lName_initial'] = u.last_name

    return kwargs

def get_context_data(self, **kwargs): #GET OBJECT ACTS AFTER THAN GET_OBJECT --> EXAMPLE OF GET_CONTEXT_DATA, I DIDN'T NEED THIS
    context = super(DetailUserInfoView, self).get_context_data(**kwargs)
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    context['form'] = form
    return context

My form (with init function, to set initial values on form, and is called by def get_form_kwargs(self)).

class CustomUserChangeForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        username_initial = kwargs.pop('username_initial', None)
        fName_initial = kwargs.pop('fName_initial', None)
        lName_initial = kwargs.pop('lName_initial', None)
        super(CustomUserChangeForm, self).__init__(*args, **kwargs)
        self.fields['username'].initial = username_initial
        self.fields['first_name'].initial = fName_initial
        self.fields['last_name'].initial = lName_initial

    class Meta(UserChangeForm.Meta):
        model = CustomUser.CustomUser
        fields = ('username', 'email', 'first_name', 'last_name')

And finnaly, in template I replace the tag input with {{ form.username }}.

I hope it can help someone who has the same problem.


问:
SED Variable contains Dollar Sign
I m having difficulty with sed, a variable contains Dollar Sign like this...

```<code>PASSWORD='AsecretPassword$'
</code>```

I am trying to 'cleanse' and outputfile of a password with.

```<code>sed -i "s,$PASSWORD,ChangeMePassword,g" outputfile.json
</code>```

I have tried every version of quotes you can imagine. please help.

答:
Well, let us suppose you have this file:

```<code>$ cat outputfile
commonpassword
AsecretPassword$
abc123
</code>```

If you had control over the value of the pattern, you could just escape the dollar sign:

```<code>$ sed 's,AsecretPassword\$,ChangeMe,g' outputfile
commonpassword
ChangeMe
abc123
</code>```

Alas, we don't have, but we can use sed to escape the variable value:

```<code> $ echo $PASSWORD | sed -e 's/\$/\\$/g'
 AsecretPassword\$
</code>```

Fortunately, we can get the output of one command as part of another by using command substitution:

```<code>$ echo "Command substitution: $(echo $PASSWORD | sed -e 's/\$/\\$/g') Cool, right?"
Command substitution: AsecretPassword\$ Cool, right?
</code>```

...so we just need to do it on our original command!

```<code>$ sed "s,$(echo $PASSWORD| sed -e 's/\$/\\&/g'),ChangeMe,g" outputfile
commonpassword
ChangeMe
abc123
</code>```

In this case, we just escaped one special character. There are some more on sed, so this Q&A can be helpful in the general case.

Title: SED Variable contains Dollar Sign

Body:
I m having difficulty with sed, a variable contains Dollar Sign like this...

PASSWORD='AsecretPassword$'

I am trying to 'cleanse' and outputfile of a password with.

sed -i "s,$PASSWORD,ChangeMePassword,g" outputfile.json

I have tried every version of quotes you can imagine. please help.

Body:
Well, let us suppose you have this file:

$ cat outputfile
commonpassword
AsecretPassword$
abc123

If you had control over the value of the pattern, you could just escape the dollar sign:

$ sed 's,AsecretPassword\$,ChangeMe,g' outputfile
commonpassword
ChangeMe
abc123

Alas, we don't have, but we can use sed to escape the variable value:

 $ echo $PASSWORD | sed -e 's/\$/\\$/g'
 AsecretPassword\$

Fortunately, we can get the output of one command as part of another by using command substitution:

$ echo "Command substitution: $(echo $PASSWORD | sed -e 's/\$/\\$/g') Cool, right?"
Command substitution: AsecretPassword\$ Cool, right?

...so we just need to do it on our original command!

$ sed "s,$(echo $PASSWORD| sed -e 's/\$/\\&/g'),ChangeMe,g" outputfile
commonpassword
ChangeMe
abc123

In this case, we just escaped one special character. There are some more on sed, so this Q&A can be helpful in the general case.


问:
How to get the index in a primefaces dataList?
some one can tell me pliz how can i get index (i) datalist?

ex : Bean.myList.get(i) for putting it into a slide like :

```<code> <p:dataList value="#{Bean.myList}" var="objet">
    <slide :index="i" >
</code>```

答:
I don't know what documentation you've checked, but please note that the showcase is not documentation. In the documentation you'll find that you can use the rowIndexVar attribute with DataLists. It reads:

Name of the iterator to refer each row index.

Body:
some one can tell me pliz how can i get index (i) datalist?

ex : Bean.myList.get(i) for putting it into a slide like :

    <slide :index="i" >


问:
pyinstaller + usaddress package: 'ImportError: cannot import name _dumpparser'
I'm trying to use the python package usaddress together with pyinstaller on Windows. After I build the executable, I get this error that I don't understand:

```<code>Traceback (most recent call last):
  File "test_usaddress\main.py", line 1, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\usaddress\__init__.py", line 16, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pycrfsuite\__init__.py", line 2, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 714, in load_module
    module = loader.load_module(fullname)
  File "pycrfsuite\_pycrfsuite.pyx", line 14, in init pycrfsuite._pycrfsuite
ImportError: cannot import name _dumpparser
[14752] Failed to execute script main
</code>```

I get this error with a package that does nothing but import and call usaddress. The only thing in my main.py file is:

```<code>import usaddress

if __name__ == '__main__':
    addr = '123 Main St. Suite 100 Chicago, IL'
    print(usaddress.parse(addr))
</code>```

I build the executable with

```<code>pyinstaller main.py
</code>```

I'm running 64-bit python 3.6.1 on Windows, with pyinstaller 3.3. usaddress works fine without pyinstaller.

答:
I have encountered the same issue, and was able to solve it. There is a bug in the __init__.py code in usaddress package. You need to go into your usaddress package under dist, go into __init__.py. Change MODEL_PATH from

```<code>MODEL_PATH = os.path.split(os.path.abspath(__file___))[0] + '/' + MODEL_FILE
</code>```

to

```<code>MODEL_PATH = os.path.split(os.path.abspath(__file___))[0] + '\\' + MODEL_FILE
</code>```

Body:
I'm trying to use the python package usaddress together with pyinstaller on Windows. After I build the executable, I get this error that I don't understand:

Traceback (most recent call last):
  File "test_usaddress\main.py", line 1, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\usaddress\__init__.py", line 16, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pycrfsuite\__init__.py", line 2, in <module>
  File "c:\users\chq-luisd\appdata\local\continuum\anaconda3\lib\site-packages\P
yInstaller\loader\pyimod03_importers.py", line 714, in load_module
    module = loader.load_module(fullname)
  File "pycrfsuite\_pycrfsuite.pyx", line 14, in init pycrfsuite._pycrfsuite
ImportError: cannot import name _dumpparser
[14752] Failed to execute script main

I get this error with a package that does nothing but import and call usaddress. The only thing in my main.py file is:

import usaddress

if __name__ == '__main__':
    addr = '123 Main St. Suite 100 Chicago, IL'
    print(usaddress.parse(addr))

I build the executable with

pyinstaller main.py

I'm running 64-bit python 3.6.1 on Windows, with pyinstaller 3.3. usaddress works fine without pyinstaller.

Body:
I have encountered the same issue, and was able to solve it. There is a bug in the __init__.py code in usaddress package. You need to go into your usaddress package under dist, go into __init__.py. Change MODEL_PATH from

MODEL_PATH = os.path.split(os.path.abspath(__file___))[0] + '/' + MODEL_FILE

to

MODEL_PATH = os.path.split(os.path.abspath(__file___))[0] + '\\' + MODEL_FILE


问:
How to get the placeholder and the text to begin from the start of the textarea?
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="comment-label" for="comments">Comments</label>
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></code>```

OUTPUT

答:
Simplest would be replace input element with text area element. If still you want achieve with input element you can try to style the placeholder pseudo-element by adjusting the position according to your need</p>

```<code>::-webkit-input-placeholder {
       position:relative;
       top:-35px;
    }

    :-moz-placeholder { /* Firefox 18- */
       position:relative;
       top:-35px;
    }

    ::-moz-placeholder {  /* Firefox 19+ */
       position:relative;
       top:-35px;
    }

    :-ms-input-placeholder {
       position:relative;
       top:-35px;
    }
</code>```

Body:
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}

Comments
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required>

OUTPUT

Body:
Simplest would be replace input element with text area element. If still you want achieve with input element you can try to style the placeholder pseudo-element by adjusting the position according to your need

::-webkit-input-placeholder {
       position:relative;
       top:-35px;
    }

    :-moz-placeholder { /* Firefox 18- */
       position:relative;
       top:-35px;
    }

    ::-moz-placeholder {  /* Firefox 19+ */
       position:relative;
       top:-35px;
    }

    :-ms-input-placeholder {
       position:relative;
       top:-35px;
    }


问:
Why i have array [] option as consturctor invoke?
I have a class for example GooglePlayConnection. When I create object of this class without variable initialization (just to invoke method) new GooglePlayConnection() IDEA suggest to me 2 options: like default empty constructor () and .. array []? What does it mean?

I don't have any constructors in these classes.

答:
...and .. array []? What does it mean?

It's to create a GooglePlayConnection array:

```<code>GooglePlayConnection[] connections = new GooglePlayConnection[10];
connections[0] = new GooglePlayConnection(/*...*/);
// ...
</code>```

or

```<code>GooglePlayConnection[] connections = new GooglePlayConnection[] {
    new GooglePlayConnection(/*...*/),
    // ...
};
</code>```

Body:
...and .. array []? What does it mean?

It's to create a GooglePlayConnection array:

GooglePlayConnection[] connections = new GooglePlayConnection[10];
connections[0] = new GooglePlayConnection(/*...*/);
// ...

or

GooglePlayConnection[] connections = new GooglePlayConnection[] {
    new GooglePlayConnection(/*...*/),
    // ...
};


问:
How do I make a gulp function run in series? (gulp-download)
I've been trying to set up functions to download and then install frameworks into my development workflow with gulp-download. Every time I run gulp-download in series, it always runs last, so the function tries to move the files, then they download.

I tried to use merge and run this in a single function, then split it and used a task in series to run it. Neither way is successful.

```<code>// DOWNLOAD BOOTSTRAP
function downloadBootstrap(cb) {
  download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
  cb();
}

// INSTALL BOOTSTRAT
function installBootstrap(cb) {

  var css = gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}')
    .pipe(dest('_developer/2-css/0-frameworks/bootstrap'))

  var js = gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}')
  .pipe(dest('_developer/3-js/0-frameworks/bootstrap'))

  var clear = gulp.src('downloads/bootstrap', {read: false, allowEmpty: true})
  .pipe(clean())

  return merge(css, js, clear); // Combined src
  cb();
}

gulp.task('bootstrap', gulp.series('downloadBootstrap', 'installBootstrap'));
</code>```

答:
You need to make sure you only call the callback function when your task is complete. Inside download, the function call returning doesn't mean the download has finished. However, since you're using a pipeline here, you can eliminate the callback parameter altogether. (On an unrelated note, I would avoid having two functions named download.)

```<code>// DOWNLOAD BOOTSTRAP
function download() {
  return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
}
</code>```

Returning the stream will ensure that the stream has been fully processed before the next task continues. Also, you can just remove the callback from your install function since it will never actually be used. (Nothing runs after your function returns.)

Body:
I've been trying to set up functions to download and then install frameworks into my development workflow with gulp-download. Every time I run gulp-download in series, it always runs last, so the function tries to move the files, then they download.

I tried to use merge and run this in a single function, then split it and used a task in series to run it. Neither way is successful.

// DOWNLOAD BOOTSTRAP
function downloadBootstrap(cb) {
  download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
  cb();
}

// INSTALL BOOTSTRAT
function installBootstrap(cb) {

  var css = gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}')
    .pipe(dest('_developer/2-css/0-frameworks/bootstrap'))

  var js = gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}')
  .pipe(dest('_developer/3-js/0-frameworks/bootstrap'))

  var clear = gulp.src('downloads/bootstrap', {read: false, allowEmpty: true})
  .pipe(clean())

  return merge(css, js, clear); // Combined src
  cb();
}

gulp.task('bootstrap', gulp.series('downloadBootstrap', 'installBootstrap'));

Body:
You need to make sure you only call the callback function when your task is complete. Inside download, the function call returning doesn't mean the download has finished. However, since you're using a pipeline here, you can eliminate the callback parameter altogether. (On an unrelated note, I would avoid having two functions named download.)

// DOWNLOAD BOOTSTRAP
function download() {
  return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
}

Returning the stream will ensure that the stream has been fully processed before the next task continues. Also, you can just remove the callback from your install function since it will never actually be used. (Nothing runs after your function returns.)


问:
How do get this database cloud function to fire?
UPDATE

The challenging database function works when deployed but not with the emulator

ORIGINAL QUESTION

I have a couple of http cloud functions and one database cloud function in my cloud functions project.
All http cloud functions are running fine but the database cloud function is never triggered irrespective of the many fixes I've made.

When I start the cloud functions emulator, I see the database cloud function alongside the http functions on the list of functions being initialised, but the database cloud function is never triggered whenever new modifications are made to the database path (potential-students) that it is supposed to monitor.

Here are snippets of my index.js code

// This cloud function works perfectly
exports.status = functions.https.onRequest(async (req, resp) => {
  console.log("Hitting /status with", req.hostname, req.baseUrl, req.path);
  return resp.status(200).send({
    ok: true,
    data: {
      message:
        "connected to HTTP Cloud Function listener"
    }
  });
});
```

<p>Here are different versions of the database function I've tried</p>

<pre class="lang-js prettyprint-override"><code>exports.notifyOnPreRegistration = functions.database
  .ref("/potential-students")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });
</code>```

exports.notifyOnPreRegistration = functions.database
  .ref("potential-students")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });
```

<p>Whenever I try to access <code>localhost:9000/potential-students.json</code>, I get <code>null</code> as the response.
I also see this in my <code>database.debug.log</code> file</p>

```WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by io.netty.util.internal.ReflectionUtil (file:/path/firebase/emulators/firebase-database-emulator-v4.3.1.jar) to field sun.nio.ch.SelectorImpl.selectedKeys
WARNING: Please consider reporting this to the maintainers of io.netty.util.internal.ReflectionUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
12:38:29.482 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
12:38:29.627 [main] INFO com.firebase.server.forge.App$ - Listening at localhost:9000
```

Below is a picture of my terminal when I run my emulator. I'll be glad to provide any other non-secret information if required.

My question is: How do get this database cloud function to fire?

答:
I get it you need to fire the database function everytime a document is created, modified or deleted, right? If so, this should work:</p>

```<code>exports.notifyOnPreRegistration = functions.database
  .ref("/potential-students/{studentId}")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });
</code>```

Body:
UPDATE

The challenging database function works when deployed but not with the emulator

ORIGINAL QUESTION

I have a couple of http cloud functions and one database cloud function in my cloud functions project.
All http cloud functions are running fine but the database cloud function is never triggered irrespective of the many fixes I've made.

When I start the cloud functions emulator, I see the database cloud function alongside the http functions on the list of functions being initialised, but the database cloud function is never triggered whenever new modifications are made to the database path (potential-students) that it is supposed to monitor.

Here are snippets of my index.js code

// This cloud function works perfectly
exports.status = functions.https.onRequest(async (req, resp) => {
  console.log("Hitting /status with", req.hostname, req.baseUrl, req.path);
  return resp.status(200).send({
    ok: true,
    data: {
      message:
        "connected to HTTP Cloud Function listener"
    }
  });
});

Here are different versions of the database function I've tried

exports.notifyOnPreRegistration = functions.database
  .ref("/potential-students")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });

exports.notifyOnPreRegistration = functions.database
  .ref("potential-students")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });

Whenever I try to access localhost:9000/potential-students.json, I get null as the response.
I also see this in my database.debug.log file

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by io.netty.util.internal.ReflectionUtil (file:/path/firebase/emulators/firebase-database-emulator-v4.3.1.jar) to field sun.nio.ch.SelectorImpl.selectedKeys
WARNING: Please consider reporting this to the maintainers of io.netty.util.internal.ReflectionUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
12:38:29.482 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
12:38:29.627 [main] INFO com.firebase.server.forge.App$ - Listening at localhost:9000

Below is a picture of my terminal when I run my emulator. I'll be glad to provide any other non-secret information if required.

My question is: How do get this database cloud function to fire?

Body:
I get it you need to fire the database function everytime a document is created, modified or deleted, right? If so, this should work:

exports.notifyOnPreRegistration = functions.database
  .ref("/potential-students/{studentId}")
  .onWrite((change, context) => {
    console.log("running");
    console.log(change);
    console.log(context);
  });


问:
Repository, IRepository and structuremap
I have an interface IRepository and an implementation EFRepository.

I use structuremap injection in order to get the repository implementation.

Right now the EFRepository has constructor with no parameter so structuremap knows to retrieve instances on EFRepository easily.

Now I need to change the repository implementation so that it will recieve in the constructor parameter that holds the unit of work.

My question in such case, how I use structuremap in order to return an instance that initialized with the unit of work?

EXAMPLE

Until today I used:

```<code>using(IUnitOfWork uow=UnitOfWork.current) {
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>();
    //repository operations that uses UnitOfWork.current that initialized above
}// here dispose of UnitOfWork.current
</code>```

Now I want to use:

```<code>using(IUnitOfWork uow=new UnitOfWork()) {
    //Not sure is this is how I tell sructure map to use contractor that
    //get IUnitOfWork)
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>(uow);
    //repository operations that uses uow that initialized above
}// here dispose of UnitOfWork
</code>```

答:
In order to pass a specific instance to ObjectFactory you can use "with":</p>

```<code>IRepository rep = ObjectFactory.With<UnitOfWork>(uow).
  GetInstance<IRepository<T>>();
</code>```

Body:
I have an interface IRepository and an implementation EFRepository.

I use structuremap injection in order to get the repository implementation.

Right now the EFRepository has constructor with no parameter so structuremap knows to retrieve instances on EFRepository easily.

Now I need to change the repository implementation so that it will recieve in the constructor parameter that holds the unit of work.

My question in such case, how I use structuremap in order to return an instance that initialized with the unit of work?

EXAMPLE

Until today I used:

using(IUnitOfWork uow=UnitOfWork.current) {
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>();
    //repository operations that uses UnitOfWork.current that initialized above
}// here dispose of UnitOfWork.current

Now I want to use:

using(IUnitOfWork uow=new UnitOfWork()) {
    //Not sure is this is how I tell sructure map to use contractor that
    //get IUnitOfWork)
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>(uow);
    //repository operations that uses uow that initialized above
}// here dispose of UnitOfWork

Body:
In order to pass a specific instance to ObjectFactory you can use "with":

IRepository rep = ObjectFactory.With<UnitOfWork>(uow).
  GetInstance<IRepository<T>>();


问:
Reset gcloud auth identity token?
I'm working on a gcloud service which is not publicly available, i.e. you need to connect to it with your Authorization Header set with your gcloud identity token.

The docs used curl to show how to use it from the command line, however as my case concerns a web application I used a browser extension to inject this header when connecting to pages.

Silly me, I forgot to turn if off after I was done, which resulted in accessing a few websites with that token set in the request header. This means some third parties may now have that code.

2 questions concerning this:

How bad is this? What can this token be used for by the ill-willed?

How can I reset/revoke/renew this token?

答:
Identity Tokens are JWTs and are bearer tokens (as you are undoubtedly aware) and generally include a short-ish (60 minute) expiry.

As you suggest, you should be very careful with them as they could be used unscrupulously (while valid).

You may query your JWT using a (trustworthy!) tool to check the expiry:

E.g https://jwt.io/

I'm unsure (doesn't mean that there isn't) whether there's a way to forcibly expire Google-issued JWTs

Update:

Spoke with a Googler who's very well informed on auth and he confirmed that you must await expiry.

Update:

Independently, I reminded myself that Google has a( very trustworthy) endpoint to verify tokens too (I can just never remember the URL, but) it's:

TOKEN=$(gcloud auth print-identity-token)
curl \
--request GET \
https://oauth2.googleapis.com/tokeninfo?id_token=${TOKEN}
```

<p>And, for completeness, for access tokens:</p>

<pre class="lang-sh prettyprint-override"><code>TOKEN=$(gcloud auth print-access-token)
curl \
--request GET \
https://oauth2.googleapis.com/tokeninfo?access_token=${TOKEN}
</code>```

Title: Reset gcloud auth identity token?

Body:
Identity Tokens are JWTs and are bearer tokens (as you are undoubtedly aware) and generally include a short-ish (60 minute) expiry.

As you suggest, you should be very careful with them as they could be used unscrupulously (while valid).

You may query your JWT using a (trustworthy!) tool to check the expiry:

E.g https://jwt.io/

I'm unsure (doesn't mean that there isn't) whether there's a way to forcibly expire Google-issued JWTs

Update:

Spoke with a Googler who's very well informed on auth and he confirmed that you must await expiry.

Update:

Independently, I reminded myself that Google has a( very trustworthy) endpoint to verify tokens too (I can just never remember the URL, but) it's:

TOKEN=$(gcloud auth print-identity-token)
curl \
--request GET \
https://oauth2.googleapis.com/tokeninfo?id_token=${TOKEN}

And, for completeness, for access tokens:

TOKEN=$(gcloud auth print-access-token)
curl \
--request GET \
https://oauth2.googleapis.com/tokeninfo?access_token=${TOKEN}


问:
sql 2008 point reprojection
i have a table with two fields (X,Y)
they hold the location of points in New Israel Projection (EPSG: 2039) (e.g. X=194545.05941493041, Y=668112.83849507652)
i want to reproject all points to WGS84 (EPSG: 4326). (e.g. the same coordinates above should translate to something around: 34.940578289586, 32.106153057749005

how do i do that in SQL 2008?

答:
There may be a easier solution now, but what I had to do a few years ago was the following:
I needed to reproject between UTM33N(x, y ) and WGS84 (lat lon).

I use http://projnet.codeplex.com/ to translate each coordinate. The key you need is the two WKT (WellKnownText) that make up the projection model.
For me it was some hours of try and fail, but eventually I had a good translation.

Later when we started to use spatial indexes I created a SSIS package to reproject all data on inport.

There may be better solutions that that today:
perhaps it's supported by http://sqlspatialtools.codeplex.com/
Also I see that many are using ogr2ogr http://www.gdal.org/ogr2ogr.html

Title: sql 2008 point reprojection


问:
Re-render web-view on bottomTabNavigator
How I can re-render a web-view running inside a app built with react native. For exemple: The cart tab need to load the same url every time I click on it.

This is the cart class:

```<code>import React, { useState } from 'react';
import { ActivityIndicator, WebView, View, Button, ScrollView,
  RefreshControl,
  Text, } from 'react-native';
import Config from '../config';

export default class CarrinhoScreen extends React.Component {

  reload() {
    this.myWebView.reload()
  }

  render() {
    return (
    <>
        <View style={{ flex: 1 }}>
          <WebView
            source={{ uri: 'https://www.genieshopp.com/checkout/cart/' }}
            userAgent='bring-app'
            startInLoadingState={true}
            ref={(ref) => this.myWebView = ref}
          />
        </View>
    </>
    )
  }
};
</code>```

Here is where the tabNavigator is created:

```<code>import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import CarrinhoScreen from '../screens/CarrinhoScreen';

const config = Platform.select({
  web: { headerMode: 'screen' },
  default: {},
});

const CarrinhoStack = createStackNavigator(
  {
    Carrinho: CarrinhoScreen
  },
  config
);

CarrinhoStack.navigationOptions = {
  tabBarLabel: 'Carrinho',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon focused={focused} name={Platform.OS === 'ios' ? 'ios-cart' : 'md-cart'}/>
  ),
};

CarrinhoStack.path = '';

const tabNavigator = createBottomTabNavigator(
{
  CarrinhoStack,
  },
  {
    backBehavior: 'history'
  }
);

tabNavigator.path = '';

export default tabNavigator;
</code>```

I know there is the myWebView.reload(), but I want to know how I reload it when the bottom tab is switched or when I click on the same icon.

答:
Solved by putting resetOnBlur: CarrinhoScreen after backBehavior: history
You can put any other screen you want to reset on there.

Body:
How I can re-render a web-view running inside a app built with react native. For exemple: The cart tab need to load the same url every time I click on it.

This is the cart class:

import React, { useState } from 'react';
import { ActivityIndicator, WebView, View, Button, ScrollView,
  RefreshControl,
  Text, } from 'react-native';
import Config from '../config';

export default class CarrinhoScreen extends React.Component {

  reload() {
    this.myWebView.reload()
  }

  render() {
    return (
    <>
        <View style={{ flex: 1 }}>
          <WebView
            source={{ uri: 'https://www.genieshopp.com/checkout/cart/' }}
            userAgent='bring-app'
            startInLoadingState={true}
            ref={(ref) => this.myWebView = ref}
          />
        </View>
    </>
    )
  }
};

Here is where the tabNavigator is created:

import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import CarrinhoScreen from '../screens/CarrinhoScreen';

const config = Platform.select({
  web: { headerMode: 'screen' },
  default: {},
});

const CarrinhoStack = createStackNavigator(
  {
    Carrinho: CarrinhoScreen
  },
  config
);

CarrinhoStack.navigationOptions = {
  tabBarLabel: 'Carrinho',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon focused={focused} name={Platform.OS === 'ios' ? 'ios-cart' : 'md-cart'}/>
  ),
};

CarrinhoStack.path = '';

const tabNavigator = createBottomTabNavigator(
{
  CarrinhoStack,
  },
  {
    backBehavior: 'history'
  }
);

tabNavigator.path = '';

export default tabNavigator;

I know there is the myWebView.reload(), but I want to know how I reload it when the bottom tab is switched or when I click on the same icon.


问:
Lock column based on date
I need to lock columns based on days stated in G8, H8, I8, J8, and K8.

I need to lock G9 through G44 if G8 doesn’t have today's day.

If today is Sunday and G8 has Sunday then G9 to G44 should be open If not then the data range should be locked.

This should be done with all the columns from G to K. How can I do that?
Thanks a million in advance.

```<code>Private Sub worksheet_Change(ByVal Target As Range)
Dim col As Range
    With ThisWorkbook.Sheets("Sheet1")
        .Unprotect "ABCDE"
        For Each col In .UsedRange.Columns
            col.EntireColumn.Locked = col.Range("A1").Value < Date
        Next col
        .Protect "ABCDE"
        .EnableSelection = xlNoRestrictions
    End With
End Sub
</code>```

答:
Welcome to SO. Your code looks good, all you need to do is to add a few more If conditions. Give it a try:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim col                 As Long
    Dim tDate               As Date

    tDate = Date 'today's date

    With ThisWorkbook.Sheets("Sheet1")
        '.Unprotect "ABCDE"
        For col = 0 To .Range("G9:K44").Columns.Count - 1
            'check if row 8 doesn't have today's date
            If .Range("G8").Offset(0, col).Value <> tDate Then
                'if today is Sunday and row 8 has Sunday
                If Format(tDate, "dddd") = "Sunday" And Format(.Range("G8").Offset(0, col).Value, "dddd") = "Sunday" Then
                    .Range("G8:G44").Offset(0, col).EntireColumn.Locked = False
                Else
                    .Range("G8:G44").Offset(0, col).EntireColumn.Locked = True
                End If
            End If
        Next col
        '.Protect "ABCDE"
        '.EnableSelection = xlNoRestrictions
    End With
End Sub
</code>```

Change tDate to some other date to test the code, e.g. tDate = '2020-02-16' (Sunday).

Title: Lock column based on date

Body:
I need to lock columns based on days stated in G8, H8, I8, J8, and K8.

I need to lock G9 through G44 if G8 doesn’t have today's day.

If today is Sunday and G8 has Sunday then G9 to G44 should be open If not then the data range should be locked.

This should be done with all the columns from G to K. How can I do that?
Thanks a million in advance.

Private Sub worksheet_Change(ByVal Target As Range)
Dim col As Range
    With ThisWorkbook.Sheets("Sheet1")
        .Unprotect "ABCDE"
        For Each col In .UsedRange.Columns
            col.EntireColumn.Locked = col.Range("A1").Value < Date
        Next col
        .Protect "ABCDE"
        .EnableSelection = xlNoRestrictions
    End With
End Sub

Body:
Welcome to SO. Your code looks good, all you need to do is to add a few more If conditions. Give it a try:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim col                 As Long
    Dim tDate               As Date

    tDate = Date 'today's date

    With ThisWorkbook.Sheets("Sheet1")
        '.Unprotect "ABCDE"
        For col = 0 To .Range("G9:K44").Columns.Count - 1
            'check if row 8 doesn't have today's date
            If .Range("G8").Offset(0, col).Value <> tDate Then
                'if today is Sunday and row 8 has Sunday
                If Format(tDate, "dddd") = "Sunday" And Format(.Range("G8").Offset(0, col).Value, "dddd") = "Sunday" Then
                    .Range("G8:G44").Offset(0, col).EntireColumn.Locked = False
                Else
                    .Range("G8:G44").Offset(0, col).EntireColumn.Locked = True
                End If
            End If
        Next col
        '.Protect "ABCDE"
        '.EnableSelection = xlNoRestrictions
    End With
End Sub

Change tDate to some other date to test the code, e.g. tDate = '2020-02-16' (Sunday).


问:
Multiple joins off same table
I'm trying to connect two different types of users from the same users data table.

I have a database table with the following schema

agent_relationships

buyer_id

agent_id

I have a table with user data:

users

id

first name

last name

What i want is a data set that has the following:

buyer id first name

buyer id last name

agent id first name

agent id last name

I know im doing this incorrectly, but heres what I've attempted:

This one returns the same data for both buyer and agent, which i expected

select u1.first_name as buyerfirst,u1.last_name as buyerlast,u1.first_name as agentfirst,u1.last_name as agentlast from users u1 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u1.id

This one fails

select u1.first_name as buyerfirst,u1.last_name as buyerlast,u2.first_name as agentfirst,u2.last_name as agentlast from users u1,users u2 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u2.id

答:
You need  two join on user  .. depending from agent_relationships </p>

```<code>select u1.first_name as buyerfirst
    ,u1.last_name as buyerlast
    ,u2.first_name as agentfirst
    ,u2.last_name as agentlast
from agent_relationships ar
left join users  u1   ar.buyer_id=u1.id
left join users  u2   ar.agent_id=u1.id
</code>```

Title: Multiple joins off same table

Body:
You need  two join on user  .. depending from agent_relationships

select u1.first_name as buyerfirst
    ,u1.last_name as buyerlast
    ,u2.first_name as agentfirst
    ,u2.last_name as agentlast
from agent_relationships ar
left join users  u1   ar.buyer_id=u1.id
left join users  u2   ar.agent_id=u1.id


问:
Why is a ConcurrentModificationException thrown and how to debug it
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

```<code>Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
</code>```

答: Try either CopyOnWriteArrayList or CopyOnWriteArraySet depending on what you are trying to do.</p>

Body:
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)

LastEditorDisplayName: Rich B

OwnerDisplayName: Javamann

ContentLicense: CC BY-SA 2.5


问:
What does this "Lambda Expression" do?
Just come across the following line of code and having a hard time finding documentation for it, is it a lambda expression? What does this do?

```<code>temp = Regex.Replace(url, REGEX_COOKIE_REPLACE,match => cookie.Values[match.Groups["CookieVar"].Value]);
</code>```

Specifically interested in the =>.

答:
If you look at the documentation for Replace, the 3rd argument is a MatchEvaluator:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

This is a delegate that takes a Match as an argument and returns the string to replace it with. Your code is defining a MatchEvaluator using a lambda expression:

```<code>match => cookie.Values[match.Groups["CookieVar"].Value]
</code>```

Here, for each match that the Regex finds, a value is being looked up in the cookie.Values dictionary and the result is being used as the replacement.

Title: What does this "Lambda Expression" do?

Body:
Just come across the following line of code and having a hard time finding documentation for it, is it a lambda expression? What does this do?

temp = Regex.Replace(url, REGEX_COOKIE_REPLACE,match => cookie.Values[match.Groups["CookieVar"].Value]);

Specifically interested in the =>.

Body:
If you look at the documentation for Replace, the 3rd argument is a MatchEvaluator:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

This is a delegate that takes a Match as an argument and returns the string to replace it with. Your code is defining a MatchEvaluator using a lambda expression:

match => cookie.Values[match.Groups["CookieVar"].Value]

Here, for each match that the Regex finds, a value is being looked up in the cookie.Values dictionary and the result is being used as the replacement.


问:
Use alias in layout templates ruby on rails
I need to use a variable in template.
I have a class call services;
need who this atributes, after iterable, as variable type alias.

In django we use, Example: {% firstof "0" as cont %}. I use the first element as cont.

In ruby on rails templates, how can I do this?

答:
I think you are trying to find Ruby String Interpolation.

```<code>age  = 33
name = "Jesus"

"Hello, my name is #{name} & I'm #{age} years old."
</code>```

"Hello, my name is Jesus & I'm 33 years old."

for more detail visit here string interpolation

Body:
I think you are trying to find Ruby String Interpolation.

age  = 33
name = "Jesus"

"Hello, my name is #{name} & I'm #{age} years old."

"Hello, my name is Jesus & I'm 33 years old."

for more detail visit here string interpolation


问:
Most efficient way to search event log messages
Suppose I want to find the newest occurrence of event 4688 that contains the string 0x1278. I am able to find the event by getting a certain number of events and then searching the message for that string:

```<code>Get-WinEvent -MaxEvents 1000 -FilterHashTable @{LogName="Security";Id=4688} | Where-Object {$_.Message -match "0x1278"}
</code>```

There are two issues with this approach:

The script must always wait for 1000 events to be returned, even if the event being searched for was at index 3.

If the event was older and would have been at index 1034, too few events were checked and it wasn't found when it should have been.

Is there a way to address these issues? Ideally the event should be found in the shortest time possible.

答:
Instead of piping the array of events to Where-Object, pipe it to ForEach-Object, assign the first match to a variable, and then break out of the loop. If you remove the -MaxEvents parameter, all events will be searched until a match is found or there are no more events:

```<code>PS C:\WINDOWS\system32> Get-WinEvent -FilterHashTable @{LogName="Security";id=4688} | ForEach-Object {if ($_.Message -match "0x1278") {$result = $_; break;}}
PS C:\WINDOWS\system32> $result

   ProviderName: Microsoft-Windows-Security-Auditing

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2/18/2020 10:14:55 AM         4688 Information      A new process has been created....
</code>```

Body:
Suppose I want to find the newest occurrence of event 4688 that contains the string 0x1278. I am able to find the event by getting a certain number of events and then searching the message for that string:

Get-WinEvent -MaxEvents 1000 -FilterHashTable @{LogName="Security";Id=4688} | Where-Object {$_.Message -match "0x1278"}

There are two issues with this approach:

The script must always wait for 1000 events to be returned, even if the event being searched for was at index 3.

If the event was older and would have been at index 1034, too few events were checked and it wasn't found when it should have been.

Is there a way to address these issues? Ideally the event should be found in the shortest time possible.

Body:
Instead of piping the array of events to Where-Object, pipe it to ForEach-Object, assign the first match to a variable, and then break out of the loop. If you remove the -MaxEvents parameter, all events will be searched until a match is found or there are no more events:

PS C:\WINDOWS\system32> Get-WinEvent -FilterHashTable @{LogName="Security";id=4688} | ForEach-Object {if ($_.Message -match "0x1278") {$result = $_; break;}}
PS C:\WINDOWS\system32> $result

   ProviderName: Microsoft-Windows-Security-Auditing

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2/18/2020 10:14:55 AM         4688 Information      A new process has been created....


问:
Getting 'java.lang.ClassNotFoundException: org.springframework.core.log.LogAccessor' when updating spring-kafka to 2.4.0.RELEASE
We are using spring boot 2.1.7.RELEASE and spring-kafka 2.2.7.RELEASE. Now, we are planning to update the spring-kafka version to 2.4.0.RELEASE and getting below error on app startup

java.lang.ClassNotFoundException: org.springframework.core.log.LogAccessor

Can you please suggest what am i missing here?

答: Yeah... For that feature you also need to upgrade a spring-core to 5.2.x version. But with that it would be better to move your project fully to Spring Boot 2.2. Otherwise it is going to be a lot of incompatibility. We never advertised that the latest Spring for Apache Kafka is going to work with that old Spring Boot.


问:
binding to Iterates through Object in Angular
I'm trying to iterate through data objects for hours now, can I get assistance.

this what I have done so far.

details.component.html

```<code> ngOnChanges(changes: SimpleChanges): void {
     this.repos = this.APiService.getRepos(changes.keywords.currentValue)
     .subscribe((res) =>  console.log(res))
  console.log('target', this.repos)

  }
</code>```

details.component.html

```<code><div>
    <ul *ngFor="let repo of repos | keyvalue">
        <li>{{repo.name}}</li>
    </ul>
</div>
</code>```

Console:

答:
You need to set the repos in your subscription.</p>

```<code>ngOnChanges(changes: SimpleChanges) {
    this.APiService
        .getRepos(changes.keywords.currentValue)
        .subscribe(res => this.repos = res);
}
</code>```

Body:
I'm trying to iterate through data objects for hours now, can I get assistance.

this what I have done so far.

details.component.html

 ngOnChanges(changes: SimpleChanges): void {
     this.repos = this.APiService.getRepos(changes.keywords.currentValue)
     .subscribe((res) =>  console.log(res))
  console.log('target', this.repos)

  }

details.component.html

{{repo.name}}

Console:

Body:
You need to set the repos in your subscription.

ngOnChanges(changes: SimpleChanges) {
    this.APiService
        .getRepos(changes.keywords.currentValue)
        .subscribe(res => this.repos = res);
}


问:
Multiple CSS classes that change the same attributes
I keep seeing divs in our HTML pages with multiple (bootstrap) CSS classes that seem to do the same thing:

Here's what dev tools show is being applied with the classes:

This happens all over the place, so as a sanity check, is there ever any reason for having multiple col-x classes? col-sm-9 is being overwritten, so it feels like a major oversight.

答: These classes define the width of columns based on how big the viewer's screen is. Sm is small or mobile screens, md is medium or tablet-sized screens, lg is large or desktop. While mobile, tablet and desktop are not universally defined screen sizes, the sm, md and lg cover these general areas. This page in Bootstraps documentation explains the grid system and gives you the official breakpoints of these screen sizes, https://getbootstrap.com/docs/4.4/layout/grid/.</p>


问:
Why is it a bad idea to refresh access token every time when I sent request?
I was doing react native app and using OAuth2 and get access token, refresh token and expire in time when I log in my App. I checked my token expire in time when I send a request (GET, POST). If my token expired, then I used a refresh token to get a new access token. My co-worker told me, I don't need check expired time, just use a refresh token to get access token every time I sent the request. I know his way is not properly, but what could be happened if I use his way? Why is it bad to refresh access token every time when I sent requests?</p>

答:
Your co-worker probably advised you to do this, which is how I always code these things:

Send the current access token to the API on each request

Eventually the access token will return 401

Then use the refresh token to get a new access token + retry the API call

Eventually the token renewal request will fail with an invalid_grant error and the user has to login again

That is, you refresh only when the access token expires and not on every single request. You avoid relying on the access token expiry time, since APIs can reject tokens for multiple reasons.


问:
Java useDelimiter and nextLine
I am trying to create a program that separate a string input (windows pathway) by using the delimiter. However my programme seems so ignore the delimiter.

The result I am expecting:

Skriv in sökvägen: C://Windows/System/

C

Windows

System
```

<p>The result I am getting:</p>

<pre class="lang-none prettyprint-override"><code>Skriv in sökvägen: C://Windows/System/

C://Windows/System/
</code>```

What am I missing in the below code?

```<code>import java.util.Scanner;

public class Sokvagen
{

   public static void main(String[] args)

   {

      //String representing pathway
      String sokvag;

      //Creating scanner object for reading from input stream
      Scanner userInput = new Scanner(System.in);

      // Set delimiter to ':' or '/' or whitespace
      userInput.useDelimiter("[:/\\s]+");

      // Instructions to the user to type a windows patway ex: C://Windows/System/
      System.out.print("Skriv in sökvägen: ");

      //Input
      sokvag = userInput.nextLine();

      //Print the result
      System.out.println(sokvag);

      userInput.close();
   }
}
</code>```

答:
I figuered out that I should have used 3 strings and use next and everything worked just fine.</p>

```<code>  //String representing pathway
  String sokvag1, sokvag2, sokvag3;

  //Creating scanner object for reading from input stream
  Scanner userInput = new Scanner(System.in);

  // Set delimiter to ':' or '/' or whitespace
  userInput.useDelimiter("[:/\\s]+");

  // Instructions to the user to type a windows patway ex: C://Windows/System/
  System.out.print("Skriv in sökvägen: ");

  //Input
  sokvag1 = userInput.next();
  sokvag2 = userInput.next();
  sokvag2 = userInput.next();

  //Print the result
  System.out.println(sokvag1);
  System.out.println(sokvag2);
  System.out.println(sokvag3);

  userInput.close();
</code>```

Title: Java useDelimiter and nextLine

Body:
I am trying to create a program that separate a string input (windows pathway) by using the delimiter. However my programme seems so ignore the delimiter.

The result I am expecting:

Skriv in sökvägen: C://Windows/System/

C

Windows

System

The result I am getting:

Skriv in sökvägen: C://Windows/System/

C://Windows/System/

What am I missing in the below code?

import java.util.Scanner;

public class Sokvagen
{

   public static void main(String[] args)

   {

      //String representing pathway
      String sokvag;

      //Creating scanner object for reading from input stream
      Scanner userInput = new Scanner(System.in);

      // Set delimiter to ':' or '/' or whitespace
      userInput.useDelimiter("[:/\\s]+");

      // Instructions to the user to type a windows patway ex: C://Windows/System/
      System.out.print("Skriv in sökvägen: ");

      //Input
      sokvag = userInput.nextLine();

      //Print the result
      System.out.println(sokvag);

      userInput.close();
   }
}

Body:
I figuered out that I should have used 3 strings and use next and everything worked just fine.

  //String representing pathway
  String sokvag1, sokvag2, sokvag3;

  //Creating scanner object for reading from input stream
  Scanner userInput = new Scanner(System.in);

  // Set delimiter to ':' or '/' or whitespace
  userInput.useDelimiter("[:/\\s]+");

  // Instructions to the user to type a windows patway ex: C://Windows/System/
  System.out.print("Skriv in sökvägen: ");

  //Input
  sokvag1 = userInput.next();
  sokvag2 = userInput.next();
  sokvag2 = userInput.next();

  //Print the result
  System.out.println(sokvag1);
  System.out.println(sokvag2);
  System.out.println(sokvag3);

  userInput.close();


问:
Why does Array(repeating: Dog(), count: 7) make an array of 7 elements pointing to the same Dog instance?
Assuming Dog is a class

```<code>let arr = Array(repeating: Dog(), count: 7)
</code>```

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

```<code>var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}
</code>```

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

答:
It's nothing special, it's just how values of class type are copied. Instances of classes get copied by duplicating references that point to the same objects. Instances of structs get copied by duplicating the entire instances.

To achieve what you want to do, you need to create a separate instances for each position in the array. You can do that using a closure provided to map:

```<code>(1...7).map { _ in Dog() }
</code>```

Body:
Assuming Dog is a class

let arr = Array(repeating: Dog(), count: 7)

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

Body:
It's nothing special, it's just how values of class type are copied. Instances of classes get copied by duplicating references that point to the same objects. Instances of structs get copied by duplicating the entire instances.

To achieve what you want to do, you need to create a separate instances for each position in the array. You can do that using a closure provided to map:

(1...7).map { _ in Dog() }


问:
I want to get the price of the books in k and k2 in the console application, but the code is not working
I want to get only prices value in the console application. So if the normal value of the price is more than 30 just deduct it to 10 percent. In the set method i had to put the condition if(value > 30), but i dont know the codes not working. </p>

```<code>class Book
{
    public string name;
    public string writer;
    public string publisher;
    private double price;
    public string category;

    public Book(string name, string writer, string publisher, double price, string category)
    {
        this.name = name;
        this.writer = writer;
        this.publisher = publisher;
        this.price = price;
        this.category = category;
    }

    public double Price
    {
        get
        {
            return price;
        }

        set
        {
            if(value >= 30)
            price = value * (.1);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Book b = new Book("Book1", "Micheal", "AB Publisher", 21.50, "Thriller");
        Book b1 = new Book("Book2", "Jones", "CD Publisher", 36.90, "History");
        Console.WriteLine(b.Price);
        Console.WriteLine(b1.Price);
    }
}
</code>```

答:
You have several problems here:

Your title should ask a question and yours doesn't. “The code is not working” is not a question anyone can answer.

You didn't debug your code. If you had done that you would have seen that if Book.Price < 30 then your setter does nothing at all; it doesn't save or change anything.

You're using double for prices. Doubles are binary floating-point and are designed for continuous quantities like mass or distance, not for discrete quantities like prices. For discrete floating-point use Decimal.

Your setter is not idempotent. That means your Book instances will have different values depending on how you assign it. You won't see it in your example because you have only a single assignment, but as soon as you start doing things like b.Price += 1 your prices are going to start changing to unpredictable values. Do not do this ever.

The first thing you need to do is change your price field to:

```<code>private decimal price;
</code>```

Then remove your Price property altogether.

You want to only display the discounted price, not change it every time you display it. The following property will do that:

```<code>public decimal DiscountedPrice => price >= 30 ? price * 0.1m : price;
</code>```

Then display discounted price like this; do not change your instance variable states to display them:

```<code>Console.WriteLine(b.DiscountedPrice )
</code>```

Body:
I want to get only prices value in the console application. So if the normal value of the price is more than 30 just deduct it to 10 percent. In the set method i had to put the condition if(value > 30), but i dont know the codes not working.

class Book
{
    public string name;
    public string writer;
    public string publisher;
    private double price;
    public string category;

    public Book(string name, string writer, string publisher, double price, string category)
    {
        this.name = name;
        this.writer = writer;
        this.publisher = publisher;
        this.price = price;
        this.category = category;
    }

    public double Price
    {
        get
        {
            return price;
        }

        set
        {
            if(value >= 30)
            price = value * (.1);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Book b = new Book("Book1", "Micheal", "AB Publisher", 21.50, "Thriller");
        Book b1 = new Book("Book2", "Jones", "CD Publisher", 36.90, "History");
        Console.WriteLine(b.Price);
        Console.WriteLine(b1.Price);
    }
}

Body:
You have several problems here:

Your title should ask a question and yours doesn't. “The code is not working” is not a question anyone can answer.

You didn't debug your code. If you had done that you would have seen that if Book.Price < 30 then your setter does nothing at all; it doesn't save or change anything.

You're using double for prices. Doubles are binary floating-point and are designed for continuous quantities like mass or distance, not for discrete quantities like prices. For discrete floating-point use Decimal.

Your setter is not idempotent. That means your Book instances will have different values depending on how you assign it. You won't see it in your example because you have only a single assignment, but as soon as you start doing things like b.Price += 1 your prices are going to start changing to unpredictable values. Do not do this ever.

The first thing you need to do is change your price field to:

private decimal price;

Then remove your Price property altogether.

You want to only display the discounted price, not change it every time you display it. The following property will do that:

public decimal DiscountedPrice => price >= 30 ? price * 0.1m : price;

Then display discounted price like this; do not change your instance variable states to display them:

Console.WriteLine(b.DiscountedPrice )


问:
Split a list of JSON blobs delimited by commas (ignoring commas inside a JSON blob)
Here's a weird one. I'm given an ill-conceived input string that is a list of JSON blobs, separated commas. e.g.:

string input = "{<some JSON object>},{JSON_2},{JSON_3},...,{JSON_n}"
```

<p>And I have to convert this to an actual list of JSON strings (<code>List<string></code>).</p>

<p>For context, the unsanitary "input" list of JSONs is read in directly from a .txt file on disk, produced by some other software. I'm writing an "adapter" to allow this data to be consumed by another piece of software that knows how to interpret the individual JSON objects contained within the list. Ideally, the original software could have output one file per JSON object.</p>

<hr>

<p>The "obvious" solution (using <code>String.Split</code>):</p>

<pre class="lang-cs prettyprint-override"><code>List<string> split = input.Split(',').ToList();
</code>```

would of course fail to escape commas present within the JSON objects ({}) themselves

I was considering a manual approach - walking the string character-by-character and only splitting out a new element if the count of { is equal to the count of }. Something like:

List<string> JsonBlobs = new List<string>();
int start = 0, nestingLevel = 0;
for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '{') nestingLevel++;
    else if (input[i] == '}') nestingLevel--;
    else if (input[i] == ',' && nestingLevel == 0)
    {
        JsonBlobs.Add(input.Substring(start, i - start));
        start = i + 1;
    }
}
```

<p><em>(The above likely contains bugs)</em></p>

<hr>

<p>I had also considered adding JSON array braces on either end of the string (<code>[]</code>) and letting a JSON serializer deserialize it as a JSON array, then re-serialize each of the array elements one at a time:</p>

<pre class="lang-cs prettyprint-override"><code>List<string> JsonBlobs = Newtonsoft.Json.Linq.JArray.Parse("[" + input + "]")
    .Select<Newtonsoft.Json.Linq.JToken, string>(token => token.ToString()).ToList();
</code>```

But this seems overly-expensive, and could potentially result in newly serialized JSON representations that are not exactly equal to the original string contents.

Any better suggestions?

I'd prefer to use some easily-understandable use of built-in libraries and/or LINQ if possible. Regex would be a last resort, although nifty regex solutions would also be interesting to see.

答:
You can try splitting on:

```<code>(?<=}),(?={)
</code>```

but this of course assumes that a JSON string does not literally contain a sequence of },{ such as:

```<code>{"key":"For whatever reason, },{ literally exists in this string"}
</code>```

it would also fail for an array of objects such as:

```<code>{"key1":[{"key2":"value2"},{"key3":"value3"}]}
</code>```

:-/

Body:
Here's a weird one. I'm given an ill-conceived input string that is a list of JSON blobs, separated commas. e.g.:

string input = "{<some JSON object>},{JSON_2},{JSON_3},...,{JSON_n}"

And I have to convert this to an actual list of JSON strings (List<string>).

For context, the unsanitary "input" list of JSONs is read in directly from a .txt file on disk, produced by some other software. I'm writing an "adapter" to allow this data to be consumed by another piece of software that knows how to interpret the individual JSON objects contained within the list. Ideally, the original software could have output one file per JSON object.

The "obvious" solution (using String.Split):

List<string> split = input.Split(',').ToList();

would of course fail to escape commas present within the JSON objects ({}) themselves

I was considering a manual approach - walking the string character-by-character and only splitting out a new element if the count of { is equal to the count of }. Something like:

List<string> JsonBlobs = new List<string>();
int start = 0, nestingLevel = 0;
for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '{') nestingLevel++;
    else if (input[i] == '}') nestingLevel--;
    else if (input[i] == ',' && nestingLevel == 0)
    {
        JsonBlobs.Add(input.Substring(start, i - start));
        start = i + 1;
    }
}

(The above likely contains bugs)

I had also considered adding JSON array braces on either end of the string ([]) and letting a JSON serializer deserialize it as a JSON array, then re-serialize each of the array elements one at a time:

List<string> JsonBlobs = Newtonsoft.Json.Linq.JArray.Parse("[" + input + "]")
    .Select<Newtonsoft.Json.Linq.JToken, string>(token => token.ToString()).ToList();

But this seems overly-expensive, and could potentially result in newly serialized JSON representations that are not exactly equal to the original string contents.

Any better suggestions?

I'd prefer to use some easily-understandable use of built-in libraries and/or LINQ if possible. Regex would be a last resort, although nifty regex solutions would also be interesting to see.

Body:
You can try splitting on:

(?<=}),(?={)

but this of course assumes that a JSON string does not literally contain a sequence of },{ such as:

{"key":"For whatever reason, },{ literally exists in this string"}

it would also fail for an array of objects such as:

{"key1":[{"key2":"value2"},{"key3":"value3"}]}

:-/


答:
```<code>match => cookie.Values[match.Groups["CookieVar"].Value]
</code>```

is a shortcut to

```<code>delegate (Match match)
{
    return cookie.Values[match.Groups["CookieVar"].Value];
}
</code>```

Title: What does this "Lambda Expression" do?

Body:
match => cookie.Values[match.Groups["CookieVar"].Value]

is a shortcut to

delegate (Match match)
{
    return cookie.Values[match.Groups["CookieVar"].Value];
}


问:
How can I make a new column by adding two columns with a priority given to one of them?
I have the following dataframe and I want to get C as shown. Checking if there is a value for A then it would appear in C. If there is no value in A, then C will take B value.

```<code>data <-
structure(list(A = c(15L, 20L, NA, 8L), B = c(7L, NA, 9L, 6L),
    C = c(15L, 20L, 9L, 8L)), class = "data.frame", row.names = c(NA,
-4L))
</code>```

I tried something like:

```<code>data$C <- coalesce(data$A, data$B)
</code>```

答:
We can use</p>

```<code>data %>% mutate(C = coalesce(A, B))
</code>```

Body:
I have the following dataframe and I want to get C as shown. Checking if there is a value for A then it would appear in C. If there is no value in A, then C will take B value.

data <-
structure(list(A = c(15L, 20L, NA, 8L), B = c(7L, NA, 9L, 6L),
    C = c(15L, 20L, 9L, 8L)), class = "data.frame", row.names = c(NA,
-4L))

I tried something like:

data$C <- coalesce(data$A, data$B)

Body:
We can use

data %>% mutate(C = coalesce(A, B))