问:
Pygame image animation loop not properly looping
I have a small animation loop that cycles through images quickly. The goal is to make this constant and fluid, but I seem to be running in to an issue where the images show for a second and stay on the first frame.

The following code is from the entire player class with the animation:

```<code>class Ship(pygame.sprite.Sprite):

    change_x = 0

    delay = 0
    frame = 1

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = PlayerShip0.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = SCREEN_X / 2 - 100
        self.rect.y = SCREEN_Y - 40

    def move(self, speed):
        self.change_x = speed

    def stop(self):
        self.change_x = 0

    def update(self, screen):
        self.rect.x += self.change_x

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_X:
            self.rect.x -= 3

        self.delay += 1
        if self.delay >= 50:
            if self.frame == 1:
                self.image = PlayerShip0.convert_alpha()
                self.frame = 2
                self.delay = 1
            if self.frame == 2:
                self.image = PlayerShip1.convert_alpha()
                self.frame = 3
                self.delay = 1
            if self.frame == 3:
                self.image = PlayerShip2.convert_alpha()
                self.frame = 1
                self.delay = 1

        print(self.frame)

        screen.blit(self.image,self.rect)
</code>```

答:
Instead of

```<code>        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        if self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        if self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1
</code>```

use

```<code>        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        elif self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        elif self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1
</code>```

Otherwise, you set self.frame to 2 in the first if block, and the second if block will set it to 3 right away, making the condition for the third if block truthy, and so on.

Body:
I have a small animation loop that cycles through images quickly. The goal is to make this constant and fluid, but I seem to be running in to an issue where the images show for a second and stay on the first frame.

The following code is from the entire player class with the animation:

class Ship(pygame.sprite.Sprite):

    change_x = 0

    delay = 0
    frame = 1

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = PlayerShip0.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = SCREEN_X / 2 - 100
        self.rect.y = SCREEN_Y - 40

    def move(self, speed):
        self.change_x = speed

    def stop(self):
        self.change_x = 0

    def update(self, screen):
        self.rect.x += self.change_x

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_X:
            self.rect.x -= 3

        self.delay += 1
        if self.delay >= 50:
            if self.frame == 1:
                self.image = PlayerShip0.convert_alpha()
                self.frame = 2
                self.delay = 1
            if self.frame == 2:
                self.image = PlayerShip1.convert_alpha()
                self.frame = 3
                self.delay = 1
            if self.frame == 3:
                self.image = PlayerShip2.convert_alpha()
                self.frame = 1
                self.delay = 1

        print(self.frame)

        screen.blit(self.image,self.rect)

Body:
Instead of

        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        if self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        if self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1

use

        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        elif self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        elif self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1

Otherwise, you set self.frame to 2 in the first if block, and the second if block will set it to 3 right away, making the condition for the third if block truthy, and so on.


来源: stackexchange

问:
JSON to textView?
I have my app get JSON data from a link, but I need to get status from the JSON.

Status > Code and Msg.

Here is what I have working:

Screenshot:

I need to have it output >

Code : success (or fail, whatever the json says)

Msg : Licence updated.. (Or whatever the JSON spits out)

Any help would be nice or pointing me in the direction, thanks.

Some of my code:

```<code>public class doit extends AsyncTask<Void,Void,Void>{
String words;

        public doit() throws JSONException {
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                WebView wv = (WebView) findViewById(R.id.webview);
                EditText messages = (EditText) findViewById(R.id.messages);
                Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

                words=doc.text();

            }catch(Exception e){e.printStackTrace();}

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            texx.setText(words);

        }
</code>```

答:
Checkout awesome library Gson
You just need to create Object for response, And you will get it like

```<code>Response response = gson.fromJson("words", Response.class);
</code>```

response contains all your needs.

OR

You can go with json parser tutorials.

ContentLicense: CC BY-SA 3.0

Title: JSON to textView?

Body:
I have my app get JSON data from a link, but I need to get status from the JSON.

Status > Code and Msg.

Here is what I have working:

Screenshot:

I need to have it output >

Code : success (or fail, whatever the json says)

Msg : Licence updated.. (Or whatever the JSON spits out)

Any help would be nice or pointing me in the direction, thanks.

Some of my code:

public class doit extends AsyncTask<Void,Void,Void>{
String words;

        public doit() throws JSONException {
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                WebView wv = (WebView) findViewById(R.id.webview);
                EditText messages = (EditText) findViewById(R.id.messages);
                Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

                words=doc.text();

            }catch(Exception e){e.printStackTrace();}

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            texx.setText(words);

        }

Body:
Checkout awesome library Gson
You just need to create Object for response, And you will get it like

Response response = gson.fromJson("words", Response.class);

response contains all your needs.

OR

You can go with json parser tutorials.


问:
java 8 stream transform list of maps to one single map. Cannot be cast to integer exception
The following code is a java 8 stream expected to transform list of maps to one map containing all the elements from this list of maps.. The test data below is throwing a cannot be cast to integer exception.

```<code>Map test = new HashMap();
test.put("PreLoadTransactionId", 1234);
List<Map<String, String>> preloadTranactions = new List<>();
preloadTranactions.add(test);
final Map<String, Date> preloadTranactionIdUpdateMap = preloadTranactions.stream()
    .collect(Collectors.toMap(
        preloadTransaction -> preloadTransaction.get("PreLoadTransactionId"),
        preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
        (preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));
</code>```

Expecting to transform a list maps into a Map containing all the elements from this list of maps. Instead getting exception: "java.lang.Integer cannot be cast to java.lang.String"

How am I getting this exception ???

答:
First of all we do not know from this code snippet what is the type of "PreLoadTransactionId" and "UpdateDate" fields in the map.

If any of them is Integer you will get this error.
You should check how the map of preloadTransactions is being populated.
This when it is defined like Map<String, String> doesn't mean anything since in the example here:

```<code>List<Map<String, String>> preloadTranactions = new ArrayList<>();
    Map test = new HashMap();
    test.put("PreLoadTransactionId", 1234);
    preloadTranactions.add(test);
</code>```

You could save integer as a transactionId even it is declared in preloadTranactions as a Map with String values

So I think you just need to see how the map is populated and to fix the population or to explicitly cast to String in your Collector like this:

```<code>preloadTranactions.stream()
        .collect(Collectors.toMap(
                preloadTransaction ->
                String.valueOf( //THIS WILL FIX THE ISSUE EVEN IF VALUE IS NUMBER
                    preloadTransaction.get("PreLoadTransactionId")
                ),
                preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
                (preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));
</code>```

Body:
The following code is a java 8 stream expected to transform list of maps to one map containing all the elements from this list of maps.. The test data below is throwing a cannot be cast to integer exception.

Map test = new HashMap();
test.put("PreLoadTransactionId", 1234);
List<Map<String, String>> preloadTranactions = new List<>();
preloadTranactions.add(test);
final Map<String, Date> preloadTranactionIdUpdateMap = preloadTranactions.stream()
    .collect(Collectors.toMap(
        preloadTransaction -> preloadTransaction.get("PreLoadTransactionId"),
        preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
        (preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));

Expecting to transform a list maps into a Map containing all the elements from this list of maps. Instead getting exception: "java.lang.Integer cannot be cast to java.lang.String"

How am I getting this exception ???

Body:
First of all we do not know from this code snippet what is the type of "PreLoadTransactionId" and "UpdateDate" fields in the map.

If any of them is Integer you will get this error.
You should check how the map of preloadTransactions is being populated.
This when it is defined like Map<String, String> doesn't mean anything since in the example here:

List<Map<String, String>> preloadTranactions = new ArrayList<>();
    Map test = new HashMap();
    test.put("PreLoadTransactionId", 1234);
    preloadTranactions.add(test);

You could save integer as a transactionId even it is declared in preloadTranactions as a Map with String values

So I think you just need to see how the map is populated and to fix the population or to explicitly cast to String in your Collector like this:

preloadTranactions.stream()
        .collect(Collectors.toMap(
                preloadTransaction ->
                String.valueOf( //THIS WILL FIX THE ISSUE EVEN IF VALUE IS NUMBER
                    preloadTransaction.get("PreLoadTransactionId")
                ),
                preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
                (preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));


问:
spread syntax with map doesn't work
```<code>data.map(obj =>
        {person_name: obj.user.name,
        ...obj})
</code>```

Why above code failed?

my data look like this

```<code>[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]
</code>```

I want to 'pull' the obj.user.name out from the nested obj.

答:
First of all, if you want to create an object using an arrow function, you have to wrap the curly braces in parenthesis:

data.map(obj => ({ foo: 'bar' }));
```

Otherwise, JS thinks the curly braces are the function body, and you get a syntax error.

And secondly, you can't use the spread operator in object literals. You can only use it when calling a function, using the array literal or when destructuring.

Title: spread syntax with map doesn't work

Body:
data.map(obj =>
        {person_name: obj.user.name,
        ...obj})

Why above code failed?

my data look like this

[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]

I want to 'pull' the obj.user.name out from the nested obj.

Body:
First of all, if you want to create an object using an arrow function, you have to wrap the curly braces in parenthesis:

data.map(obj => ({ foo: 'bar' }));

Otherwise, JS thinks the curly braces are the function body, and you get a syntax error.

And secondly, you can't use the spread operator in object literals. You can only use it when calling a function, using the array literal or when destructuring.


问:
Seaborn barplot ordering by bar length
I am trying to plot barplot using seaborn.

```<code>k= 'all'
k_best = SelectKBest(k=k)
k_best=k_best.fit(features, labels)
features_k=k_best.transform(features)
scores = k_best.scores_ # extract scores attribute
pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True) # sort tuples in descending order
print pairs

#Bar plot of features and its scores
sns.set(style="white")
ax = sns.barplot(x=features_list[1:], y=scores)
plt.ylabel('SelectKBest Feature Scores')
plt.xticks(rotation=90)
</code>```

My plot looks like this

I want the bars to be sorted in descending order.Exercised_stock_options with highest value on left followed by total_stock_value and so on.

Kindly help.Thanks

答:
The two lines

```<code>pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)
</code>```

already give you a list of tuples, sorted by the scores values. Now you only need to unzip it to two lists, which can be plotted.

```<code>newx, newy = zip(*pairs)
sns.barplot(x=newx, y=newy)
</code>```

A full working example:

```<code>import seaborn.apionly as sns
import matplotlib.pyplot as plt

