问:
How can I recover my Git repository for a "missing tree" error?
We are using Gerrit for our Git repository.  On a project that has been active for several months, we are suddenly unable to push any changes.  When we execute git push we see the following error:

error: unpack failed: error Missing tree 14d62f0ed4385e3f68f226ac133fa9932a9c65c9

Executing git fsck --full yields:

```<code>dangling tree 2701c92fb6eab1826482f6bcc9598413e651a92a
dangling blob c505b3b12cfacd1e26dec8dc559820a30fc20c27
dangling blob 8907f94b5b4ec881e1b86d50681795e368c167ff
dangling blob 4938d9fc34c6e2f92c68872bfec6e070b2b3a9c2
dangling blob 8a5c8b8d35484ea1470e2d8e6c482fcb97b23d0f
dangling commit 3072d3314e20bf6c6998e1c02986d83019d3e1df
dangling tree 5377d7f7111d340854c3ee0946667c202227e603
dangling tree c3783e9ab540457924ceb9f9fb5ea1c2b97472b1
dangling blob 8b92d1765038e4ec5e721f98a2aabb305a7f9819
dangling tree 38a03153f0f18ca15846e9bd4983a86800a43a94
dangling commit 8db2d6ae5364174bebe13720a359ddb2e62d4c9d
</code>```

All of our developers are experiencing the same error when they try to push.  So far, we've tried re-initializing the gerrit repo (git init --bare ...) and pushing up to it.  We've also tried creating a new gerrit project with a separate repo.  In the end, we keep getting the same error.

Does anyone have any insight on what the cause would be, or how to recover?

答:
I deleted my master branch and created once again. Its working .
git branch -D master,
git checkout master
Luckily it working</p>

Body:
We are using Gerrit for our Git repository.  On a project that has been active for several months, we are suddenly unable to push any changes.  When we execute git push we see the following error:

error: unpack failed: error Missing tree 14d62f0ed4385e3f68f226ac133fa9932a9c65c9

Executing git fsck --full yields:

dangling tree 2701c92fb6eab1826482f6bcc9598413e651a92a
dangling blob c505b3b12cfacd1e26dec8dc559820a30fc20c27
dangling blob 8907f94b5b4ec881e1b86d50681795e368c167ff
dangling blob 4938d9fc34c6e2f92c68872bfec6e070b2b3a9c2
dangling blob 8a5c8b8d35484ea1470e2d8e6c482fcb97b23d0f
dangling commit 3072d3314e20bf6c6998e1c02986d83019d3e1df
dangling tree 5377d7f7111d340854c3ee0946667c202227e603
dangling tree c3783e9ab540457924ceb9f9fb5ea1c2b97472b1
dangling blob 8b92d1765038e4ec5e721f98a2aabb305a7f9819
dangling tree 38a03153f0f18ca15846e9bd4983a86800a43a94
dangling commit 8db2d6ae5364174bebe13720a359ddb2e62d4c9d

All of our developers are experiencing the same error when they try to push.  So far, we've tried re-initializing the gerrit repo (git init --bare ...) and pushing up to it.  We've also tried creating a new gerrit project with a separate repo.  In the end, we keep getting the same error.

Does anyone have any insight on what the cause would be, or how to recover?


来源: stackexchange

问:
array of pointers
Consider the following code:

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

int main()
{
  static int a[]={0,1,2,3,4};
  int *p[]={a,a+1,a+2,a+3};            /* clear up to this extent */
  printf(("%u\n%u\n%u",p,*p,*(*p)));   /* how does this statement work? */
  return 0;
}
</code>```

Also is it necessary to get the value of addresses through %u,or we can use %d also?

答:
Okay, you've created an array of integers and populated it with the integers from 0 to 4. Then you created a 4 element array of pointers to integers, and initialized it so its four elements point to the first four elements of a. So far, so good.

Then the printf is very strange. printf is passed a single argument, namely ("%u\n%u\n%u",p,p,(*p)). This is a comma-expression which means that the comma-separated expressions will be calculated in turn, and only the last one returned. Since the very first thing is a literal, and not an expression, I'd expect it to generate an error. However, without the extraneous parentheses, you have:

```<code>printf("%u\n%u\n%u\n",p, *p, *(*p));
</code>```

This is legal. Three values are passed to printf, interpreted as unsigned integers (which actually only works on some systems, since what you are actually passing in are pointers in the first two cases, and they aren't guarateed to be the same size as unsigned ints) and printed.

Those values are p, *p and **p. p is an array, and so the value of p is the address of the array. *p is what p points to, which are the values of the array. *p is the first value, *(p+1) is the second value, etc. Now *p is the value stored in p[0] which is the address of a[0], so another address is printed. The third argument is **p which is the value stored at (*p), or a[0], which is 0

ContentLicense: CC BY-SA 3.0

Title: array of pointers

Body:
Consider the following code:

#include <stdio.h>

int main()
{
  static int a[]={0,1,2,3,4};
  int *p[]={a,a+1,a+2,a+3};            /* clear up to this extent */
  printf(("%u\n%u\n%u",p,*p,*(*p)));   /* how does this statement work? */
  return 0;
}

Also is it necessary to get the value of addresses through %u,or we can use %d also?

Body:
Okay, you've created an array of integers and populated it with the integers from 0 to 4. Then you created a 4 element array of pointers to integers, and initialized it so its four elements point to the first four elements of a. So far, so good.

Then the printf is very strange. printf is passed a single argument, namely ("%u\n%u\n%u",p,p,(*p)). This is a comma-expression which means that the comma-separated expressions will be calculated in turn, and only the last one returned. Since the very first thing is a literal, and not an expression, I'd expect it to generate an error. However, without the extraneous parentheses, you have:

printf("%u\n%u\n%u\n",p, *p, *(*p));

This is legal. Three values are passed to printf, interpreted as unsigned integers (which actually only works on some systems, since what you are actually passing in are pointers in the first two cases, and they aren't guarateed to be the same size as unsigned ints) and printed.

Those values are p, *p and **p. p is an array, and so the value of p is the address of the array. *p is what p points to, which are the values of the array. *p is the first value, *(p+1) is the second value, etc. Now *p is the value stored in p[0] which is the address of a[0], so another address is printed. The third argument is **p which is the value stored at (*p), or a[0], which is 0


问:
How to divide footer in column wise along with footer contents?
I'm setting footer with headings title as About, contact us, popular searches, Blogs. I want to display the contents below footer title but its not working. I'm getting the output like contents are getting displayed next to footer title.

I tried to use the grid system but no result as of now.

```<code>Contact us            Services          Blogs

no:12, 8th cross,     Find doctors       Twitter
Rajajinagar,          Find hospitals     Facebook
Bangalore.
</code>```

HTML Code:

```<code><mat-grid-list cols="4" row Height="4:0.8" class="list">
  <mat-grid-tile >Contact Us <h3>Contact us</h3> </mat-grid-tile>
  <mat-grid-tile>Services</mat-grid-tile>
  <mat-grid-tile>About Us</mat-grid-tile>
  <mat-grid-tile>Popular Searches</mat-grid-tile>
</mat-grid-list>
</code>```

答:
You can use mat-grid-tile-header in order to define the title (e.g. Contact Us, Services etc), then define the content below this - but still within mat-grid-tile

```<code><mat-grid-list cols="3" row Height="4:0.8" class="list">
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Contact us</h3>
    </mat-grid-tile-header>
    no:12, 8th cross,<br/>
    Rajajinagar,<br/>
    Bangalore.
  </mat-grid-tile>
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Services</h3>
    </mat-grid-tile-header>
    Find doctors<br/>
    Find hospitals
  </mat-grid-tile>
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Blogs</h3>
    </mat-grid-tile-header>
    Twitter<br/>
    Facebook
  </mat-grid-tile>
</mat-grid-list>
</code>```

Please see this StackBlitz for a working demo.

ContentLicense: CC BY-SA 4.0

Body:
I'm setting footer with headings title as About, contact us, popular searches, Blogs. I want to display the contents below footer title but its not working. I'm getting the output like contents are getting displayed next to footer title.

I tried to use the grid system but no result as of now.

Contact us            Services          Blogs

no:12, 8th cross,     Find doctors       Twitter
Rajajinagar,          Find hospitals     Facebook
Bangalore.

HTML Code:

<mat-grid-list cols="4" row Height="4:0.8" class="list">
  <mat-grid-tile >Contact Us
Contact us
 </mat-grid-tile>
  <mat-grid-tile>Services</mat-grid-tile>
  <mat-grid-tile>About Us</mat-grid-tile>
  <mat-grid-tile>Popular Searches</mat-grid-tile>
</mat-grid-list>

Body:
You can use mat-grid-tile-header in order to define the title (e.g. Contact Us, Services etc), then define the content below this - but still within mat-grid-tile

<mat-grid-list cols="3" row Height="4:0.8" class="list">
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Contact us</h3>
    </mat-grid-tile-header>
    no:12, 8th cross,<br/>
    Rajajinagar,<br/>
    Bangalore.
  </mat-grid-tile>
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Services</h3>
    </mat-grid-tile-header>
    Find doctors<br/>
    Find hospitals
  </mat-grid-tile>
  <mat-grid-tile>
    <mat-grid-tile-header>
      <h3>Blogs</h3>
    </mat-grid-tile-header>
    Twitter<br/>
    Facebook
  </mat-grid-tile>
</mat-grid-list>

Please see this StackBlitz for a working demo.


问:
How can I update the voice channel when a user enters the guild with JDA
I basically wanted to convert this code to JDA

JavaScript

bot.channels.get(serverStats.totalUserID).setName(`Total Users: ${member.guild.memberCount}`);

```

<p>Java (Error)</p>

<pre class="lang-java prettyprint-override"><code>public void onGuildJoin(GuildJoinEvent event) {
     event.getGuild().getTextChannelById(573629024102776853L).setName("Total Users:" + event.getGuild().getMembers().size()); //<---- Error
}
</code>```

答:
To modify an entity in JDA you usually have to use the manager. You can acquire an instance of a manager through getManager() on almost every entity.

TextChannel channel = guild.getTextChannelById(573629024102776853L);
channel.getManager()
       .setName("Total Users:" + guild.getMemberCache().size())
       .queue(); // this is needed, otherwise the request won't be made to discord
```

If the id for the channel is incorrect it will throw an NPE on channel.getManager() because getTextChannelById will return null.
I used getMemberCache() instead of getMembers() because its more efficient for this kind of code. The size is directly available on the cache-view instance and does not require copying the entire cache into a list which is effectively what getMembers() does.

Body:
I basically wanted to convert this code to JDA

JavaScript

bot.channels.get(serverStats.totalUserID).setName(`Total Users: ${member.guild.memberCount}`);

Java (Error)

public void onGuildJoin(GuildJoinEvent event) {
     event.getGuild().getTextChannelById(573629024102776853L).setName("Total Users:" + event.getGuild().getMembers().size()); //<---- Error
}

Body:
To modify an entity in JDA you usually have to use the manager. You can acquire an instance of a manager through getManager() on almost every entity.

TextChannel channel = guild.getTextChannelById(573629024102776853L);
channel.getManager()
       .setName("Total Users:" + guild.getMemberCache().size())
       .queue(); // this is needed, otherwise the request won't be made to discord

If the id for the channel is incorrect it will throw an NPE on channel.getManager() because getTextChannelById will return null.
I used getMemberCache() instead of getMembers() because its more efficient for this kind of code. The size is directly available on the cache-view instance and does not require copying the entire cache into a list which is effectively what getMembers() does.


问:
Create multiple files with Powershell?
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

```<code>touch {a..z}.txt
</code>```

Or 152 with:

```<code>touch {{a..z},{A..Z},{0..99}}.txt
</code>```

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

答:
For letters, in PowerShell, use:</p>

```<code>97..( 97+25 ) | foreach { new-item $env:temp\$( [char]$_ ).txt }
</code>```

Title: Create multiple files with Powershell?

Body:
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

touch {a..z}.txt

Or 152 with:

touch {{a..z},{A..Z},{0..99}}.txt

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

Body:
For letters, in PowerShell, use:

97..( 97+25 ) | foreach { new-item $env:temp\$( [char]$_ ).txt }


问:
How to find the neighborhood for certain vertices only?
The question was started here.

I have an undirected graph g with n<100 vertices. The graph is simple. The coordinates of all vertices are integer (x_i, y_i), i=1, 2,..., n, the set of edges is predefinded, they are line segments with the length 1 unit.
The degree of vertices can be 2, 3 or 4.

```<code>library(igraph)

g <- graph_from_literal(1-2-3-4-5-6-7-8-1, 8-9-4)
B <- t(matrix(c(0,0, 0,1, 0,2, -1,2, -2,2, -2,1, -2,0, -1,0, -1,1), nrow =2));

V(g)$id <- seq_len(vcount(g))

V(g)$x <- B[,1]; V(g)$y <- B[,2]

plot(g, layout=as.matrix(B))
</code>```

I need to set the new attribute for vertex the corner attribute.

We say the vertex i is the corner vertex if its degree is 2 and two incident edges do not lie on the same line. On the plot above vertices 1, 3, 5, 7 are corner vertices while remaining vertices 2, 4, 6, 8, 9 are non-corner.

My attempt

I have found the list of vertices that have degree equal to 2.

```<code>idv <- V(g)[strength(g)==2]; idv # 1 2 3 5 6 7 9
</code>```

Then the list of neighborhood vertices for i-th vertex was found.

```<code>neigh<-neighborhood(g, idv); neigh
</code>```

The error is here, because I see the neighborhood vertices for all vertices, no only vertices that have degree equal to 2. For instance,

```<code>neigh[[4]]; neigh[[8]];
#[1] 4 3 5 9
#[1] 8 1 7 9
</code>```

Question. How to use the neighborhood function to find the neighborhood for vertices with degree 2 only?

答:
The function is correct, but the second argument isn't about vertices of interest, it's the third one:

```<code>neighborhood
# function (graph, order = 1, nodes = V(graph), mode = c("all",
#     "out", "in"), mindist = 0)
# {
# ...
</code>```

Thus,

```<code>length(neighborhood(g, nodes = idv))
# [1] 7
</code>```

does the job.

Body:
The question was started here.

I have an undirected graph g with n<100 vertices. The graph is simple. The coordinates of all vertices are integer (x_i, y_i), i=1, 2,..., n, the set of edges is predefinded, they are line segments with the length 1 unit.
The degree of vertices can be 2, 3 or 4.

library(igraph)

g <- graph_from_literal(1-2-3-4-5-6-7-8-1, 8-9-4)
B <- t(matrix(c(0,0, 0,1, 0,2, -1,2, -2,2, -2,1, -2,0, -1,0, -1,1), nrow =2));

V(g)$id <- seq_len(vcount(g))

V(g)$x <- B[,1]; V(g)$y <- B[,2]

plot(g, layout=as.matrix(B))

I need to set the new attribute for vertex the corner attribute.

We say the vertex i is the corner vertex if its degree is 2 and two incident edges do not lie on the same line. On the plot above vertices 1, 3, 5, 7 are corner vertices while remaining vertices 2, 4, 6, 8, 9 are non-corner.

My attempt

I have found the list of vertices that have degree equal to 2.

idv <- V(g)[strength(g)==2]; idv # 1 2 3 5 6 7 9

Then the list of neighborhood vertices for i-th vertex was found.

neigh<-neighborhood(g, idv); neigh

The error is here, because I see the neighborhood vertices for all vertices, no only vertices that have degree equal to 2. For instance,

neigh[[4]]; neigh[[8]];
#[1] 4 3 5 9
#[1] 8 1 7 9

Question. How to use the neighborhood function to find the neighborhood for vertices with degree 2 only?

Body:
The function is correct, but the second argument isn't about vertices of interest, it's the third one:

neighborhood
# function (graph, order = 1, nodes = V(graph), mode = c("all",
#     "out", "in"), mindist = 0)
# {
# ...

Thus,

length(neighborhood(g, nodes = idv))
# [1] 7

does the job.


问:
R exact selection based on %in%
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

```<code>   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4
</code>```

Intuitively I was going for

```<code>rb[rb$time %in% c(-1, -2, -3, -4), ]
</code>```

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

```<code>rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]
</code>```

But it does not work.

Any clue how I could tag or subset these id, such that

```<code>   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1
</code>```

Title: R exact selection based on %in%

Body:
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4

Intuitively I was going for

rb[rb$time %in% c(-1, -2, -3, -4), ]

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]

But it does not work.

Any clue how I could tag or subset these id, such that

   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1

Body:
One dplyr possibility could be:

df %>%
 group_by(id) %>%
 mutate(tag = all(c(-1, -2, -3, -4) %in% time) * 1)

      id  time   tag
   <int> <int> <dbl>
 1     1    -4     1
 2     1    -3     1
 3     1    -2     1
 4     1    -1     1
 5     2    -1     0
 6     2    -2     0
 7     3    -1     0
 8     3    -3     0
 9     4    -1     1
10     4    -2     1
11     4    -3     1
12     4    -4     1

And the same with base R could be:

with(df, ave(time, id, FUN = function(x) all(c(-1, -2, -3, -4) %in% x) * 1))


问:
Listbox inside ScrollViewer height calculations
When I place a ListBox inside a ScrollViewer, if I do not define a Height attribute for the ListBox, it doesn't scroll (aside from bouncing up and down a bit), so elements off the screen are inaccessible. If I set the Height attribute on the ListBox to the actual height it takes up on the screen, it scrolls perfectly. If I don't get the Height exactly right, it doesn't scroll properly, e.g. I might not be able to reach the bottom elements in the list.

When placing other elements in the single column LayoutRoot Grid above and below the ScrollViewer/ListBox, I set the RowDefinition.Height="Auto" on all rows except the ScrollViewer's, which gets "*". The Grid appears to properly allocate space accordingly. Except now I don't know a priori how much space the ScrollViewer/ListBox takes up.

Part A: Why should I have to set the Height on the ListBox, doesn't its (virtual) height vary with the number of elements?

Part B: It appears I have to manually lay out the Grid row heights, then manually re-do them if a fontsize or other style change is called for. Is that the case? That approach seems bogus.

答:
Your problems are caused because you've got a ListBox inside a ScrollViewer. Don't do this.