x = ["z","g","o"]
y = [5,7,4]

pairs = zip(x, y)
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)

newx, newy = zip(*pairs)
ax = sns.barplot(x=newx, y=newy)

plt.show()
</code>```

Title: Seaborn barplot ordering by bar length

Body:
I am trying to plot barplot using seaborn.

k= 'all'
k_best = SelectKBest(k=k)
k_best=k_best.fit(features, labels)
features_k=k_best.transform(features)
scores = k_best.scores_ # extract scores attribute
pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True) # sort tuples in descending order
print pairs

#Bar plot of features and its scores
sns.set(style="white")
ax = sns.barplot(x=features_list[1:], y=scores)
plt.ylabel('SelectKBest Feature Scores')
plt.xticks(rotation=90)

My plot looks like this

I want the bars to be sorted in descending order.Exercised_stock_options with highest value on left followed by total_stock_value and so on.

Kindly help.Thanks

Body:
The two lines

pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)

already give you a list of tuples, sorted by the scores values. Now you only need to unzip it to two lists, which can be plotted.

newx, newy = zip(*pairs)
sns.barplot(x=newx, y=newy)

A full working example:

import seaborn.apionly as sns
import matplotlib.pyplot as plt

x = ["z","g","o"]
y = [5,7,4]

pairs = zip(x, y)
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)

newx, newy = zip(*pairs)
ax = sns.barplot(x=newx, y=newy)

plt.show()


问:
How to display countdown timer in tableau dashboard?
I want to display countdown timer in tableau dashboard.
I have tried different calculation filed formula.
Is there any other way ?</p>

答:
Without elaborate tricks you will not be able to show a dynamic countdown.

If you have a fixed target time you can calculate the datediff dynamically and display that with every refresh (you cannot force it to refresh regularly)

```<code>DATEDIFF('seconds',now(),[TargetDate])
</code>```

You could even hide a dashboard once the targetdate is reached by creating a field

```<code>DATEDIFF('seconds',now(),[TargetDate]) < 0
</code>```

and filtering the values that are FALSE. Once the traget date is reached, everything will be false and the graph will be empty.

However you will not be able to for example hide a graph 20 seconds after somebody opened your dashboard. At least not with working around a lot of obstacles.

If you have a Tableau Server at hand you could try something like getting the event data from the Tableau Server data base, checking for when the currently logged in user accessed the dashboard the last time and calculating the datediff between that time and now(). This sounds overly complicated though and you will need to have a Server AND access to the Tableau DB.

Body:
Without elaborate tricks you will not be able to show a dynamic countdown.

If you have a fixed target time you can calculate the datediff dynamically and display that with every refresh (you cannot force it to refresh regularly)

DATEDIFF('seconds',now(),[TargetDate])

You could even hide a dashboard once the targetdate is reached by creating a field

DATEDIFF('seconds',now(),[TargetDate]) < 0

and filtering the values that are FALSE. Once the traget date is reached, everything will be false and the graph will be empty.

However you will not be able to for example hide a graph 20 seconds after somebody opened your dashboard. At least not with working around a lot of obstacles.

If you have a Tableau Server at hand you could try something like getting the event data from the Tableau Server data base, checking for when the currently logged in user accessed the dashboard the last time and calculating the datediff between that time and now(). This sounds overly complicated though and you will need to have a Server AND access to the Tableau DB.


问:
Transform a list to a string
What is the pythonic way to perform the below transformation?

[a, b, c] -> "'a', 'b', 'c'"

Where a, b, and c are all variables holding strings.

答:
A direct method would be

```<code>var = [a,b,c]
'\'' + '\', \''.join(var) + '\''
</code>```

Assuming the contents of the variables is the character version of their name, (i.e., a, b, c = 'a', 'b', 'c'), the output would be

```<code>"'a', 'b', 'c'"
</code>```

Title: Transform a list to a string

Body:
A direct method would be

var = [a,b,c]
'\'' + '\', \''.join(var) + '\''

Assuming the contents of the variables is the character version of their name, (i.e., a, b, c = 'a', 'b', 'c'), the output would be

"'a', 'b', 'c'"


问:
Replace anything in certain position in string using javascript regular expression
I am trying to remove empty all paragraph tags, regardless of what style attributes might be in the p tag, from a string. I want to remove, for example, all of these and replace with an empty string.

```<code><p style="margin-left:0px"></p>
<p></p>
<p style="margin-left:1cm; margin-right:1cm"></p>
</code>```

So far, to deal with one situation I have, I am doing this:

```<code>str = str.replace(/<p style=\"margin:0cm 0cm 10pt\"><\/p>/g,'')
</code>```

which is working in that particular situation. How can I write it so it removes

```<code><p AnythingHereInThisTag></p>
</code>```

and replaces it with an empty string?

Edit - further to answer below - if I do this:

```<code>str = str.replace(/<p(.*)><\/p>/g,'')
</code>```

it is replacing the whole string which might look like

```<code><p>Hello</p><p>Some text in the middle</p><p>Goodbye</p>
</code>```

It needs to look at each pair of

 tags

答:
Replace Any charecter without a char " has the regex as [^\"]

var reg=/\
\<\/p\>/g;
console.log('

'.replace(reg,''));
console.log('

'.replace(reg,''));
console.log('

'.replace(reg,''));
console.log('

'.replace(reg,''));```

Body:
I am trying to remove empty all paragraph tags, regardless of what style attributes might be in the p tag, from a string. I want to remove, for example, all of these and replace with an empty string.

So far, to deal with one situation I have, I am doing this:

str = str.replace(/
<\/p>/g,'')

which is working in that particular situation. How can I write it so it removes

and replaces it with an empty string?

Edit - further to answer below - if I do this:

str = str.replace(/
<\/p>/g,'')

it is replacing the whole string which might look like

Hello

Some text in the middle

Goodbye

It needs to look at each pair of

 tags

Body:
Replace Any charecter without a char " has the regex as [^\"]

var reg=/\<p( [a-zA-Z]*=((\"[^\"]*\")|(\'[^\']*\')))*\>\<\/p\>/g;
console.log('<p style=\'margin:0cm 0cm 10pt\'></p>'.replace(reg,''));
console.log('<p style=\"margin:0cm 0cm 10pt\"></p>'.replace(reg,''));
console.log('<p style=\"margin:0cm 0cm 10pt\" class=\"test\"></p>'.replace(reg,''));
console.log('<p></p>'.replace(reg,''));


问:
Why doesn't this SQL statement work?
```
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
```

that wont work. cant u have two "AND" in a sql statement??

//Tomek

答:
First let's start with getting rid of that old-style join so that the join and where clauses are clearly separated to make understanding much easier.

```<code>SELECT * FROM table1 t1.
JOIN table2 t2
ON t1.user_id = t2.id
WHERE t1.content = news
AND t1.content_id = 1
</code>```

Now let's discuss what the problem might be. First what error are you receiving as this could be perfectly acceptable syntax? Could the problem be that you have not noted which table news is to come from? If it is in both tables you could be getting an error there. If news is meant to be the value of the column you would want it to be 'news' instead of news. It could also simply be that no records meet your conditions.

Further it is a bad practice to ever use select * and it should never be used in a join as you are returning at least one field twice and that is wasteful of both database and network resources. Always specify only the columns you need. This wastes lots of resources every day when lazy programmers do this in every query.

OwnerDisplayName: Tomek

LastEditorDisplayName: Graeme Perrow

ContentLicense: CC BY-SA 2.5

Title: Why doesn't this SQL statement work?

Body:
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek

Body:
First let's start with getting rid of that old-style join so that the join and where clauses are clearly separated to make understanding much easier.

SELECT * FROM table1 t1.
JOIN table2 t2
ON t1.user_id = t2.id
WHERE t1.content = news
AND t1.content_id = 1

Now let's discuss what the problem might be. First what error are you receiving as this could be perfectly acceptable syntax? Could the problem be that you have not noted which table news is to come from? If it is in both tables you could be getting an error there. If news is meant to be the value of the column you would want it to be 'news' instead of news. It could also simply be that no records meet your conditions.

Further it is a bad practice to ever use select * and it should never be used in a join as you are returning at least one field twice and that is wasteful of both database and network resources. Always specify only the columns you need. This wastes lots of resources every day when lazy programmers do this in every query.

OwnerDisplayName: HLGEM


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答:
Essentially the line-height helps to set the "leading" and "half-leading".  The 100px accounts for the total height of the element and the text is being "vertically aligned" within that area.  Half is going above and half below.

This explains better than I.
http://www.w3.org/TR/CSS2/visudet.html#line-height

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


答:
You can use str.format():

```<code>d = [a, b, c]
final = "'{}', '{}', '{}'".format(*d)
</code>```

Edit: An answer inspired by the answer of @Stefan Pochmann

```<code>d = [a, b, c]
final = str(d)[1:-1]
</code>```

example:

```<code>a, b, c = 'a', 'b', 'c'
d = [a, b, c]
final = "'{}', '{}', '{}'".format(*d)
print(final)
</code>```

output:

```<code>'a', 'b', 'c'
</code>```

Title: Transform a list to a string

Body:
What is the pythonic way to perform the below transformation?

[a, b, c] -> "'a', 'b', 'c'"

Where a, b, and c are all variables holding strings.

Body:
You can use str.format():

d = [a, b, c]
final = "'{}', '{}', '{}'".format(*d)

Edit: An answer inspired by the answer of @Stefan Pochmann

d = [a, b, c]
final = str(d)[1:-1]

example:

a, b, c = 'a', 'b', 'c'
d = [a, b, c]
final = "'{}', '{}', '{}'".format(*d)
print(final)

output:

'a', 'b', 'c'


问:
MVC 3 RC2 Webgrid nightmares, anyone have paging working correctly?
I am using the latest RC2 version of MVC3.

I have a webgrid and it is giving me horrible problems, specifically with the paging and sorting.
I have been told that the paging should be more efficient now, and not pull back the whole table but only rows needed for the page you are viewing. This is not working as i hoped (very slow), and so have taken it to the simplest form and booted up the profiler.

I have this ActionResult:

```<code>    public ActionResult TestGrid()
    {
        return View(ents.Decisions);
    }
</code>```

And this view:

```<code>    @model IEnumerable<DecisionPanel.Web.Models.DataModel.Decision>

@{
    ViewBag.Title = "TestGrid";
    var usersGrid = new WebGrid(source: Model, rowsPerPage: 50);
}

<h2>TestGrid</h2>

@usersGrid.GetHtml(
        tableStyle: "grid",
        headerStyle: "header",
        alternatingRowStyle: "alt",
        rowStyle: "row",
                columns: usersGrid.Columns(
                        usersGrid.Column("UserID", "User Id"),
                        usersGrid.Column("HasAgreed", "Has Agreed?"),
                        usersGrid.Column("Comment"),
                        usersGrid.Column("DateResponded", "Date of Response", format: @<text>@item.DateResponded.ToString("dd MMM yyy (HH:mm.ss)")</text>)
        )
    )
</code>```

Hitting the page is causing this to run on the profiler - 11 times:

```<code>SELECT
[Extent1].[ID] AS [ID],
[Extent1].[UserID] AS [UserID],
[Extent1].[HasAgreed] AS [HasAgreed],
[Extent1].[Comment] AS [Comment],
[Extent1].[DateResponded] AS [DateResponded]
FROM [dbo].[DecisionResults] AS [Extent1]
</code>```

I am having some other problems but if i can't even get this working i am considering abandoning the webgrid.

I know it's early days with it being out under a week, but has anyone else had any joy using the paging?

答: At this point I can confirm there is an issue with the WebGrid as shipping in MVC3 RC2 where it does not smartly handle IQueryable data that supports database-side paging. We'll look into resolving this for RTM. For now you would have to do paging manually. Sorry about that.</p>

Body:
I am using the latest RC2 version of MVC3.

I have a webgrid and it is giving me horrible problems, specifically with the paging and sorting.
I have been told that the paging should be more efficient now, and not pull back the whole table but only rows needed for the page you are viewing. This is not working as i hoped (very slow), and so have taken it to the simplest form and booted up the profiler.

I have this ActionResult:

    public ActionResult TestGrid()
    {
        return View(ents.Decisions);
    }

And this view:

    @model IEnumerable<DecisionPanel.Web.Models.DataModel.Decision>

@{
    ViewBag.Title = "TestGrid";
    var usersGrid = new WebGrid(source: Model, rowsPerPage: 50);
}

TestGrid

@usersGrid.GetHtml(
        tableStyle: "grid",
        headerStyle: "header",
        alternatingRowStyle: "alt",
        rowStyle: "row",
                columns: usersGrid.Columns(
                        usersGrid.Column("UserID", "User Id"),
                        usersGrid.Column("HasAgreed", "Has Agreed?"),
                        usersGrid.Column("Comment"),
                        usersGrid.Column("DateResponded", "Date of Response", format: @<text>@item.DateResponded.ToString("dd MMM yyy (HH:mm.ss)")</text>)
        )
    )

Hitting the page is causing this to run on the profiler - 11 times:

SELECT
[Extent1].[ID] AS [ID],
[Extent1].[UserID] AS [UserID],
[Extent1].[HasAgreed] AS [HasAgreed],
[Extent1].[Comment] AS [Comment],
[Extent1].[DateResponded] AS [DateResponded]
FROM [dbo].[DecisionResults] AS [Extent1]

I am having some other problems but if i can't even get this working i am considering abandoning the webgrid.

I know it's early days with it being out under a week, but has anyone else had any joy using the paging?


问:
Services in Angular
I'm quite new with Angular and I am trying to bring some structure in my website I am building with Angular.

Now I have a Controller where I have some functions which I use on multiple pages. I have heard that I could better make a service out of these functions. How am I able to do this?

This is my Controller in current state:
How can I make a service from $scope.city function and $scope.specials function?

```<code>app.controller('DataCtrl', function($scope,$http){
  $scope.city = function(){
    $scope.items = [];

    $http.get('/getdata').then(function(d){
      $scope.items = d.data;
      $scope.selectedItem = $scope.items[0];
    },function(err){
      console.log(err);
    });
  };

  /* Function for specialization data */
  $scope.specials = function(){
    $scope.special = [];

    $http.get('/specialdata').then(function(d){
      $scope.special = d.data[0];
    },function(err){
      console.log(err);
    });
  };
});
</code>```

答:
Try like this </p>

```<code> app.factory('getServiceData', function($http){
 return {
    getSpecials: function() {
      return $http.get("/specialdata")
     }
   };
});
</code>```

<p>and for use it in controller inject factory or service into controller as you see in bellow.  </p>

```<code> app.controller('DataCtrl', function($scope,getServiceData){
 getServiceData.getSpecials().then(function(response){
        $scope.special =  response.data[0];
    })
  };
</code>```

Title: Services in Angular

Body:
I'm quite new with Angular and I am trying to bring some structure in my website I am building with Angular.

Now I have a Controller where I have some functions which I use on multiple pages. I have heard that I could better make a service out of these functions. How am I able to do this?

This is my Controller in current state:
How can I make a service from $scope.city function and $scope.specials function?

app.controller('DataCtrl', function($scope,$http){
  $scope.city = function(){
    $scope.items = [];

    $http.get('/getdata').then(function(d){
      $scope.items = d.data;
      $scope.selectedItem = $scope.items[0];
    },function(err){
      console.log(err);
    });
  };

  /* Function for specialization data */
  $scope.specials = function(){
    $scope.special = [];

    $http.get('/specialdata').then(function(d){
      $scope.special = d.data[0];
    },function(err){
      console.log(err);
    });
  };
});

Body:
Try like this

 app.factory('getServiceData', function($http){
 return {
    getSpecials: function() {
      return $http.get("/specialdata")
     }
   };
});

and for use it in controller inject factory or service into controller as you see in bellow.

 app.controller('DataCtrl', function($scope,getServiceData){
 getServiceData.getSpecials().then(function(response){
        $scope.special =  response.data[0];
    })
  };


问:
Append Words from different arrays to div
this might be easy but I cannot see the forest because of trees.
I have several arrays of words and fade-in-times.

This should happen:
On Start words from array PartA are added to the div with respect of each individual time. For this I use setTimeout().

Not working.
If a User clicks on a link added from partA Words from array partB (or partN) should be append to the div as well.  How can I pass in the current array of interest to function buildString(what) ?

This is where I hang

// WORDS!
partA = [
        ["Hello", 300],
        ["my", 300],
        ["name", 300],
        ["is", 600],
        [".", 300],
    ];

PartB = [
        ["Good", 300],
        ["Bye", 300]
    ];

// Function to iterate over array
var i = 1;
function buildString(what) {
   $('div').append(partA[i-1][0]+' ');
   if(i > partA.length-1) return;
   i++;
   window.setTimeout(buildString, partA[i-1][1]);
}

// Bind click on link to continue with different array
$('a.partB').click(function(e){
  e.preventDefault();
  // Continue with part B
  // Not working
 buildString(partB);
})

// Begin with first array
buildString(partA);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
    font-size: 50pt;
    font-family: Arial;
    letter-spacing: -1px;
    margin:2rem;
}</code>```

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

<p><strong>EDIT:</strong>
When using what in my setTimeout function and injecting the array:</p>

```function buildString(what) {
   $('div').append(what[i-1][0]+' ');
   if(i > what.length-1) return;
   i++;
   window.setTimeout(buildString(what), what[i-1][1]);
}
```

The words do not get appended each after another but the whole sting is added.

https://jsfiddle.net/telemark/yxkazn1k/2/

答:
Do you mean something like this? https://jsfiddle.net/hallleron/4x93qx1x/

I use a for loop for execution and add your timeout values each cicle:

```<code>var box = $('div');
var before;
function buildString(array) {
    before = 0;
   for(var i = 0; i < array.length; i++){
    appendToBox(array[i]);
   }
}

function appendToBox(obj){
    setTimeout(function(){
        box.append(obj[0] + ' ');
    }, obj[1] + before);
    before += obj[1];
}
</code>```

Using this method ensures that every timeout value can be executed properly.

EDIT:

And you can pass as many Arrays as you want to you buildString(array) function.

Body:
this might be easy but I cannot see the forest because of trees.
I have several arrays of words and fade-in-times.

This should happen:
On Start words from array PartA are added to the div with respect of each individual time. For this I use setTimeout().

Not working.
If a User clicks on a link added from partA Words from array partB (or partN) should be append to the div as well.  How can I pass in the current array of interest to function buildString(what) ?

This is where I hang

// WORDS!
partA = [
        ["Hello", 300],
        ["my", 300],
        ["name", 300],
        ["is", 600],
        [".", 300],
    ];

PartB = [
        ["Good", 300],
        ["Bye", 300]
    ];

// Function to iterate over array
var i = 1;
function buildString(what) {
   $('div').append(partA[i-1][0]+' ');
   if(i > partA.length-1) return;
   i++;
   window.setTimeout(buildString, partA[i-1][1]);
}

// Bind click on link to continue with different array
$('a.partB').click(function(e){
  e.preventDefault();
  // Continue with part B
  // Not working
 buildString(partB);
})

// Begin with first array
buildString(partA);

#div {
    font-size: 50pt;
    font-family: Arial;
    letter-spacing: -1px;
    margin:2rem;
}

EDIT:
When using what in my setTimeout function and injecting the array:

function buildString(what) {
   $('div').append(what[i-1][0]+' ');
   if(i > what.length-1) return;
   i++;
   window.setTimeout(buildString(what), what[i-1][1]);
}

The words do not get appended each after another but the whole sting is added.

https://jsfiddle.net/telemark/yxkazn1k/2/

Body:
Do you mean something like this? https://jsfiddle.net/hallleron/4x93qx1x/

I use a for loop for execution and add your timeout values each cicle:

var box = $('div');
var before;
function buildString(array) {
    before = 0;
   for(var i = 0; i < array.length; i++){
    appendToBox(array[i]);
   }
}

function appendToBox(obj){
    setTimeout(function(){
        box.append(obj[0] + ' ');
    }, obj[1] + before);
    before += obj[1];
}

Using this method ensures that every timeout value can be executed properly.

EDIT:

And you can pass as many Arrays as you want to you buildString(array) function.


问:
sql-to fetch reciprocal data
I have a table in Oracle db, which contains data like this, a+b, b+a, c+d, d+c.

My question is, when a+b = b+a, how to fetch distinct records.

```<code>PK         CODE
1000    87DIA4+BAJI204
1001    87DIA4+BIJI939
1002    87DIA4+C3IDI02
1003    87DIA4+C3IZI419
1004    BAJI204+87DIA4
1005    BIJI939+87DIA4
1006    C3IDI02+87DIA4
1007    C3IZI419+87DIA4
</code>```

答:
Write a sub-query which splits out the two elements from the CODE column. Then use a self-join to find the reciprocal pairs:

```<code>SQL> with cte as ( select pk
  2                       , substr(code, 1, instr(code, '+')-1) as str1
  3                       , substr(code, instr(code, '+')+1) as str2
  4                from your_table)
  5  select a.pk as a_pk
  6         , b.pk as b_pk
  7        , a.str1
  8        , a.str2
  9  from cte a
 10       join cte b
 11        on a.str1 = b.str2
 12           and a.str2 = b.str1
 13  where a.pk < b.pk
 14  order by a_pk;

      A_PK       B_PK STR1         STR2
---------- ---------- ------------ ------------
      1000       1004 87DIA4       BAJI204
      1001       1005 87DIA4       BIJI939
      1002       1006 87DIA4       C3IDI02
      1003       1007 87DIA4       C3IZI419

4 rows selected.

SQL>
</code>```

The WHERE clause ensures the result set contains only one instance of each reciprocal pair.

Title: sql-to fetch reciprocal data

Body:
I have a table in Oracle db, which contains data like this, a+b, b+a, c+d, d+c.

My question is, when a+b = b+a, how to fetch distinct records.

PK         CODE
1000    87DIA4+BAJI204
1001    87DIA4+BIJI939
1002    87DIA4+C3IDI02
1003    87DIA4+C3IZI419
1004    BAJI204+87DIA4
1005    BIJI939+87DIA4
1006    C3IDI02+87DIA4
1007    C3IZI419+87DIA4

Body:
Write a sub-query which splits out the two elements from the CODE column. Then use a self-join to find the reciprocal pairs:

SQL> with cte as ( select pk
  2                       , substr(code, 1, instr(code, '+')-1) as str1
  3                       , substr(code, instr(code, '+')+1) as str2
  4                from your_table)
  5  select a.pk as a_pk
  6         , b.pk as b_pk
  7        , a.str1
  8        , a.str2
  9  from cte a
 10       join cte b
 11        on a.str1 = b.str2
 12           and a.str2 = b.str1
 13  where a.pk < b.pk
 14  order by a_pk;

      A_PK       B_PK STR1         STR2
---------- ---------- ------------ ------------
      1000       1004 87DIA4       BAJI204
      1001       1005 87DIA4       BIJI939
      1002       1006 87DIA4       C3IDI02
      1003       1007 87DIA4       C3IZI419

4 rows selected.

SQL>

The WHERE clause ensures the result set contains only one instance of each reciprocal pair.


问:
Strongly typing a view to a class from the webservice?
Currently I use a webservice to call the database and pass back an object back to my MVC app. The purpose is to display the data on a table.

So would it better if I just type the View to the class from the webservice, or should it always be typed to a model inside the MVC app? If I type it to a model inside my app, then I would have to create a new instance of the class and copy all the information over, which seems like a waste of time.

Which one is considered best practice? Strongly typing to a class from the webservice or a class within the MVC app?

Cheers.

答: You shouldn't have a dependency on the class from WebService. MVC's ViewModel is desined to be simple data representation. You can easely map your WebService class to ViewModel class using AutoMapper. This is considered as best practice and described in this book.</p>


问:
Trying to center one column with content to the left in CSS
I have a design to implement that is supposed to have a centered column of shortcuts and then a text to the left of each.
It should look like this:

The column of the shortcuts should be centered below the title.

I can't get this to work with a responsive design.
The markup I have is ATM this:

```<code><div class="ax-learn__shortcuts">
 <h2>Learn shortcuts</h2>
 <div class="ax-learn__shortcuts-row">
   <div>Go to home:</div>
   <div><kbd>g</kbd>then<kbd>h</kbd></div>
 </div>
 <div class="ax-learn__shortcuts-row">
   <div>Go to search:</div>
   <div><kbd>g</kbd>then<kbd>s</kbd></div>
 </div>
 <div class="ax-learn__shortcuts-row">
   <div>Go to learn:</div>
   <div><kbd>g</kbd>then<kbd>l</kbd></div>
 </div>
</code>```

And the current CSS, which doesn't center it perfectly at all, is this:

```<code>.ax-learn__shortcuts {
  display: flex;
  flex-direction: column;
}

.ax-learn__shortcuts h2 {
  text-align: center;
}

.ax-learn__shortcuts-row {
  display: flex;
  justify-content: center;
  align-items: center;
}
</code>```

And here's an example on Codepen

答:
By adding a pseudo as a ghost element, that matches the labels on the left, you can set that and the left labels to flex: 1, and they will take all available space and leave the kbd in the middle.

Then text-align: right for labels and margin: 0 10px for kbd, and it will look nice too :)

I added these rules, to achieve that.

```<code>.ax-learn__shortcuts-row::after {
  content: '';
}
.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
  flex: 1;
}
.ax-learn__shortcuts-row div:nth-child(1) {
  text-align: right;
}
.ax-learn__shortcuts-row div:nth-child(2) {
  margin: 0 10px;
}
</code>```

Updated codepen

Stack snippet

.ax-learn__shortcuts-row {
  display: flex;
  justify-content: center;
  align-items: center;
}

.ax-learn__shortcuts-row::after {
  content: '';
}

.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
  flex: 1;
}

.ax-learn__shortcuts-row div:nth-child(1) {
  text-align: right;
}

.ax-learn__shortcuts-row div:nth-child(2) {
  margin: 0 10px;
}

.ax-learn__shortcuts {
  display: flex;
  flex-direction: column;
}
.ax-learn__shortcuts kbd {
  padding: 7px 15px;
  border: 2px solid black;
  border-radius: 5px;
  background: white;
  display: inline-block;
}
.ax-learn__shortcuts kbd:first-of-type {
  margin-right: 15px;
}
.ax-learn__shortcuts kbd:last-of-type {
  margin-left: 15px;
}
.ax-learn__shortcuts h2 {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ax-learn__shortcuts">
  <h2>Learn shortcuts</h2>
  <div class="ax-learn__shortcuts-row">
    <div>Go to home:</div>
    <div><kbd>g</kbd>then<kbd>h</kbd></div>
  </div>
  <div class="ax-learn__shortcuts-row">
    <div>Go to search:</div>
    <div><kbd>g</kbd>then<kbd>s</kbd></div>
  </div>
  <div class="ax-learn__shortcuts-row">
    <div>Go to learn:</div>
    <div><kbd>g</kbd>then<kbd>l</kbd></div>
  </div>
</div></code>```

Body:
I have a design to implement that is supposed to have a centered column of shortcuts and then a text to the left of each.
It should look like this:

The column of the shortcuts should be centered below the title.

I can't get this to work with a responsive design.
The markup I have is ATM this:

Learn shortcuts

Go to home:

gthenh

Go to search:

gthens

Go to learn:

gthenl

And the current CSS, which doesn't center it perfectly at all, is this:

.ax-learn__shortcuts {
  display: flex;
  flex-direction: column;
}

.ax-learn__shortcuts h2 {
  text-align: center;
}

.ax-learn__shortcuts-row {
  display: flex;
  justify-content: center;
  align-items: center;
}

And here's an example on Codepen

Body:
By adding a pseudo as a ghost element, that matches the labels on the left, you can set that and the left labels to flex: 1, and they will take all available space and leave the kbd in the middle.

Then text-align: right for labels and margin: 0 10px for kbd, and it will look nice too :)

I added these rules, to achieve that.

.ax-learn__shortcuts-row::after {
  content: '';
}
.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
  flex: 1;
}
.ax-learn__shortcuts-row div:nth-child(1) {
  text-align: right;
}
.ax-learn__shortcuts-row div:nth-child(2) {
  margin: 0 10px;
}

Updated codepen

Stack snippet

.ax-learn__shortcuts-row {
  display: flex;
  justify-content: center;
  align-items: center;
}

.ax-learn__shortcuts-row::after {
  content: '';
}

.ax-learn__shortcuts-row::after,
.ax-learn__shortcuts-row div:nth-child(1) {
  flex: 1;
}

.ax-learn__shortcuts-row div:nth-child(1) {
  text-align: right;
}

.ax-learn__shortcuts-row div:nth-child(2) {
  margin: 0 10px;
}

.ax-learn__shortcuts {
  display: flex;
  flex-direction: column;
}
.ax-learn__shortcuts kbd {
  padding: 7px 15px;
  border: 2px solid black;
  border-radius: 5px;
  background: white;
  display: inline-block;
}
.ax-learn__shortcuts kbd:first-of-type {
  margin-right: 15px;
}
.ax-learn__shortcuts kbd:last-of-type {
  margin-left: 15px;
}
.ax-learn__shortcuts h2 {
  text-align: center;
}

<div class="ax-learn__shortcuts">
  <h2>Learn shortcuts</h2>
  <div class="ax-learn__shortcuts-row">
    <div>Go to home:</div>
    <div><kbd>g</kbd>then<kbd>h</kbd></div>
  </div>
  <div class="ax-learn__shortcuts-row">
    <div>Go to search:</div>
    <div><kbd>g</kbd>then<kbd>s</kbd></div>
  </div>
  <div class="ax-learn__shortcuts-row">
    <div>Go to learn:</div>
    <div><kbd>g</kbd>then<kbd>l</kbd></div>
  </div>
</div>


答:
In your buildString function you did not use you parameter.

I think that using an internal index in sted of a global i would be much better.

Third and most imporant if you create dinamically an element (like you did with your link) you cannot bind an event of an element that dows not already exist.

What you can do is to bind the click event to an anchestor like I did in the example. Basically you bind the click event to every descendant of document of the class a.partB

// WORDS!
partA = [
        ["Hello", 300],
        ["my", 300],
        ["name", 300],
        ["is", 600],
        [".", 300],
    ];

partB = [
        ["Good", 300],
        ["Bye", 300]
    ];

// Function to iterate over array
function buildString(part, index) {
   console.log('part');
   console.log(part);
   console.log('with index ' + index);
   console.log(part[index]);
   $('div').append(part[index][0]+' ');
   if(index == part.length-1) return;
   index++;
   window.setTimeout(buildString, part[index-1][1], part, index);
}

$(document).on('click', 'a.partB', function(e){
  e.preventDefault();
  // Continue with part B
  console.log('here we go B');
 buildString(partB, 0);
});

buildString(partA, 0);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
    font-size: 50pt;
    font-family: Arial;
    letter-spacing: -1px;
    margin:2rem;
}</code>```

```