The Listbox contains an internal ScrollViewer and will (normally) grow to the available space.

By essentially having a ScrollViewer inside a ScrollViewer it doesn't know which one should grow to fit available space and how they should scroll relative to one another.

Let us know what you're trying to do. There is a better way to do it.


问:
Local Jekyll Repository Clone shows different output from Github hosted page
New to Jekyll. Have created and hosted a site via github for jekyll. Tried to clone the repo and serve it locally. Problem is that some pages show differently from the online hosted version. If you look at the site I created online:

http://taijisoce.com/

and click (excuse the immaturity) "Jamie is the butthole now its online" you can see it takes you to another well formatted page.

However when I tried to clone it to my local repository (I am on windows) and serve the site the homepage looks alright. But when I click the above link it just takes me to a plaintext line that says "does this work? Can I put this text and make it make sense?" no formatting no css etc.

Repo: https://github.com/themallardcomplexion/themallardcomplexion.github.io

Any ideas?

答:
Looking into this I added YML front matter to my post and tried to serve again. With the front matter entered it formatted correctly.

I just dont understand how Github didnt require front matter for it to format correctly.


问:
'for' loop terminating before termination condition is met
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
```

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

答:
You are creating the array before n is initialized, so there might not be space for all members.

```<code>// n is used here
int n,d,arr[n];
// Initialized here
cin>>n>>d;
</code>```

Instead of array, you could use for example std::vector. With it you don't have to know the size when declaring the variable.

Body:
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

Body:
You are creating the array before n is initialized, so there might not be space for all members.

// n is used here
int n,d,arr[n];
// Initialized here
cin>>n>>d;

Instead of array, you could use for example std::vector. With it you don't have to know the size when declaring the variable.


问:
Simple pagination in javascript
I am trying to make pagination for my site. (http://anuntorhei.md)

CODE:

```<code>var someVar = 50;

function someStupidFunction() {
        if (objJson.length > 50) {
                document.getElementById("nextPage").style.visibility = "visible";
        }

        if (someVar <= 50) {
                document.getElementById("prevPage").style.visibility ="hidden";
        } else {
                document.getElementById("prevPage").style.visibility = "visible";
        }
}

function nextPage() {
        document.getElementById("listingTable").innerHTML = "";

        if (someVar < objJson.length) {
                document.getElementById("nextPage").style.visibility = "visible";
        } else {
                document.getElementById("nextPage").style.visibility = "hidden";
        }

        for (var i = someVar - 50; i < someVar; i++) {
                document.getElementById("listingTable").innerHTML += objJson[i].adName + "<br>";
        }

        someVar += 50;

        document.getElementById("prevPage").style.visibility = "visible";
}

function prevPage() {
        document.getElementById("listingTable").innerHTML = "";

        if (someVar > 50) {
                document.getElementById("prevPage").style.visibility = "visible";
        } else {
                document.getElementById("prevPage").style.visibility = "hidden";
        }

        for (var i = someVar - 50; i < someVar; i++) {
                document.getElementById("listingTable").innerHTML += objJson[i].adName + "<br>";
        }

        someVar -= 50;

        document.getElementById("nextPage").style.visibility = "visible";
}
</code>```

But I can't understand how to "hide" nextPage button when someVar is bigger than objJson.length.

And when I reach the "end", nextPage button disappear after than objJson is smaller than someVar. What is wrong in this code?

How can I change it to make it perfect? Sorry for my bad English, can't explain all what I need, hope you understand what I need!

答:
I created a class structure for collections in general that would meet this requirement. and it looks like this:

```<code>class Collection {

    constructor() {
        this.collection = [];
        this.index = 0;
    }

    log() {
        return console.log(this.collection);
    }

    push(value) {
        return this.collection.push(value);
    }

    pushAll(...values) {
        return this.collection.push(...values);
    }

    pop() {
        return this.collection.pop();
    }

    shift() {
        return this.collection.shift();
    }

    unshift(value) {
        return this.collection.unshift(value);
    }

    unshiftAll(...values) {
        return this.collection.unshift(...values);
    }

    remove(index) {
        return this.collection.splice(index, 1);
    }

    add(index, value) {
        return this.collection.splice(index, 0, value);
    }

    replace(index, value) {
        return this.collection.splice(index, 1, value);
    }

    clear() {
        this.collection.length = 0;
    }

    isEmpty() {
        return this.collection.length === 0;
    }

    viewFirst() {
        return this.collection[0];
    }

    viewLast() {
        return this.collection[this.collection.length - 1];
    }

    current(){
        if((this.index <= this.collection.length - 1) && (this.index >= 0)){
            return this.collection[this.index];
        }
        else{
            return `Object index exceeds collection range.`;
        }
    }

    next() {
        this.index++;
        this.index > this.collection.length - 1 ? this.index = 0 : this.index;
        return this.collection[this.index];
    }

    previous(){
        this.index--;
        this.index < 0 ? (this.index = this.collection.length-1) : this.index;
        return this.collection[this.index];
    }
}
</code>```

...and essentially what you would do is have a collection of arrays of whatever length for your pages pushed into the class object, and then use the next() and previous() functions to display whatever 'page' (index) you wanted to display. Would essentially look like this:

```<code>let books = new Collection();
let firstPage - [['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'],];
let secondPage - [['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'],];
books.pushAll(firstPage, secondPage); // loads each array individually
books.current() // display firstPage
books.next() // display secondPage
</code>```

Title: Simple pagination in javascript

Body:
I am trying to make pagination for my site. (http://anuntorhei.md)

CODE:

var someVar = 50;

function someStupidFunction() {
        if (objJson.length > 50) {
                document.getElementById("nextPage").style.visibility = "visible";
        }

        if (someVar <= 50) {
                document.getElementById("prevPage").style.visibility ="hidden";
        } else {
                document.getElementById("prevPage").style.visibility = "visible";
        }
}

function nextPage() {
        document.getElementById("listingTable").innerHTML = "";

        if (someVar < objJson.length) {
                document.getElementById("nextPage").style.visibility = "visible";
        } else {
                document.getElementById("nextPage").style.visibility = "hidden";
        }

        for (var i = someVar - 50; i < someVar; i++) {
                document.getElementById("listingTable").innerHTML += objJson[i].adName + "
";
        }

        someVar += 50;

        document.getElementById("prevPage").style.visibility = "visible";
}

function prevPage() {
        document.getElementById("listingTable").innerHTML = "";

        if (someVar > 50) {
                document.getElementById("prevPage").style.visibility = "visible";
        } else {
                document.getElementById("prevPage").style.visibility = "hidden";
        }

        for (var i = someVar - 50; i < someVar; i++) {
                document.getElementById("listingTable").innerHTML += objJson[i].adName + "
";
        }

        someVar -= 50;

        document.getElementById("nextPage").style.visibility = "visible";
}

But I can't understand how to "hide" nextPage button when someVar is bigger than objJson.length.

And when I reach the "end", nextPage button disappear after than objJson is smaller than someVar. What is wrong in this code?

How can I change it to make it perfect? Sorry for my bad English, can't explain all what I need, hope you understand what I need!

Body:
I created a class structure for collections in general that would meet this requirement. and it looks like this:

class Collection {

    constructor() {
        this.collection = [];
        this.index = 0;
    }

    log() {
        return console.log(this.collection);
    }

    push(value) {
        return this.collection.push(value);
    }

    pushAll(...values) {
        return this.collection.push(...values);
    }

    pop() {
        return this.collection.pop();
    }

    shift() {
        return this.collection.shift();
    }

    unshift(value) {
        return this.collection.unshift(value);
    }

    unshiftAll(...values) {
        return this.collection.unshift(...values);
    }

    remove(index) {
        return this.collection.splice(index, 1);
    }

    add(index, value) {
        return this.collection.splice(index, 0, value);
    }

    replace(index, value) {
        return this.collection.splice(index, 1, value);
    }

    clear() {
        this.collection.length = 0;
    }

    isEmpty() {
        return this.collection.length === 0;
    }

    viewFirst() {
        return this.collection[0];
    }

    viewLast() {
        return this.collection[this.collection.length - 1];
    }

    current(){
        if((this.index <= this.collection.length - 1) && (this.index >= 0)){
            return this.collection[this.index];
        }
        else{
            return `Object index exceeds collection range.`;
        }
    }

    next() {
        this.index++;
        this.index > this.collection.length - 1 ? this.index = 0 : this.index;
        return this.collection[this.index];
    }

    previous(){
        this.index--;
        this.index < 0 ? (this.index = this.collection.length-1) : this.index;
        return this.collection[this.index];
    }
}

...and essentially what you would do is have a collection of arrays of whatever length for your pages pushed into the class object, and then use the next() and previous() functions to display whatever 'page' (index) you wanted to display. Would essentially look like this:

let books = new Collection();
let firstPage - [['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'],];
let secondPage - [['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'],];
books.pushAll(firstPage, secondPage); // loads each array individually
books.current() // display firstPage
books.next() // display secondPage


问:
How to override parent class?
I have two classes:

```<code>class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)
</code>```

Output is 1 (0+1) but I expect to have 2 (1+1). How can I achieve such result?

答:
You could use a key word argument to set the value of a in the parent class if the argument is not provided:

```<code>class Parent(object):
    def __init__(self, a=None):
        if a is None:
            self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__(self.a)