Title: Append Words from different arrays to div

Body:
In your buildString function you did not use you parameter.

I think that using an internal index in sted of a global i would be much better.

Third and most imporant if you create dinamically an element (like you did with your link) you cannot bind an event of an element that dows not already exist.

What you can do is to bind the click event to an anchestor like I did in the example. Basically you bind the click event to every descendant of document of the class a.partB

// WORDS!
partA = [
        ["Hello", 300],
        ["my", 300],
        ["name", 300],
        ["<a href='#' class='partB' >is</a>", 600],
        [".", 300],
    ];

partB = [
        ["Good", 300],
        ["Bye", 300]
    ];

// Function to iterate over array
function buildString(part, index) {
   console.log('part');
   console.log(part);
   console.log('with index ' + index);
   console.log(part[index]);
   $('div').append(part[index][0]+' ');
   if(index == part.length-1) return;
   index++;
   window.setTimeout(buildString, part[index-1][1], part, index);
}

$(document).on('click', 'a.partB', function(e){
  e.preventDefault();
  // Continue with part B
  console.log('here we go B');
 buildString(partB, 0);
});

buildString(partA, 0);

#div {
    font-size: 50pt;
    font-family: Arial;
    letter-spacing: -1px;
    margin:2rem;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>


问:
How to get a kendo grid on a kendo template
Firstly I have made a Kendo grid. Each row of the grid has a button on it, which on-click opens a Kendo template (pop-up). still here it's fine.

Is it possible to add another grid in the popup and add editable child items(like grid hierarchy) to each grid row?

This is my main grid:

var grid= $("#Grid").kendoGrid({
        columns: [
          { field: "Name", title: "Name" },
          { field: "Description", title:"Description"},
          { field: "Remarks", title:"Remarks" },
          { command: { name: "details", text: "....", click: showDetails }, title: "Button", attributes: {
              style: "text-align: center;"
          }
          },
          {field:"Status",title:"Status"},
          ],

{......... data source and irrelevant code }

});```
</div>
</div>
</p>

<p><strong>Code for window pop-up and button on-click function:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>wnd = $("#details")
                        .kendoWindow({
                            title: "Details",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 400,
                            height:600
                        }).data("kendoWindow");

    detailsTemplate = kendo.template($("#template").html());
    });

    function showDetails(e) {
        e.preventDefault();

        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        wnd.content(detailsTemplate(dataItem));
        wnd.center().open();
    }</code>```

Code for template look like:

```

The div tag including window grid is not displaying the grid but displaying remaining other things.
can you suggest what mistake I have done in the code
Secondly, Can you help me with the code to get a child row for each grid row.

Thank you

EDIT This is the dojo link of whole code: http://dojo.telerik.com/igOroG

答:
You are trying to initialise an element before it has been rendered in the x-kendo-template, so just move your grid instantiation to after the open of the kendoWindow.

```<code>function showDetails(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    wnd.content(detailsTemplate(dataItem));
    wnd.center().open();
    // grid definition here
    var grid = $("#windowgrid").kendoGrid({
        .....
    }).data("kendoGrid");
}
</code>```

"Code to get a child row for each grid row"

You can use detailInit with detailTemplate on the grids in order to achieve this. With your detailInit function, you will be able to access the data at that specific row using [e.data].

```<code>// gets elements on detailRow
var detailRow = e.detailRow;
// get the data at the expanded row
var dataList = [e.data];
</code>```

I have updated your Dojo example to display the changes required to firstly initialise the grid and extended the code to provide detail rows for the first grid.

EDIT

In order to apply a filtered dataSource to the pop-up grid based on the value selected, you can use the filter function on the data before applying to the Kendo DataSource:

```<code>var filteredDataArr = dataArr.filter(function(el) {
    return el.NId == e.NId
});
</code>```

el being the element in the data array and e.NId being the selected NId in the parent grid.

Updated Dojo example to demonstrate the above in action.

Body:
Firstly I have made a Kendo grid. Each row of the grid has a button on it, which on-click opens a Kendo template (pop-up). still here it's fine.

Is it possible to add another grid in the popup and add editable child items(like grid hierarchy) to each grid row?

This is my main grid:

var grid= $("#Grid").kendoGrid({
        columns: [
          { field: "Name", title: "Name" },
          { field: "Description", title:"Description"},
          { field: "Remarks", title:"Remarks" },
          { command: { name: "details", text: "....", click: showDetails }, title: "Button", attributes: {
              style: "text-align: center;"
          }
          },
          {field:"Status",title:"Status"},
          ],

{......... data source and irrelevant code }

});

Code for window pop-up and button on-click function:

wnd = $("#details")
                        .kendoWindow({
                            title: "Details",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 400,
                            height:600
                        }).data("kendoWindow");

    detailsTemplate = kendo.template($("#template").html());
    });

    function showDetails(e) {
        e.preventDefault();

        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        wnd.content(detailsTemplate(dataItem));
        wnd.center().open();
    }

Code for template look like:

The div tag including window grid is not displaying the grid but displaying remaining other things.
can you suggest what mistake I have done in the code
Secondly, Can you help me with the code to get a child row for each grid row.

Thank you

EDIT This is the dojo link of whole code: http://dojo.telerik.com/igOroG

Body:
You are trying to initialise an element before it has been rendered in the x-kendo-template, so just move your grid instantiation to after the open of the kendoWindow.

function showDetails(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    wnd.content(detailsTemplate(dataItem));
    wnd.center().open();
    // grid definition here
    var grid = $("#windowgrid").kendoGrid({
        .....
    }).data("kendoGrid");
}

"Code to get a child row for each grid row"

You can use detailInit with detailTemplate on the grids in order to achieve this. With your detailInit function, you will be able to access the data at that specific row using [e.data].

// gets elements on detailRow
var detailRow = e.detailRow;
// get the data at the expanded row
var dataList = [e.data];

I have updated your Dojo example to display the changes required to firstly initialise the grid and extended the code to provide detail rows for the first grid.

EDIT

In order to apply a filtered dataSource to the pop-up grid based on the value selected, you can use the filter function on the data before applying to the Kendo DataSource:

var filteredDataArr = dataArr.filter(function(el) {
    return el.NId == e.NId
});

el being the element in the data array and e.NId being the selected NId in the parent grid.

Updated Dojo example to demonstrate the above in action.


问:
Reference to an instance method of a particular object breaks the type-safety in Java?
Does the notion of a reference to an instance method of a particular object break the type-safety in Java?

According to

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

you can have a custom class ComparisonProvider  that DOES not implement the Comparator  interface, and still use an instance of this class as the second argument of the method

Arrays.sort(T[] a, Comparator c)

Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?

In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.

This means, that we are loosing Type-safety in Java, do we?

答:
Comparator is a functional interface, which means that when requested you can pass an instance of a class implementing it, use a lambda expression that conforms to the type of single abstract method declared in it or use a method reference that also conforms to.

Java 8 Functional interface makes the difference. This tries to catch the concept of function. Afterall what is important in Comparator is not the type itself but the method (and its type) that should be provided at runtime. In pre Java 8 you need to provide a function object, while in Java 8 you can simply provide the function (just what is needed).

So for the type system everything is correct, provided that the lambdas or references you use are of the type of the method of the functional interface.


问:
Getting a KeyError when using Python and BeautifulSoup
Trying to build a script to scrape the text and the number of stars from the corresponding review from Yelp and store the data in an Excel file.

A snippet of the HTML code that I am working with is below:

```<code><div class="review-content">
<div class="biz-rating biz-rating-large clearfix">
<div>
<div class="i-stars i-stars--regular-5 rating-large" title="5.0 star
rating">
<img alt="5.0 star rating" class="offscreen" height="303"
src="https://s3-media1.fl.yelpcdn.com/assets/srv0/yelp_design_web/41341496d9db/assets/img/stars/stars.png" width="84"/>
</div>
</div>
<span class="rating-qualifier">
    5/10/2017