parent = Parent()
child = Child()
print(parent.a, parent.b)
print(child.a, child.b)
</code>```

output:

```<code>0 1
1 2
</code>```

Another approach could use class variables:

```<code>class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
    def __init__(self):
        super().__init__()

parent = Parent()
child = Child()
print(parent.a, parent.b)
print(child.a, child.b)
</code>```

output:

```<code>0 1
1 2
</code>```

In the above, using class variables, you can entirely do without the __init__ method in the child class: (this may, or may not be applicable to your real world use case)

```<code>class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
</code>```

Title: How to override parent class?

Body:
I have two classes:

class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)

Output is 1 (0+1) but I expect to have 2 (1+1). How can I achieve such result?

Body:
You could use a key word argument to set the value of a in the parent class if the argument is not provided:

class Parent(object):
    def __init__(self, a=None):
        if a is None:
            self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__(self.a)

parent = Parent()
child = Child()
print(parent.a, parent.b)
print(child.a, child.b)

output:

0 1
1 2

Another approach could use class variables:

class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
    def __init__(self):
        super().__init__()

parent = Parent()
child = Child()
print(parent.a, parent.b)
print(child.a, child.b)

output:

0 1
1 2

In the above, using class variables, you can entirely do without the __init__ method in the child class: (this may, or may not be applicable to your real world use case)

class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1


答:
You need a left join and a CASE statement:

```<code>select
  t.*,
  case
    when s.id_topic is null then 'no'
    else 'yes'
  end subscribed
from topics t left join sub s
on s.id_topic = t.id_topic
</code>```

Title: SQLite CASE Between two tables

Body:
SQLite CASE Between two tables

I have 2 tables "topics" and "sub"

TABLE TOPICS :

+------------+-------------+
| id_topic   | topic_name  |
+------------+-------------+
| 1          | books       |
| 2          | food        |
| 3          | movies      |
| 4          | weather     |
| 5          | travel      |
| 6          | pets        |
+------------+-------------+

TABLE SUB :

+------------+
| id_topic   |
+------------+
| 2          |
| 5          |
+------------+

I want to print this :

+-------------+-------------+-------------+
| id_topic    | topic_name  | subscribed  |
+-------------+-------------+-------------+
| 1           | books       | no          |
| 2           | food        | yes         |
| 3           | movies      | no          |
| 4           | weather     | no          |
| 5           | travel      | yes         |
| 6           | pets        | no          |
+-------------+-------------+-------------+

Body:
You need a left join and a CASE statement:

select
  t.*,
  case
    when s.id_topic is null then 'no'
    else 'yes'
  end subscribed
from topics t left join sub s
on s.id_topic = t.id_topic


问:
How to count everything but letters at end of a string
I have a random string and need to know the number of non-letter / non-number characters at the end of it.

For example:

"Some text." should result in 1

"More text 123 !.?" should result in 4 (blanks included)

"Even more text 123" should result in 0

How can I do that?

答: You could iterate backwards through the string and use Char.IsLetterOrDigit to determine if it's non-alphanumeric. When you find a letter or digit then stop and return the count.</p>


问:
Changing Default Retention Policy Length
I have been saving data in my InfluxDB instance with a Default retention policy with a DURATION of 720h (30 days). I have recently altered the same retention policy to keep the data for INF (0s). I was expecting to have issues querying the data stored under the old RP duration ( as explained here https://docs.influxdata.com/influxdb/v0.13/troubleshooting/frequently_encountered_issues/#missing-data-after-creating-a-new-default-retention-policy) but haven't had any issues.

Should I expect to see issues or will my data just be kept indefinitely?

I altered the RP via the ALTER command and everything worked correctly however having a few minutes and a few new data points I have not had any issue with missing data.

I expected it to give me issues finding older data.

Before:

```<code>name                     duration shardGroupDuration replicaN default
----                     -------- ------------------ -------- -------
autogen                  0s       168h0m0s           1        false
default_retention_policy 720h0m0s 24h0m0s            1        true
one_day                  24h0m0s  1h0m0s             1        false
</code>```

After ALTER RETENTION POLICY default_retention_policy on defaultdb DURATION INF:

```<code>name                     duration shardGroupDuration replicaN default
----                     -------- ------------------ -------- -------
autogen                  0s       168h0m0s           1        false
default_retention_policy 0s       168h0m0s           1        true
one_day                  24h0m0s  1h0m0s             1        false
</code>```

答: You should be fine. That caveat is for when you create a new default retention policy. Using ALTER should keep you working just fine</p>

Body:
I have been saving data in my InfluxDB instance with a Default retention policy with a DURATION of 720h (30 days). I have recently altered the same retention policy to keep the data for INF (0s). I was expecting to have issues querying the data stored under the old RP duration ( as explained here https://docs.influxdata.com/influxdb/v0.13/troubleshooting/frequently_encountered_issues/#missing-data-after-creating-a-new-default-retention-policy) but haven't had any issues.

Should I expect to see issues or will my data just be kept indefinitely?

I altered the RP via the ALTER command and everything worked correctly however having a few minutes and a few new data points I have not had any issue with missing data.

I expected it to give me issues finding older data.

Before:

name                     duration shardGroupDuration replicaN default
----                     -------- ------------------ -------- -------
autogen                  0s       168h0m0s           1        false
default_retention_policy 720h0m0s 24h0m0s            1        true
one_day                  24h0m0s  1h0m0s             1        false

After ALTER RETENTION POLICY default_retention_policy on defaultdb DURATION INF:

name                     duration shardGroupDuration replicaN default
----                     -------- ------------------ -------- -------
autogen                  0s       168h0m0s           1        false
default_retention_policy 0s       168h0m0s           1        true
one_day                  24h0m0s  1h0m0s             1        false


问:
ASP.NET Core 2.2 kestrel server's performance issue
I'm facing problem with kestrel server's performance. I have following scenario :

```<code>    TestClient(JMeter) -> DemoAPI-1(Kestrel) -> DemoAPI-2(IIS)
</code>```

I'm trying to create a sample application that could get the file content as and when requested.
TestClient(100 Threads) requests to DemoAPI-1 which in turn request to DemoAPI-2. DemoAPI-2 reads a fixed XML file(1 MB max) and returns it's content as a response(In production DemoAPI-2 is not going to be exposed to outside world).

When I tested direct access from TestClient -> DemoAPI-2 I got expected result(good) which is following :

Average : 368ms

Minimum : 40ms

Maximum : 1056ms

Throughput : 40.1/sec

But when I tried to access it through DemoAPI-1 I got following result :

Average : 48232ms

Minimum : 21095ms

Maximum : 49377ms

Throughput : 2.0/sec

As you can see there is a huge difference.I'm not getting even the 10% throughput of DemoAPI-2. I was told has kestrel is more efficient and fast compared to traditional IIS. Also because there is no problem in direct access, I think we can eliminate the possible of problem on DemoAPI-2.

※Code of DemoAPI-1 :

string base64Encoded = null;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                var content = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                base64Encoded = Convert.ToBase64String(content);
            }
return base64Encoded;
```
<p>※Code of DemoAPI-2 :</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet("Demo2")]
    public async Task<IActionResult> Demo2Async(int wait)
    {
        try
        {
            if (wait > 0)
            {
                await Task.Delay(wait);
            }
            var path = Path.Combine(Directory.GetCurrentDirectory(), "test.xml");
            var file = System.IO.File.ReadAllText(path);
            return Content(file);
        }
        catch (System.Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
</code>```

Some additional information :

Both APIs are async.

Both APIs are hosted on different EC2 instances(C5.xlarge Windows Server 2016).

DemoAPI-1(kestrel) is a self-contained API(without reverse proxy)

TestClient(jMeter) is set to 100 thread for this testing.

No other configuration is done for kestrel server as of now.

There are no action filter, middleware or logging that could effect the performance as of now.

Communication is done using SSL on 5001 port.

Wait parameter for DemoAPI2 is set to 0 as of now.

The CPU usage of DEMOAPI-1 is not over 40%.

答:
The problem was due to HttpClient's port exhaustion issue.
I was able to solve this problem by using IHttpClientFactory.
Following article might help someone who faces similar problem.

https://www.stevejgordon.co.uk/httpclient-creation-and-disposal-internals-should-i-dispose-of-httpclient

Body:
I'm facing problem with kestrel server's performance. I have following scenario :

    TestClient(JMeter) -> DemoAPI-1(Kestrel) -> DemoAPI-2(IIS)

I'm trying to create a sample application that could get the file content as and when requested.
TestClient(100 Threads) requests to DemoAPI-1 which in turn request to DemoAPI-2. DemoAPI-2 reads a fixed XML file(1 MB max) and returns it's content as a response(In production DemoAPI-2 is not going to be exposed to outside world).

When I tested direct access from TestClient -> DemoAPI-2 I got expected result(good) which is following :

Average : 368ms

Minimum : 40ms

Maximum : 1056ms

Throughput : 40.1/sec

But when I tried to access it through DemoAPI-1 I got following result :

Average : 48232ms

Minimum : 21095ms

Maximum : 49377ms

Throughput : 2.0/sec

As you can see there is a huge difference.I'm not getting even the 10% throughput of DemoAPI-2. I was told has kestrel is more efficient and fast compared to traditional IIS. Also because there is no problem in direct access, I think we can eliminate the possible of problem on DemoAPI-2.

※Code of DemoAPI-1 :

string base64Encoded = null;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                var content = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                base64Encoded = Convert.ToBase64String(content);
            }
return base64Encoded;

※Code of DemoAPI-2 :

[HttpGet("Demo2")]
    public async Task<IActionResult> Demo2Async(int wait)
    {
        try
        {
            if (wait > 0)
            {
                await Task.Delay(wait);
            }
            var path = Path.Combine(Directory.GetCurrentDirectory(), "test.xml");
            var file = System.IO.File.ReadAllText(path);
            return Content(file);
        }
        catch (System.Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }

Some additional information :

Both APIs are async.

Both APIs are hosted on different EC2 instances(C5.xlarge Windows Server 2016).

DemoAPI-1(kestrel) is a self-contained API(without reverse proxy)

TestClient(jMeter) is set to 100 thread for this testing.

No other configuration is done for kestrel server as of now.

There are no action filter, middleware or logging that could effect the performance as of now.

Communication is done using SSL on 5001 port.

Wait parameter for DemoAPI2 is set to 0 as of now.

The CPU usage of DEMOAPI-1 is not over 40%.


问:
Properly assembling a drinks database with Django (Many to Many)
I would like to set up a drink database, now I have the problem that the databases are not generated accordingly and I do not know how to do this.

i have already tried several things, but unfortunately no solution was found

how the database should look like:

```<code>

Table 1 (Drinks)

-----------------------------------------------------------
drink_Id |  drink_name  | description | image_path | slug |
-----------------------------------------------------------

Table 2 (ingredients)
---------------------------------
ingredient_id | ingredient_name |
---------------------------------

Table 3 (drink_ratio)
---------------------
ID_ratio | quantity |
---------------------

Table 4 ()
-----------------------------------------
id | drink_id | ingredient_id | ID_ratio |
-----------------------------------------

</code>```

Code:

```<code>

from django.db import models

class Drinks(models.Model):
    drink_name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    image_path = models.ImageField(upload_to="./images")
    slug = models.SlugField(unique=True)
    ingredient = models.ManyToManyField('ingredient')

    def __str__(self):
        return self.drink_name

class ingredient(models.Model):
    name = models.CharField(max_length=256, unique=True)

    liquid_ratio = models.ManyToManyField('liquid_ratio')

    def __str__(self):
        return self.name

class liquid_ratio(models.Model):
    quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)
</code>```

I want to achieve that I have only 4 tables.
like at the top.

A drink can have several ingredients.
A drink can only exist once.

A drink can only have one quantity per ingredient.

THANK YOU :))

答:
I'm not sure why you want a separate drink_ratio table. The quantity is a property of the linking element between drink and ingredient, and therefore belongs on the through table (table 4); table 3 isn't required at all. You can model this in Django by using the through parameter:

```<code>class Drink(models.Model):
    drink_name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    image_path = models.ImageField(upload_to="./images")
    slug = models.SlugField(unique=True)
    ingredient = models.ManyToManyField('Ingredient', through='IngredientRatio')

    def __str__(self):
        return self.drink_name

class Ingredient(models.Model):
    name = models.CharField(max_length=256, unique=True)

    def __str__(self):
        return self.name

class IngredientRatio(models.Model):
    quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)
    ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE)
    drink = models.ForeignKey('Drink', on_delete=models.CASCADE)