</span>
</div>
<p lang="en">This place is really fun and cute. I was happy to discover
it.. <br/><br/>They also have beer and wine here, which is kind of a
nice bonus. The sangria is good..</p>
</div>
</code>```

My python code is below:

```<code>import requests
from bs4 import BeautifulSoup as soup
import xlsxwriter

#Index for xlsxwriter
row = 1
i = 0

#Index for all of the review-containing pages for one restaurant.

page_num = 0

#Call xlsxwriter and name the output file.
workbook = xlsxwriter.Workbook('file_1.xlsx')
worksheet = workbook.add_worksheet()

#Write in the header for the file
worksheet.write('A1','num_stars')
worksheet.write('B1', 'review_text')

#Loop to scrape all of the reviews off of one single page with a
specific url and advance the to all subsequent pages of the restaurant.

while page_num <= 260:

  url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach?
  start=%s" % page_num

  r = requests.get(url)
  page_soup = soup(r.content, "lxml")

  review_container = page_soup.findAll("div", {"class": "review-
  content"})

  for review in review_container:
      string = str(review.p.text)
      stars = float(review[i].select('img')[0]['alt'].split()[0])
      worksheet.write(row, 0, stars)
      worksheet.write(row, 1, string)
    row += 1
    i += 1

  #Advance counter in order to scrape the next url for the restaurant
  page_num += 20

workbook.close()
</code>```

The problem when running this script is that I get the following error:

```<code>-----------------------------------------------------------------------
----
KeyError                                  Traceback (most recent call last)
<ipython-input-18-a73ecb4ef119> in <module>()
 38     for review in review_container:
 39         string = str(review.p.text)
---> 40         stars = float(review[i].select('img')[0]['alt'].split()[0])
 41         worksheet.write(row, 0, stars)
 42         worksheet.write(row, 1, string)

//anaconda/lib/python3.5/site-packages/bs4/element.py in
__getitem__(self, key)
956         """tag[key] returns the value of the 'key' attribute for the tag,
957         and throws an exception if it's not there."""
--> 958         return self.attrs[key]
959
960     def __iter__(self):

KeyError: 0
</code>```

I understand that the line that is causing the code is the one below:

```<code>stars = float(review[i].select('img')[0]['alt'].split()[0])
</code>```

However, I don't know enough to understand how to correct the error to make the script work.

What do I need to change in my code in order to get the script to work?

答:
I believe it should just be </p>

```<code>stars = float(review.select('img')[0]['alt'].split()[0])
</code>```

Body:
Trying to build a script to scrape the text and the number of stars from the corresponding review from Yelp and store the data in an Excel file.

A snippet of the HTML code that I am working with is below:

    5/10/2017

This place is really fun and cute. I was happy to discover
it..

They also have beer and wine here, which is kind of a
nice bonus. The sangria is good..

My python code is below:

import requests
from bs4 import BeautifulSoup as soup
import xlsxwriter

#Index for xlsxwriter
row = 1
i = 0

#Index for all of the review-containing pages for one restaurant.

page_num = 0

#Call xlsxwriter and name the output file.
workbook = xlsxwriter.Workbook('file_1.xlsx')
worksheet = workbook.add_worksheet()

#Write in the header for the file
worksheet.write('A1','num_stars')
worksheet.write('B1', 'review_text')

#Loop to scrape all of the reviews off of one single page with a
specific url and advance the to all subsequent pages of the restaurant.

while page_num <= 260:

  url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach?
  start=%s" % page_num

  r = requests.get(url)
  page_soup = soup(r.content, "lxml")

  review_container = page_soup.findAll("div", {"class": "review-
  content"})

  for review in review_container:
      string = str(review.p.text)
      stars = float(review[i].select('img')[0]['alt'].split()[0])
      worksheet.write(row, 0, stars)
      worksheet.write(row, 1, string)
    row += 1
    i += 1

  #Advance counter in order to scrape the next url for the restaurant
  page_num += 20

workbook.close()

The problem when running this script is that I get the following error:

-----------------------------------------------------------------------
----
KeyError                                  Traceback (most recent call last)
<ipython-input-18-a73ecb4ef119> in <module>()
 38     for review in review_container:
 39         string = str(review.p.text)
---> 40         stars = float(review[i].select('img')[0]['alt'].split()[0])
 41         worksheet.write(row, 0, stars)
 42         worksheet.write(row, 1, string)

//anaconda/lib/python3.5/site-packages/bs4/element.py in
__getitem__(self, key)
956         """tag[key] returns the value of the 'key' attribute for the tag,
957         and throws an exception if it's not there."""
--> 958         return self.attrs[key]
959
960     def __iter__(self):

KeyError: 0

I understand that the line that is causing the code is the one below:

stars = float(review[i].select('img')[0]['alt'].split()[0])

However, I don't know enough to understand how to correct the error to make the script work.

What do I need to change in my code in order to get the script to work?

Body:
I believe it should just be

stars = float(review.select('img')[0]['alt'].split()[0])


问:
Publish test utils from maven project
I created a library in maven that can be extended by implementing some interfaces. To test the default implementation I have written some hamcrest matchers that currently live in src/test/java.

However, I think they might be useful for users of the library if they want to test their customization.

So how can I make them available? Moving them to src/main would require to make hamcrest a runtime dependency and I don't want that.

答: As you said, move it to src/main in a new project. Let that project only be used in a test dependency and you don't pollute your module's classpath.</p>

Title: Publish test utils from maven project


问:
spread syntax with map doesn't work
```<code>data.map(obj =>
        {person_name: obj.user.name,
        ...obj})
</code>```

Why above code failed?

my data look like this

```<code>[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]
</code>```

I want to 'pull' the obj.user.name out from the nested obj.

答:
You can't spread an object like this (throws SyntaxError at ....

I would write it using Object.assign:

```<code>data.map(obj => Object.assign({person_name: obj.user.name}, obj ));
</code>```

Title: spread syntax with map doesn't work

Body:
data.map(obj =>
        {person_name: obj.user.name,
        ...obj})

Why above code failed?

my data look like this

[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]

I want to 'pull' the obj.user.name out from the nested obj.

Body:
You can't spread an object like this (throws SyntaxError at ....

I would write it using Object.assign:

data.map(obj => Object.assign({person_name: obj.user.name}, obj ));


问:
show soft keyboard onResume
Couldn't find a clear answer to this one, basically I have an activity with an EditText field. The soft keyboard is set to visible within manifest, so keyboard is visible when activity starts however if user navigates away and returns using the back button the keyboard is hidden (I need it visible on resume).
I have added the below method to my onResume but doesn't seem to work?
Any ideas what I'm missing here?</p>

```<code>private void showSoftKeyboard(){
    quickListName.requestFocus();
    InputMethodManager imm = D(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(quickListName,InputMethodManager.SHOW_IMPLICIT);
}
</code>```

答:
try {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }</p>

Title: show soft keyboard onResume

Body:
Couldn't find a clear answer to this one, basically I have an activity with an EditText field. The soft keyboard is set to visible within manifest, so keyboard is visible when activity starts however if user navigates away and returns using the back button the keyboard is hidden (I need it visible on resume).
I have added the below method to my onResume but doesn't seem to work?
Any ideas what I'm missing here?

private void showSoftKeyboard(){
    quickListName.requestFocus();
    InputMethodManager imm = D(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(quickListName,InputMethodManager.SHOW_IMPLICIT);
}


问:
Get index of enum with extension of String,
I have an Enum that looks like this:

```<code>enum Status: String {
    case online = "online"
    case offline = "offline"
    case na = "na"
}
</code>```

I need the String value and I know how to get it, but my question is if it´s possible to get the index value too for each case in the enum.

0 for online, 1 for offline and 2 for na.

I will add more statues in the future.

答:
How about this.

```<code>enum Status: Int {
    case online = 0
    case offline = 1
    case na = 2
}
</code>```

You can get the string value and the integer index both.

```<code>// enum as string
let enumName = "\(Status.online)" // `online`

// enum as int value
let enumValue = Status.online.rawValue // 0

// enum from int
let enumm = Status.init(rawValue: 1)
</code>```

Hope it helps. Thanks.

Body:
I have an Enum that looks like this:

enum Status: String {
    case online = "online"
    case offline = "offline"
    case na = "na"
}

I need the String value and I know how to get it, but my question is if it´s possible to get the index value too for each case in the enum.

0 for online, 1 for offline and 2 for na.

I will add more statues in the future.

Body:
How about this.

enum Status: Int {
    case online = 0
    case offline = 1
    case na = 2
}

You can get the string value and the integer index both.

// enum as string
let enumName = "\(Status.online)" // `online`

// enum as int value
let enumValue = Status.online.rawValue // 0

// enum from int
let enumm = Status.init(rawValue: 1)

Hope it helps. Thanks.


问:
Given a bitonic array and element x in the array, find the index of x in 2log(n) time
First, a bitonic array for this question is defined as one such that for some index K in an array of length N where 0 < K < N - 1 and 0 to K is a monotonically increasing sequence of integers, and K to N - 1 is a monotonically decreasing sequence of integers.

Example: [1, 3, 4, 6, 9, 14, 11, 7, 2, -4, -9]. It monotonically increases from 1 to 14, then decreases from 14 to -9.

The precursor to this question is to solve it in 3log(n), which is much easier. One altered binary search to find the index of the max, then two binary searchs for 0 to K and K + 1 to N - 1 respectively.

I presume the solution in 2log(n) requires you solve the problem without finding the index of the max. I've thought about overlapping the binary searches, but beyond that, I'm not sure how to move forward.

答:
```<code>    public int FindLogarithmicGood(int value)
    {
        int lo = 0;
        int hi = _bitonic.Length - 1;
        int mid;
        while (hi - lo > 1)
        {
            mid = lo + ((hi - lo) / 2);
            if (value < _bitonic[mid])
            {
                return DownSearch(lo, hi - lo + 1, mid, value);
            }
            else
            {
                if (_bitonic[mid] < _bitonic[mid + 1])
                    lo = mid;
                else
                    hi = mid;
            }
        }

        return _bitonic[hi] == value
            ? hi
            : _bitonic[lo] == value
                ? lo
                : -1;
    }
</code>```

where DownSearch is

```<code>    public int DownSearch(int index, int count, int mid, int value)
    {
        int result = BinarySearch(index, mid - index, value);
        if (result < 0)
            result = BinarySearch(mid, index + count - mid, value, false);
        return result;
    }
</code>```

and BinarySearch is

```<code>    /// <summary>
    /// Exactly log(n) on average and worst cases.
    /// Note: System.Array.BinarySerch uses 2*log(n) in the worst case.
    /// </summary>
    /// <returns>array index</returns>
    public int BinarySearch(int index, int count, int value, bool asc = true)
    {
        if (index < 0 || count < 0)
            throw new ArgumentOutOfRangeException();
        if (_bitonic.Length < index + count)
            throw new ArgumentException();

        if (count == 0)
            return -1;

        // "lo minus one" trick
        int lo = index - 1;
        int hi = index + count - 1;
        int mid;
        while (hi - lo > 1)
        {
            mid = lo + ((hi - lo) / 2);
            if ((asc && _bitonic[mid] < value) || (!asc && _bitonic[mid] > value))
                lo = mid;
            else
                hi = mid;
        }

        return _bitonic[hi] == value ? hi : -1;
    }
</code>```

github

Body:
    public int FindLogarithmicGood(int value)
    {
        int lo = 0;
        int hi = _bitonic.Length - 1;
        int mid;
        while (hi - lo > 1)
        {
            mid = lo + ((hi - lo) / 2);
            if (value < _bitonic[mid])
            {
                return DownSearch(lo, hi - lo + 1, mid, value);
            }
            else
            {
                if (_bitonic[mid] < _bitonic[mid + 1])
                    lo = mid;
                else
                    hi = mid;
            }
        }

        return _bitonic[hi] == value
            ? hi
            : _bitonic[lo] == value
                ? lo
                : -1;
    }

where DownSearch is

    public int DownSearch(int index, int count, int mid, int value)
    {
        int result = BinarySearch(index, mid - index, value);
        if (result < 0)
            result = BinarySearch(mid, index + count - mid, value, false);
        return result;
    }

and BinarySearch is

    /// <summary>
    /// Exactly log(n) on average and worst cases.
    /// Note: System.Array.BinarySerch uses 2*log(n) in the worst case.
    /// </summary>
    /// <returns>array index</returns>
    public int BinarySearch(int index, int count, int value, bool asc = true)
    {
        if (index < 0 || count < 0)
            throw new ArgumentOutOfRangeException();
        if (_bitonic.Length < index + count)
            throw new ArgumentException();

        if (count == 0)
            return -1;

        // "lo minus one" trick
        int lo = index - 1;
        int hi = index + count - 1;
        int mid;
        while (hi - lo > 1)
        {
            mid = lo + ((hi - lo) / 2);
            if ((asc && _bitonic[mid] < value) || (!asc && _bitonic[mid] > value))
                lo = mid;
            else
                hi = mid;
        }

        return _bitonic[hi] == value ? hi : -1;
    }

github


问:
RadTree - How to save expanded state
We are using Telerik 2017.1.228.45 RadTree controls. We have implemented RadTree contract inside a usercontrol and it's getting called through a master page. all Radtree nodes has a customUrl field populated,so when they are clicked on the same page, a user control appears and when some changes are made to that user control and is closed, RadTree loses its expanded state.

Is there a way to persist RadTree in that expanded state please? if yes, then how or if you could point me towards the right direction, that'll be great.

Thank you

答:
This answer has solved my issue:

http://www.telerik.com/support/code-library/save-the-expanded-state-of-the-treenodes-when-the-treeview-is-being-bound-upon-each-postback

Title: RadTree - How to save expanded state


问:
Scala array to Java
I have this invocation from scala class to Java

```<code>  private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations))
  }
</code>```

And the java class expect

```<code> public GenericXmlApplicationContext(String... resourceLocations) {
        this.load(resourceLocations);
        this.refresh();
    }
</code>```

I´ve tried to cast this with import collection.JavaConverters._

But I cannot make it works with Arrays.

Any suggestion?

答:
You do not want an Array, but a varargs.

You should do new GenericXmlApplicationContext(resourceLocations: _*)

Title: Scala array to Java

Body:
I have this invocation from scala class to Java

  private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations))
  }

And the java class expect

 public GenericXmlApplicationContext(String... resourceLocations) {
        this.load(resourceLocations);
        this.refresh();
    }

I´ve tried to cast this with import collection.JavaConverters._

But I cannot make it works with Arrays.

Any suggestion?


问:
What is universal method for `get or default` in python?
I would like to get an attribute of mongoengine model object but it's missing (how it's often in mongo):

unit.city gives me AttributeError

unit.get('city') says that 'Unit' object has no attribute 'get' and I can't find any appropriate method by dir(unit).

So I have to use standard python statement:

```<code>city = unit.city if 'city' in unit else None
</code>```

That is a bit complex for just a get operation, because I have many transformations of that kind.

And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn't exist) — such as get for dict type:

```<code>city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'
</code>```

I would define my own function get but I'm interested if there is any in standard libraries. And yet, from operation import getitem doesn't able to do that.

I use python 2, by the way.

答:
There is getattr(object, name[, default]):

```<code>city = getattr(unit, 'city', 'Moscow')
</code>```

Body:
I would like to get an attribute of mongoengine model object but it's missing (how it's often in mongo):

unit.city gives me AttributeError

unit.get('city') says that 'Unit' object has no attribute 'get' and I can't find any appropriate method by dir(unit).

So I have to use standard python statement:

city = unit.city if 'city' in unit else None

That is a bit complex for just a get operation, because I have many transformations of that kind.

And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn't exist) — such as get for dict type:

city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'

I would define my own function get but I'm interested if there is any in standard libraries. And yet, from operation import getitem doesn't able to do that.

I use python 2, by the way.

Body:
There is getattr(object, name[, default]):

city = getattr(unit, 'city', 'Moscow')


问:
Change BG color of a view with tap recogniser
I've created a view using for loop and if I click on a view ,Its background Color should change and Ive Achieved this, but when I click on another view the previous color remains the same.

my code

```<code>    _dropDownView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3.5, -SCREEN_WIDTH, SCREEN_WIDTH/2+33, SCREEN_WIDTH - 100)];