</code>```

(Note, Django models should be named in the singular and with CamelCase.)

Body:
I would like to set up a drink database, now I have the problem that the databases are not generated accordingly and I do not know how to do this.

i have already tried several things, but unfortunately no solution was found

how the database should look like:

Table 1 (Drinks)

-----------------------------------------------------------
drink_Id |  drink_name  | description | image_path | slug |
-----------------------------------------------------------

Table 2 (ingredients)
---------------------------------
ingredient_id | ingredient_name |
---------------------------------

Table 3 (drink_ratio)
---------------------
ID_ratio | quantity |
---------------------

Table 4 ()
-----------------------------------------
id | drink_id | ingredient_id | ID_ratio |
-----------------------------------------

Code:

from django.db import models

class Drinks(models.Model):
    drink_name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    image_path = models.ImageField(upload_to="./images")
    slug = models.SlugField(unique=True)
    ingredient = models.ManyToManyField('ingredient')

    def __str__(self):
        return self.drink_name

class ingredient(models.Model):
    name = models.CharField(max_length=256, unique=True)

    liquid_ratio = models.ManyToManyField('liquid_ratio')

    def __str__(self):
        return self.name

class liquid_ratio(models.Model):
    quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)

I want to achieve that I have only 4 tables.
like at the top.

A drink can have several ingredients.
A drink can only exist once.

A drink can only have one quantity per ingredient.

THANK YOU :))

Body:
I'm not sure why you want a separate drink_ratio table. The quantity is a property of the linking element between drink and ingredient, and therefore belongs on the through table (table 4); table 3 isn't required at all. You can model this in Django by using the through parameter:

class Drink(models.Model):
    drink_name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    image_path = models.ImageField(upload_to="./images")
    slug = models.SlugField(unique=True)
    ingredient = models.ManyToManyField('Ingredient', through='IngredientRatio')

    def __str__(self):
        return self.drink_name

class Ingredient(models.Model):
    name = models.CharField(max_length=256, unique=True)

    def __str__(self):
        return self.name

class IngredientRatio(models.Model):
    quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)
    ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE)
    drink = models.ForeignKey('Drink', on_delete=models.CASCADE)

(Note, Django models should be named in the singular and with CamelCase.)


问:
Resolve await in function
I'm trying to get the valid jwt token for an async method using await.
How to resolve await isValid in function?</p>

```<code>  module.exports.resolveAfter2Seconds =  async function resolveAfter2Seconds(jwt) {
       const cert = fs.readFileSync(__dirname + ‘/...’);  // get public key
       let a =  await isValid(jwt, cert)
    };

    async function isValid(jwt, cert) {
       return jwtWebToken.verify(jwt, cert, function (err, decoded) {
           console.log(decoded);
           if (! decoded) {
               throw new Error(“error”);
           }

           return decoded;
       })
    }
</code>```

答:
Try out the following code.</p>

```<code>function isValid(jwt, cert) {
  return new Promise(function(resolve) {
    jwtWebToken.verify(jwt, cert, function (err, decoded) {
      if (! decoded) {
          throw new Error(“error”);
      }

      resolve(decoded)
    })
  });
}
</code>```

Title: Resolve await in function

Body:
I'm trying to get the valid jwt token for an async method using await.
How to resolve await isValid in function?

  module.exports.resolveAfter2Seconds =  async function resolveAfter2Seconds(jwt) {
       const cert = fs.readFileSync(__dirname + ‘/...’);  // get public key
       let a =  await isValid(jwt, cert)
    };

    async function isValid(jwt, cert) {
       return jwtWebToken.verify(jwt, cert, function (err, decoded) {
           console.log(decoded);
           if (! decoded) {
               throw new Error(“error”);
           }

           return decoded;
       })
    }

Body:
Try out the following code.

function isValid(jwt, cert) {
  return new Promise(function(resolve) {
    jwtWebToken.verify(jwt, cert, function (err, decoded) {
      if (! decoded) {
          throw new Error(“error”);
      }

      resolve(decoded)
    })
  });
}


问:
.editorconfig file is not working in VS 2017
editorconfig file in my projects which works fine on VSCODE but the same doesnt work  in the VISUAL STUDIO 2017 version : 15.5.4.
As per the Documentation on GITHUB Repo https://github.com/editorconfig/editorconfig-visualstudio#readme it should work but it doesnt. Has anybody tried it with Visual Studio.
My .editorconfig file :</p>

```<code>root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
</code>```

答:
Make sure that the editorconfig file is at the root folder of your repository and not just in the same folder as your solution file.

I had a similar issue in VS 2017 15.9 : I had added the editorconfig file to my solution, following Microsoft's documentation, but it didn't get applied.
My solution had a weird architecture : the solution file was not in the root folder of my repository, but in its own subfolder. The editorconfig file was created in this subfolder.
Here's the interesting bit in the documentation :

When you add an .editorconfig file to a folder in your file hierarchy,
  its settings apply to all applicable files at that level and below.

So what's important is the actual filesystem hierarchy, not your solution's hierarchy. I moved the editorconfig file to the actual root folder of my project, it worked instantly.

Body:
editorconfig file in my projects which works fine on VSCODE but the same doesnt work  in the VISUAL STUDIO 2017 version : 15.5.4.
As per the Documentation on GITHUB Repo https://github.com/editorconfig/editorconfig-visualstudio#readme it should work but it doesnt. Has anybody tried it with Visual Studio.
My .editorconfig file :

root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true


问:
Scraping each image from a craigslist search
I'm trying to pull each image url from a craigslist search, but can't seem to drill down to the URL itself.  When I try soup.find_all("a", { "class":"result-image gallery"} )[0].img, it doesn't return anything.

Specifically, the page I am trying to scrape is https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates.

I'm trying to get the image at the following src: https://images.craigslist.org/00j0j_cC4PhAMdHLj_300x300.jpg

The super frustrating thing is that I was able to successfully do this yesterday, but didn't commit that working code to Github at the time.  I have since accidentally deleted it and can't figure out what I had originally done to make this work :(

答:
You only need requests and the landing page.

You can construct from the ids on the page (And get all the images for each property)

The data-ids attribute provides a list of the ids for the associated images which you can use to construct each image url.

    $99000
```
</div>
</div>
</p>

```from bs4 import BeautifulSoup as bs
import requests

image_url = 'https://images.craigslist.org/{}_300x300.jpg'
r = requests.get('https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates')
soup = bs(r.content, 'lxml')
ids = [item['data-ids'].replace('1:','') for item in soup.select('.result-image[data-ids]')]
images = [image_url.format(j) for i in ids for j in i.split(',')]
print(images)
```

Body:
You only need requests and the landing page.

You can construct from the ids on the page (And get all the images for each property)

The data-ids attribute provides a list of the ids for the associated images which you can use to construct each image url.

<a href="https://raleigh.craigslist.org/reo/d/rocky-mount-off-market-multifamily/6892616013.html" class="result-image gallery" data-ids="1:00j0j_cC4PhAMdHLj"><img alt="" class="" src="https://images.craigslist.org/00j0j_cC4PhAMdHLj_300x300.jpg">
    <span class="result-price">$99000</span>
</a>

from bs4 import BeautifulSoup as bs
import requests

image_url = 'https://images.craigslist.org/{}_300x300.jpg'
r = requests.get('https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates')
soup = bs(r.content, 'lxml')
ids = [item['data-ids'].replace('1:','') for item in soup.select('.result-image[data-ids]')]
images = [image_url.format(j) for i in ids for j in i.split(',')]
print(images)


问:
How to pass an intent back to MainActivity
My app has a RecyclerView in the MainActivity with an onClickListener which sends an intent to a DetailActivity. The DetailActivity has a button to go back without doing anything and a button to send an intent to the `Activity.
I already checked other posts in here like How to pass intent with extras to an already running activity  and others, but no one results.

Here is a version that I tried:

MainActivity:

```<code>@Override
protected void onNewIntent(Intent intent) {
    int codPedido = getIntent().getIntExtra("CodPedido",1);

    //Toast to test if it's working
    Toast.makeText(getApplicationContext(), String.valueOf(codPedido), Toast.LENGTH_SHORT).show();
}
</code>```

OnClick of RecyclerViewAdapter:

```<code>Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
</code>```

DetailActivity:

```<code>public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_confirm) {
            Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            startActivityForResult(intent, 1);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
</code>```

Edit:

This is what I tried now:

```<code>    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity mActivity = new MainActivity();
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            mActivity.startActivityForResult(intent, 1);
        }
    });
</code>```

and it gives method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

What I was doing before was using the context which is here in the constructor

```<code>public RvPedidosAdapter(List<Pedido> pedidos, Context context) {
    this.pedidos = pedidos;
    this.context = context;
}
</code>```

like this:

```<code>    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            context.startActivity(intent);
        }
    });
</code>```

答:
you can use
startActivityForResult(Intent intent,int requestcode);

Body:
My app has a RecyclerView in the MainActivity with an onClickListener which sends an intent to a DetailActivity. The DetailActivity has a button to go back without doing anything and a button to send an intent to the `Activity.
I already checked other posts in here like How to pass intent with extras to an already running activity  and others, but no one results.

Here is a version that I tried:

MainActivity:

@Override
protected void onNewIntent(Intent intent) {
    int codPedido = getIntent().getIntExtra("CodPedido",1);

    //Toast to test if it's working
    Toast.makeText(getApplicationContext(), String.valueOf(codPedido), Toast.LENGTH_SHORT).show();
}

OnClick of RecyclerViewAdapter:

Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());

DetailActivity:

public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_confirm) {
            Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            startActivityForResult(intent, 1);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Edit:

This is what I tried now:

    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity mActivity = new MainActivity();
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            mActivity.startActivityForResult(intent, 1);
        }
    });

and it gives method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

What I was doing before was using the context which is here in the constructor

public RvPedidosAdapter(List<Pedido> pedidos, Context context) {
    this.pedidos = pedidos;
    this.context = context;
}

like this:

    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            context.startActivity(intent);
        }
    });


问:
how to read dictionary key and values from a nested list and dictionary
I have following dictionary with nested dictionary and lists, was trying to output the values for all the keys "name".
i couldn't figure out the logic to implement on this dictionary

expecting output like

```<code>test
inside_test
inner_group1
GetFTP
</code>```

Dictionary data:

```<code>{
  "id": "0ce8df69-016b-1000-ffff-ffffbe50cb53",
  "name": "test",
  "processGroupStatusSnapshot": {
    "name": "test",
    "connectionStatusSnapshots": [],
    "processorStatusSnapshots": [],
    "processGroupStatusSnapshots": [
      {
        "id": "0ce90089-016b-1000-ffff-ffffadb84af5",
        "processGroupStatusSnapshot": {
          "name": "inside_test",
          "connectionStatusSnapshots": [],
          "processorStatusSnapshots": [],
          "processGroupStatusSnapshots": [
            {
              "id": "0ce97287-016b-1000-0000-000056414ae7",
              "processGroupStatusSnapshot": {
                "id": "0ce97287-016b-1000-0000-000056414ae7",
                "name": "inner_group1",
                "connectionStatusSnapshots": [],
                "processorStatusSnapshots": [
                  {
                    "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                    "processorStatusSnapshot": {
                      "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                      "groupId": "0ce97287-016b-1000-0000-000056414ae7",
                      "name": "GetFTP"
                    }
                  }
                ],
                "processGroupStatusSnapshots": [],
                "remoteProcessGroupStatusSnapshots": [],
                "inputPortStatusSnapshots": [],
                "outputPortStatusSnapshots": []
              }
            }
          ]
        }
      }
    ]
  }
}
</code>```

答:
Given the nesting, and the fact that key names will remain same in all levels, I think a recursive solution will work best here. Please feel free to use this solution as reference and modify based on your needs.

Argument d is the dictionary here.

def find_name(d):
    if 'processGroupStatusSnapshot' in d:
        print("Name =", d['processGroupStatusSnapshot']['name'])
        nxt = d['processGroupStatusSnapshot']['processGroupStatusSnapshots']
        if len(nxt) > 0:
            find_name(nxt[0])