for(int index = 0 ; index < indexCount ; index++)
{
    _dropDownViewCell = [[UIView alloc] initWithFrame:CGRectMake(0, index * dropCellHeight, SCREEN_WIDTH, dropCellHeight)];

    //Set Tag for future identification
    [_dropDownViewCell setTag:index];
    [_dropDownViewCell setBackgroundColor:[UIColor clearColor]];

    [_dropDownView addSubview:_dropDownViewCell];

    selectDropCell =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(dropCellAction:)];

    [_dropDownViewCell addGestureRecognizer:selectDropCell];

}
- (void)dropCellAction:(UITapGestureRecognizer *)recognizer
{

switch (recognizer.view.tag) {

    case 0: {
        selectDropCell.view.tag = 0;

    }
        break;
    case 1: {
        selectDropCell.view.tag = 1;

    }
        break;
    case 2: {
        selectDropCell.view.tag = 2;

    }
        break;
    case 3: {

        selectDropCell.view.tag = 3;

    }
        break;
    case 4: {
        selectDropCell.view.tag = 4;

    }
        break;
    case 5: {

        selectDropCell.view.tag = 5;

    }
        break;
    case 6: {

        selectDropCell.view.tag = 6;

    }
        break;

    default:
        break;
}

for(int index = 0 ; index < 6 ; index ++){

    NSUInteger slectedIndex = selectDropCell.view.tag;
    if(slectedIndex == index)
    {
        recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
    }

}

}
</code>```

Achieved : While clicking the view Bg Color Change.
Problem : While clicking another View the Previous Bg Color should reset to the Original Color.

How Can I Solve this Problem ?

答:
use this else condition </p>

```<code>if(slectedIndex == index)
   {
     recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
    }
    else
    {
     recognizer.view.backgroundColor = [UIColor clearColor];//or your desired color
    }
</code>```

Body:
I've created a view using for loop and if I click on a view ,Its background Color should change and Ive Achieved this, but when I click on another view the previous color remains the same.

my code

    _dropDownView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3.5, -SCREEN_WIDTH, SCREEN_WIDTH/2+33, SCREEN_WIDTH - 100)];

for(int index = 0 ; index < indexCount ; index++)
{
    _dropDownViewCell = [[UIView alloc] initWithFrame:CGRectMake(0, index * dropCellHeight, SCREEN_WIDTH, dropCellHeight)];

    //Set Tag for future identification
    [_dropDownViewCell setTag:index];
    [_dropDownViewCell setBackgroundColor:[UIColor clearColor]];

    [_dropDownView addSubview:_dropDownViewCell];

    selectDropCell =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(dropCellAction:)];

    [_dropDownViewCell addGestureRecognizer:selectDropCell];

}
- (void)dropCellAction:(UITapGestureRecognizer *)recognizer
{

switch (recognizer.view.tag) {

    case 0: {
        selectDropCell.view.tag = 0;

    }
        break;
    case 1: {
        selectDropCell.view.tag = 1;

    }
        break;
    case 2: {
        selectDropCell.view.tag = 2;

    }
        break;
    case 3: {

        selectDropCell.view.tag = 3;

    }
        break;
    case 4: {
        selectDropCell.view.tag = 4;

    }
        break;
    case 5: {

        selectDropCell.view.tag = 5;

    }
        break;
    case 6: {

        selectDropCell.view.tag = 6;

    }
        break;

    default:
        break;
}

for(int index = 0 ; index < 6 ; index ++){

    NSUInteger slectedIndex = selectDropCell.view.tag;
    if(slectedIndex == index)
    {
        recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
    }

}

}

Achieved : While clicking the view Bg Color Change.
Problem : While clicking another View the Previous Bg Color should reset to the Original Color.

How Can I Solve this Problem ?

Body:
use this else condition

if(slectedIndex == index)
   {
     recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
    }
    else
    {
     recognizer.view.backgroundColor = [UIColor clearColor];//or your desired color
    }


问:
VBA Getting a date variable always 3 months in the future
I'm trying to find a way to get VBA to calculate a date 3 months in the future from the current date of the system (also as the 1st day of that future month).

This would be then used in filter below.

```<code>Workbooks(FN1).Worksheets("Sheet1").Range(Final1).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2017")
</code>```

Basically what I need is to replace the "9/1/2017" with a variable that gets calculated.

Any help would be greatly appreciated. Thank you!

EDIT: Used below code in the end which works great. However, I just found out a problem which makes it a bit more complicated.

```<code>Workbooks(FN1).Worksheets("Sheet1").Range(Res).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, DateSerial(Year(Date), Month(Date) + 3, 1))
</code>```

Seems like the filter needs to be set on multiple years, not just the current year. Recorded, it looks like this.

```<code>ActiveSheet.Range("$A$4:$X$2767").AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2021", 1, "9/1/2020", 1, "9/1/2019", 1, _
    "9/1/2018", 1, "9/1/2017", 1, "9/1/2016", 1, "9/1/2015", 1, "9/1/2014", 1, "9/1/2013")