find_name(d)
```

Body:
I have following dictionary with nested dictionary and lists, was trying to output the values for all the keys "name".
i couldn't figure out the logic to implement on this dictionary

expecting output like

test
inside_test
inner_group1
GetFTP

Dictionary data:

{
  "id": "0ce8df69-016b-1000-ffff-ffffbe50cb53",
  "name": "test",
  "processGroupStatusSnapshot": {
    "name": "test",
    "connectionStatusSnapshots": [],
    "processorStatusSnapshots": [],
    "processGroupStatusSnapshots": [
      {
        "id": "0ce90089-016b-1000-ffff-ffffadb84af5",
        "processGroupStatusSnapshot": {
          "name": "inside_test",
          "connectionStatusSnapshots": [],
          "processorStatusSnapshots": [],
          "processGroupStatusSnapshots": [
            {
              "id": "0ce97287-016b-1000-0000-000056414ae7",
              "processGroupStatusSnapshot": {
                "id": "0ce97287-016b-1000-0000-000056414ae7",
                "name": "inner_group1",
                "connectionStatusSnapshots": [],
                "processorStatusSnapshots": [
                  {
                    "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                    "processorStatusSnapshot": {
                      "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                      "groupId": "0ce97287-016b-1000-0000-000056414ae7",
                      "name": "GetFTP"
                    }
                  }
                ],
                "processGroupStatusSnapshots": [],
                "remoteProcessGroupStatusSnapshots": [],
                "inputPortStatusSnapshots": [],
                "outputPortStatusSnapshots": []
              }
            }
          ]
        }
      }
    ]
  }
}


问:
How to set a mediaSubtype on a PHAsset created by the app
I'm creating an app that is intended to output an image with a custom depth map. I've managed to do this after a little bit of fiddling and it works nicely. However, despite having both a depth map and a portrait matte effect, and despite my being able to load and use these successfully within my app, the asset still does not have the correct media subtype (PHAssetMediaSubtype.photoDepthEffect). This is important to me since I want to filter the user's gallery and display only those images which contain a depth effect, and the proper way to do that is to query the media subtype.

Does anyone know what has to be done to ensure this subtype is properly set? I cannot find a way to change it, and can only assume that the system infers it from the asset's auxiliary data.

答:
Here's a temp solution that works

I can't find any APIs to declare a depth photo as an active portrait subtype like the photos app does when you tap the Portrait button. So I created a temporary fix until I can find a solution.

When taking a photo, I flag my photos with photoDepthEffects by setting the originalFilename with my App identifier. Then in the reader, I grab all the assets and check if the PHAssets mediaSubtype is set to PHAssetMediaSubtype.photoDepthEffect. These are the ones in the Portraits folder. This is pretty fast.

If not found, I look to see if the photo has my originalFilename flag. Grabbing an assetResource is kind of slow, so I only check for the last 200 photos taken.

We should contact Apple tech support and see if there is a way to flag the photos into the portrait folder like the photos app does.


问:
Postgresql COPY empty string as NULL not work
I have a CSV file with some integer column, now it 's saved as "" (empty string).

I want to COPY them to a table as NULL value.

With JAVA code, I have try these:

```<code>String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',',  HEADER true)";
String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',', NULL ''  HEADER true)";
</code>```

I get: PSQLException: ERROR: invalid input syntax for type numeric: ""

```<code>String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',', NULL '\"\"'  HEADER true)";
</code>```

I get: PSQLException: ERROR: CSV quote character must not appear in the NULL specification

Any one has done this before ?

答:
Since Postgres 9.4 you now have the ability to use FORCE_NULL. This causes the empty string to be converted into a NULL. Very handy, especially with CSV files (actually this is only allowed when using CSV format).

The syntax is as follow:

```<code>COPY table FROM '/path/to/file.csv'
WITH (FORMAT CSV, DELIMITER ';', FORCE_NULL (columnname));
</code>```

Further details are explained in the documentation: https://www.postgresql.org/docs/current/sql-copy.html

Body:
I have a CSV file with some integer column, now it 's saved as "" (empty string).

I want to COPY them to a table as NULL value.

With JAVA code, I have try these:

String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',',  HEADER true)";
String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',', NULL ''  HEADER true)";

I get: PSQLException: ERROR: invalid input syntax for type numeric: ""

String sql = "COPY " + tableName + " FROM STDIN (FORMAT csv,DELIMITER ',', NULL '\"\"'  HEADER true)";

I get: PSQLException: ERROR: CSV quote character must not appear in the NULL specification

Any one has done this before ?

Body:
Since Postgres 9.4 you now have the ability to use FORCE_NULL. This causes the empty string to be converted into a NULL. Very handy, especially with CSV files (actually this is only allowed when using CSV format).

The syntax is as follow:

COPY table FROM '/path/to/file.csv'
WITH (FORMAT CSV, DELIMITER ';', FORCE_NULL (columnname));

Further details are explained in the documentation: https://www.postgresql.org/docs/current/sql-copy.html


问:
What should the return type be?
```<code>ABRecordCopyValue(thisPerson, kABPersonAddressProperty);
</code>```

thisPerson is ABRecordRef

Thanks

答:
Just do:

```<code>NSLog(@"%@",[ABRecordCopyValue(thisPerson, kABPersonAddressProperty) class]);
</code>```

And that should tell you what class is being returned.

Title: What should the return type be?

Body:
ABRecordCopyValue(thisPerson, kABPersonAddressProperty);

thisPerson is ABRecordRef

Thanks

Body:
Just do:

NSLog(@"%@",[ABRecordCopyValue(thisPerson, kABPersonAddressProperty) class]);

And that should tell you what class is being returned.


问:
Setting a bool: One function with condition vs two separate functions
Given the function:

```<code>function Foo() {
  this.state;
}
</code>```

with this.state being a boolean triggering different functions when set depending on the value (true/false),
which one of the two following implementations is better (or common) and why?

One function with condition

```<code>this.setState = function(bool) {
  if(bool) {
    bar();
  }
  else {
    baz();
  }

  this.state = bool;
}
</code>```

Two separate functions

```<code>this.stateTrue = function() {
  bar();

  this.state = true;
}

this.stateFalse = function() {
  baz();

  this.state = false;
}
</code>```

答:
You should use the first one because it follows DRY principle: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

I would just slightly modify it:

```<code>this.setState = function(bool) {
  bool ? bar() : baz();
  this.state = bool;
}
</code>```

Always try to write less redundant code but don't compromise too much. Make it less but readable.

Body:
Given the function:

function Foo() {
  this.state;
}

with this.state being a boolean triggering different functions when set depending on the value (true/false),
which one of the two following implementations is better (or common) and why?

One function with condition

this.setState = function(bool) {
  if(bool) {
    bar();
  }
  else {
    baz();
  }

  this.state = bool;
}

Two separate functions

this.stateTrue = function() {
  bar();

  this.state = true;
}

this.stateFalse = function() {
  baz();

  this.state = false;
}

Body:
You should use the first one because it follows DRY principle: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

I would just slightly modify it:

this.setState = function(bool) {
  bool ? bar() : baz();
  this.state = bool;
}

Always try to write less redundant code but don't compromise too much. Make it less but readable.


问:
Ignoring specified items of StringList
I would like to create a program (learning Delphi) that takes 3 different list (from TEdit)

A list of names

A list of names to ignore when searching first list

A list of names to ignore when searching first list

By taking the 3 TEdit and converting the text to TStringList and seperating (I am so far okay with this).

I want to output the first name (or item) of the first list that is neither on 2nd or 3rd list

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
i, j ,k : integer;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for k := 0 to list.Count - 1 do
  begin
    for i := 0 to ignoreListFirst.Count - 1 do
    begin
      for j := 0 to ignoreListSecond.Count - 1 do
      begin
        if (list[k] <> ignoreListFirst[i]) and (list[k] <> ignoreListSecond[k]) then

        EditResult.Text := list[k];
        break;

      end;
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  EditList.Text := 'Katy,Mary,John,Maggie,Carl';
  EditIgnoreList1.Text := 'Katy,Mary,John';
  EditIgnoreList2.Text := 'John,Carl';
end;

</code>```

Tried swapping the loop order to see if I can pinpoint the problem.

first list in last loop give me no errors and produces the name 'Katy' which is yes, the first on the list but ignored.

Swapped the the first list to be first loop. produces 'Mary' which I guess ignored (which I wanted) Katy but not others from what I can see.

In this example (which does not work) I want it to result 'Maggie' which is not on either ignore lists.

Thanks and sorry if I explained this wrong. Learning Delphi.
Do pinpoint any mistakes.

答:
I'll do as follows, using TStrings.IndexOf function.

Note: Remember to free your lists in a try-finally block or you will generate memory leaks, sooner or later.

```<code>var
  List : TStrings;
  IgnoreListFirst : TStrings;
  IgnoreListSecond : TStrings;
  i : integer;
begin
  List := TStringList.Create;
  IgnoreListFirst := TStringList.Create;
  IgnoreListSecond := TStringList.Create;
  try
    List.Delimiter := ',';
    IgnoreListFirst.Delimiter := ',';
    IgnoreListSecond.Delimiter := ',';

    List.DelimitedText := EditList.Text;
    IgnoreListFirst.DelimitedText := EditIgnoreList1.Text;
    IgnoreListSecond.DelimitedText := EditIgnoreList2.Text;

    for i := 0 to List.Count do
    begin
      if(IgnoreListFirst.IndexOf(List[i]) = -1) and (IgnoreListSecond.IndexOf(List[i]) = -1) then
      begin
        EditResult.Text := List[i];
        Exit;
      end;
    end;

  finally
    IgnoreListSecond.Free;
    IgnoreListFirst.Free;
    List.Free;
  end;
end;
</code>```

Title: Ignoring specified items of StringList

Body:
I would like to create a program (learning Delphi) that takes 3 different list (from TEdit)

A list of names

A list of names to ignore when searching first list

A list of names to ignore when searching first list

By taking the 3 TEdit and converting the text to TStringList and seperating (I am so far okay with this).

I want to output the first name (or item) of the first list that is neither on 2nd or 3rd list

procedure TForm1.Button1Click(Sender: TObject);
var
i, j ,k : integer;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for k := 0 to list.Count - 1 do
  begin
    for i := 0 to ignoreListFirst.Count - 1 do
    begin
      for j := 0 to ignoreListSecond.Count - 1 do
      begin
        if (list[k] <> ignoreListFirst[i]) and (list[k] <> ignoreListSecond[k]) then

        EditResult.Text := list[k];
        break;

      end;
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  EditList.Text := 'Katy,Mary,John,Maggie,Carl';
  EditIgnoreList1.Text := 'Katy,Mary,John';
  EditIgnoreList2.Text := 'John,Carl';
end;

Tried swapping the loop order to see if I can pinpoint the problem.

first list in last loop give me no errors and produces the name 'Katy' which is yes, the first on the list but ignored.

Swapped the the first list to be first loop. produces 'Mary' which I guess ignored (which I wanted) Katy but not others from what I can see.

In this example (which does not work) I want it to result 'Maggie' which is not on either ignore lists.

Thanks and sorry if I explained this wrong. Learning Delphi.
Do pinpoint any mistakes.

Body:
I'll do as follows, using TStrings.IndexOf function.

Note: Remember to free your lists in a try-finally block or you will generate memory leaks, sooner or later.

var
  List : TStrings;
  IgnoreListFirst : TStrings;
  IgnoreListSecond : TStrings;
  i : integer;
begin
  List := TStringList.Create;
  IgnoreListFirst := TStringList.Create;
  IgnoreListSecond := TStringList.Create;
  try
    List.Delimiter := ',';
    IgnoreListFirst.Delimiter := ',';
    IgnoreListSecond.Delimiter := ',';

    List.DelimitedText := EditList.Text;
    IgnoreListFirst.DelimitedText := EditIgnoreList1.Text;
    IgnoreListSecond.DelimitedText := EditIgnoreList2.Text;

    for i := 0 to List.Count do
    begin
      if(IgnoreListFirst.IndexOf(List[i]) = -1) and (IgnoreListSecond.IndexOf(List[i]) = -1) then
      begin
        EditResult.Text := List[i];
        Exit;
      end;
    end;

  finally
    IgnoreListSecond.Free;
    IgnoreListFirst.Free;
    List.Free;
  end;