</code>```

Problem is, the years will be variable as well (ex: Might not have 2013 in the data source next month but 2022 might be added).
So problem gets more complicated as now I would need something that checks every year in the data source Range(Res).Column("R") and, I assume, would loop through all the years and check the 1st day of the month 3 months in the future.

Or rather is it possible to filter just on the month? So it just picks September (in this case) across all years?

答:
You can do it directly like:

Edit1: Based on your comment.

```<code>Criteria2:=Array(1, Format(DateAdd("m", 3, Date) - DatePart("d", Date) + 1, "m/d/yyyy"))
</code>```

Body:
I'm trying to find a way to get VBA to calculate a date 3 months in the future from the current date of the system (also as the 1st day of that future month).

This would be then used in filter below.

Workbooks(FN1).Worksheets("Sheet1").Range(Final1).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2017")

Basically what I need is to replace the "9/1/2017" with a variable that gets calculated.

Any help would be greatly appreciated. Thank you!

EDIT: Used below code in the end which works great. However, I just found out a problem which makes it a bit more complicated.

Workbooks(FN1).Worksheets("Sheet1").Range(Res).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, DateSerial(Year(Date), Month(Date) + 3, 1))

Seems like the filter needs to be set on multiple years, not just the current year. Recorded, it looks like this.

ActiveSheet.Range("$A$4:$X$2767").AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2021", 1, "9/1/2020", 1, "9/1/2019", 1, _
    "9/1/2018", 1, "9/1/2017", 1, "9/1/2016", 1, "9/1/2015", 1, "9/1/2014", 1, "9/1/2013")

Problem is, the years will be variable as well (ex: Might not have 2013 in the data source next month but 2022 might be added).
So problem gets more complicated as now I would need something that checks every year in the data source Range(Res).Column("R") and, I assume, would loop through all the years and check the 1st day of the month 3 months in the future.

Or rather is it possible to filter just on the month? So it just picks September (in this case) across all years?

Body:
You can do it directly like:

Edit1: Based on your comment.

Criteria2:=Array(1, Format(DateAdd("m", 3, Date) - DatePart("d", Date) + 1, "m/d/yyyy"))


问:
DocuSign: Rest API C# get permanent links for signers
I'm using DocuSign's REST API to create envelopes in embedded signing mode. With the function CreateRecipientView i get only a temporary link. But i would prefer to get an permanent link like in the notification mail. How can i get this link/URL? </p>

答:
To give your signers permanent links, your application creates the links by itself. Eg myapp.myserver.com/signing_links/95a086f7-a76e-40ec-938e-987be996d220

The number should be a guid, not a database record key. This is needed to prevent someone from guessing what one of these permanent links is, so they can't read (or sign!) someone else's documents.

When someone opens their browser to go to one of the signer links, your application looks up the guid in the your app's database. The database record will include the DocuSign envelope_id and the recipient_id that the link represents.

Next your app uses that data to request an embedded recipient view link from DocuSign. Then (if you get a good response back from DocuSign), your app redirects the user's browser to the signing page on DocuSign.

(You'd get back an error from DocuSign if the recipient had already signed, or the envelope had been voided, etc.)

Guess what? The above is more or less how DocuSign gives out the "permanent" links in its emails--those links always redirect to one of the 5-minutes-only signing ceremony links.

Remember that you need to authenticate the signers, or include additional authentication options in your envelope, since you don't know who is going to end up pressing one of your app's signer links.


问:
Yocto upgrade from fido to morty rootfs is read-only error
So, I was given the task to upgrade our yocto based system from fido to morty. I have very little experience with yocto, I have been struggling with it and trying to understand it for almost a week now. I have managed to fix some issues, but now I'm facing a problem when trying to build the image:

```<code>ERROR: basic-image-1.0-r0 do_rootfs: The following packages could not be configured offline and rootfs is read-only: ['component']
ERROR: basic-image-1.0-r0 do_rootfs: Function failed: do_rootfs
</code>```

If I disable the compoents the basic-image builds just fine, and both of them build just fine on their own, i.e bb component

I don't even know where to start looking for a solution. So if you have any idea what might be causing this or where to start looking for a solution, it would be greatly appreciated.
Ofcourse I have been browsing the yocto manuals, but there is so much stuff that I'm just overwhelmed by all of it.

答:
Well, the "problem" stems from the fact that you have the following in your image:

```<code>IMAGE_FEATURES += "read-only-rootfs"
</code>```

That implies that nothing can modify the rootfs during runtime, everything has to be done off-line, i.e. when constructing the rootfs in question.

Your package component (adcl and cfgmgr in your original question), all have a post-installation script including the following snippet:

```<code>pkg_postinst_${PN} () {
  if test "x$D" != "x" then
     # Need to run on first boot
     exit 1
  fi
}
</code>```

(Something similar at least, which exit 1).

The conditional in my example checks if the pkg_postinst script is being run during rootfs creation, if so, it exits with 1 as exit status. That means that the pkg_postinst has to be run live on the target system. However, as the target system is read-only, this will be impossible, and the build fails.

You'll have to check for pkg_postinst scripts, and rewrite them, such that they're able to be run during rootfs creation.

Body:
So, I was given the task to upgrade our yocto based system from fido to morty. I have very little experience with yocto, I have been struggling with it and trying to understand it for almost a week now. I have managed to fix some issues, but now I'm facing a problem when trying to build the image:

ERROR: basic-image-1.0-r0 do_rootfs: The following packages could not be configured offline and rootfs is read-only: ['component']
ERROR: basic-image-1.0-r0 do_rootfs: Function failed: do_rootfs

If I disable the compoents the basic-image builds just fine, and both of them build just fine on their own, i.e bb component

I don't even know where to start looking for a solution. So if you have any idea what might be causing this or where to start looking for a solution, it would be greatly appreciated.
Ofcourse I have been browsing the yocto manuals, but there is so much stuff that I'm just overwhelmed by all of it.

Body:
Well, the "problem" stems from the fact that you have the following in your image:

IMAGE_FEATURES += "read-only-rootfs"

That implies that nothing can modify the rootfs during runtime, everything has to be done off-line, i.e. when constructing the rootfs in question.

Your package component (adcl and cfgmgr in your original question), all have a post-installation script including the following snippet:

pkg_postinst_${PN} () {
  if test "x$D" != "x" then
     # Need to run on first boot
     exit 1
  fi
}

(Something similar at least, which exit 1).

The conditional in my example checks if the pkg_postinst script is being run during rootfs creation, if so, it exits with 1 as exit status. That means that the pkg_postinst has to be run live on the target system. However, as the target system is read-only, this will be impossible, and the build fails.

You'll have to check for pkg_postinst scripts, and rewrite them, such that they're able to be run during rootfs creation.


问:
Asynchronous write to documentdb using java driver
I'm using java-sdk for inserting documents to cosmosdb. From the driver I was not able to find any java api to do asynchronous insert, however I saw options for .Net api,

Is there a way(natively) to insert documents in background without making the client wait.

答:
I reviewed the javadocs & source code of Azure DocumentDB SDK for Java, unfortunately, there is not any native method to support the asynchronous operation. So if you have to need asynchronous feature, there are two workaround ways below.

Using an asynchronous http client to call Cosmos REST APIs, such as OkHttp.

Azure DocumentDB support MongoDB protocol, so I think it's possible to use MongoDB Async Java Driver to satisfy your needs, but I was failed due to the offical MongoDB Async Java Driver seems to not support Azure DocumentDB. However, there is a third party MongoDB Asynchronous Java Driver mongodb-async-driver, which I tried to connect to Azure DocumentDB with MongoDB protocol successfully, but its APIs are different from the MongoDB offical.

As reference, Here is my sample code using the third party driver which be download here, without maven repo.

```<code>import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.MongoIterator;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.builder.Find;

public class Test {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        String connectionString = "mongodb://<user>:<password>@<documentdb-name>.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";
        MongoClient mongo = MongoFactory.createClient(connectionString);
        String dbName = "testdb";
        MongoDatabase database = mongo.getDatabase(dbName);
        String collName = "test";
        MongoCollection collection = database.getCollection(collName);
        Future<Long> future = collection.countAsync();
        System.out.printf("There are %,d documents in the collection.%n", future.get());
        MongoIterator iter = collection.find(Find.builder().build());
        while (iter.hasNext()) {
            System.out.println(((Document) iter.next()));
        }
    }

}
</code>```

Hope it helps.

Body:
I reviewed the javadocs & source code of Azure DocumentDB SDK for Java, unfortunately, there is not any native method to support the asynchronous operation. So if you have to need asynchronous feature, there are two workaround ways below.

Using an asynchronous http client to call Cosmos REST APIs, such as OkHttp.

Azure DocumentDB support MongoDB protocol, so I think it's possible to use MongoDB Async Java Driver to satisfy your needs, but I was failed due to the offical MongoDB Async Java Driver seems to not support Azure DocumentDB. However, there is a third party MongoDB Asynchronous Java Driver mongodb-async-driver, which I tried to connect to Azure DocumentDB with MongoDB protocol successfully, but its APIs are different from the MongoDB offical.

As reference, Here is my sample code using the third party driver which be download here, without maven repo.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.MongoIterator;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.builder.Find;

public class Test {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        String connectionString = "mongodb://<user>:<password>@<documentdb-name>.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";
        MongoClient mongo = MongoFactory.createClient(connectionString);
        String dbName = "testdb";
        MongoDatabase database = mongo.getDatabase(dbName);
        String collName = "test";
        MongoCollection collection = database.getCollection(collName);
        Future<Long> future = collection.countAsync();
        System.out.printf("There are %,d documents in the collection.%n", future.get());
        MongoIterator iter = collection.find(Find.builder().build());
        while (iter.hasNext()) {
            System.out.println(((Document) iter.next()));
        }
    }

}

Hope it helps.