end;


问:
not all of my list wraps around the image
I have an unordered list and I am trying to get it to wrap around an image.  For some reason, the bottom two elements of the list "stick out".

Below is the html code I have written:

```<code><div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
        <h3>Makers Academy</h3>
        <ul class="list">
            <li>Agile Principles and Extreme Programming (XP) Values</li>
            <li>HTML, CSS and JavaScript</li>
            <li>Pair Programming </li>
            <li>Independent and Remote Learning</li>
            <li>Problem Solving</li>
            <li>OOP, TDD, SOLID, MVC, DDD</li>
            <li>JavaScript ES6</li>
            <li>SQL, PostgreSQL</li>
            <li>MongoDB</li>
            <li>Swift</li>
        </ul>
    </div>
</div>
</code>```

and this is the css code I have written:

```<code>h2 {
    color: #66BFBF;
    font-family: 'Monserrat', sans-serif;
    font-size: 2.5rem;
}

h3 {
    text-align: center;
    font-family: 'Montserrat', sans-serif;
    font-size: 2.8rem;
    color: #66BFBF;
    font-weight: normal;
    /* line-height: 2; */
}

.middle {
    height: 200px;
    width: 200px;
    background-color: red;
}

.bottom {
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
}

.bottom-cloud {
    position: absolute;
    left: 300px;
    bottom: 300px;
}

.top-cloud {
    position: absolute;
    right: 300px;
    top: 50px;
}

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.chilli-img {
    width: 25%;
    float: left;
}
</code>```

Any help would be appreciated.  I have used pesticide to give a perspective of where the divs are.

答:
HTML:

```<code><div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
      <div class="left-panel">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
      </div>
      <div class="right-panel">
        <h3>Makers Academy</h3>
        <ul class="list">
          <li>Agile Principles and Extreme Programming (XP) Values</li>
          <li>HTML, CSS and JavaScript</li>
          <li>Pair Programming </li>
          <li>Independent and Remote Learning</li>
          <li>Problem Solving</li>
          <li>OOP, TDD, SOLID, MVC, DDD</li>
          <li>JavaScript ES6</li>
          <li>SQL, PostgreSQL</li>
          <li>MongoDB</li>
          <li>Swift</li>
        </ul>
      </div>
    </div>
  </div>
</code>```

and replace your CSS:

```<code>    *{
      box-sizing: border-box;
    }

    h2 {
      color: #66BFBF;
      font-family: 'Monserrat', sans-serif;
      font-size: 2.5rem;
    }

    h3 {
      font-family: 'Montserrat', sans-serif;
      font-size: 2.8rem;
      color: #66BFBF;
      font-weight: normal;
      /* line-height: 2; */
    }

    ul{
      padding-left: 20px;
    }

    img{
      width:100%;
    }

    .skill-row{
      overflow:hidden;
    }

    .left-panel, .right-panel{
      float:left;
    }

    .left-panel{
      width:30%;
    }

    .right-panel{
      width:70%;
      padding-left:20px;
    }
</code>```

Body:
I have an unordered list and I am trying to get it to wrap around an image.  For some reason, the bottom two elements of the list "stick out".

Below is the html code I have written:

My Skills.

Makers Academy

Agile Principles and Extreme Programming (XP) Values

HTML, CSS and JavaScript

Pair Programming

Independent and Remote Learning

Problem Solving

OOP, TDD, SOLID, MVC, DDD

JavaScript ES6

SQL, PostgreSQL

MongoDB

Swift

and this is the css code I have written:

h2 {
    color: #66BFBF;
    font-family: 'Monserrat', sans-serif;
    font-size: 2.5rem;
}

h3 {
    text-align: center;
    font-family: 'Montserrat', sans-serif;
    font-size: 2.8rem;
    color: #66BFBF;
    font-weight: normal;
    /* line-height: 2; */
}

.middle {
    height: 200px;
    width: 200px;
    background-color: red;
}

.bottom {
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
}

.bottom-cloud {
    position: absolute;
    left: 300px;
    bottom: 300px;
}

.top-cloud {
    position: absolute;
    right: 300px;
    top: 50px;
}

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.chilli-img {
    width: 25%;
    float: left;
}

Any help would be appreciated.  I have used pesticide to give a perspective of where the divs are.

Body:
HTML:

<div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
      <div class="left-panel">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
      </div>
      <div class="right-panel">
        <h3>Makers Academy</h3>
        <ul class="list">
          <li>Agile Principles and Extreme Programming (XP) Values</li>
          <li>HTML, CSS and JavaScript</li>
          <li>Pair Programming </li>
          <li>Independent and Remote Learning</li>
          <li>Problem Solving</li>
          <li>OOP, TDD, SOLID, MVC, DDD</li>
          <li>JavaScript ES6</li>
          <li>SQL, PostgreSQL</li>
          <li>MongoDB</li>
          <li>Swift</li>
        </ul>
      </div>
    </div>
  </div>

and replace your CSS:

    *{
      box-sizing: border-box;
    }

    h2 {
      color: #66BFBF;
      font-family: 'Monserrat', sans-serif;
      font-size: 2.5rem;
    }

    h3 {
      font-family: 'Montserrat', sans-serif;
      font-size: 2.8rem;
      color: #66BFBF;
      font-weight: normal;
      /* line-height: 2; */
    }

    ul{
      padding-left: 20px;
    }

    img{
      width:100%;
    }

    .skill-row{
      overflow:hidden;
    }

    .left-panel, .right-panel{
      float:left;
    }

    .left-panel{
      width:30%;
    }

    .right-panel{
      width:70%;
      padding-left:20px;
    }


答:
The iOS documentation says: CFTypeRef - or do I get you wrong?

Regards
Chris

Title: What should the return type be?


答:
You can try Linq:

```<code>  string source = "More text 123 !.?";

  int result = source
    .Reverse()
    .TakeWhile(c => !char.IsLetterOrDigit(c))
    .Count();
</code>```

Demo:

```<code>string[] tests = new string[] {
  "Some text.",
  "More text 123 !.?",
  "Even more text 123"
};

string demo = string.Join(Environment.NewLine, tests
  .Select(s => $"{s,-30} : {s.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count()}"));

Console.Write(demo);
</code>```

Outcome:

```<code>Some text.                     : 1
More text 123 !.?              : 4
Even more text 123             : 0
</code>```

Title: How to count everything but letters at end of a string

Body:
I have a random string and need to know the number of non-letter / non-number characters at the end of it.

For example:

"Some text." should result in 1

"More text 123 !.?" should result in 4 (blanks included)

"Even more text 123" should result in 0

How can I do that?

Body:
You can try Linq:

  string source = "More text 123 !.?";

  int result = source
    .Reverse()
    .TakeWhile(c => !char.IsLetterOrDigit(c))
    .Count();

Demo:

string[] tests = new string[] {
  "Some text.",
  "More text 123 !.?",
  "Even more text 123"
};

string demo = string.Join(Environment.NewLine, tests
  .Select(s => $"{s,-30} : {s.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count()}"));

Console.Write(demo);

Outcome:

Some text.                     : 1
More text 123 !.?              : 4
Even more text 123             : 0


问:
python - JSON file from sql query
I have a table as following:

```<code>Name,Shoes

John,Nike
John,Adidas
John,Brand3
David,Nike
David,Adidas
Simon,Nike
Simon,Adidas
Simon,Brand3
Simon,Brand4
</code>```

How can I create a JSON file like that:

```<code>{"John":"nike,Adidas,Brand3","David":"Nike,Adidas","Simon":"Nike,Adidas,Brand3,Brand4"}
</code>```

In python?

Thanks

答:
Python has a collections library from which you can make use of defaultdict. Ref https://docs.python.org/2/library/collections.html#collections.defaultdict

If your data is read into a list of format

```<code>[{"John", "Nike"}, {"John", "Adidas"}, ... , {"Simon", "Brand4"}]
</code>```

You can use defaultdict. It would return the following

```<code>[('John', ["Nike", "Adidas", ...]), ("Simon", ["Nike", "Adidas", "Brand4"])]
</code>```

Hope this helps.

Title: python - JSON file from sql query

Body:
I have a table as following:

Name,Shoes

John,Nike
John,Adidas
John,Brand3
David,Nike
David,Adidas
Simon,Nike
Simon,Adidas
Simon,Brand3
Simon,Brand4

How can I create a JSON file like that:

{"John":"nike,Adidas,Brand3","David":"Nike,Adidas","Simon":"Nike,Adidas,Brand3,Brand4"}

In python?

Thanks

Body:
Python has a collections library from which you can make use of defaultdict. Ref https://docs.python.org/2/library/collections.html#collections.defaultdict

If your data is read into a list of format

[{"John", "Nike"}, {"John", "Adidas"}, ... , {"Simon", "Brand4"}]

You can use defaultdict. It would return the following

[('John', ["Nike", "Adidas", ...]), ("Simon", ["Nike", "Adidas", "Brand4"])]

Hope this helps.