问:
Create a custom percentile rank for a pandas series
I need to calculate the percentile using a specific algorithm that is not available using either pandas.rank() or numpy.rank().

The ranking algorithm is calculated as follows for a series:

rank[i] = (# of values in series less than i + # of values equal to
i*0.5)/total # of values

so if I had the following series

```<code>s=pd.Series(data=[5,3,8,1,9,4,14,12,6,1,1,4,15])
</code>```

For the first element, 5 there are 6 values less than 5 and no other values = to 5.  The rank would be (6+0x0.5)/13 or 6/13.

For the fourth element (1) it would be (0+ 2x0.5)/13 or 1/13.

How could I calculate this without using a loop?  I assume a combination of s.apply and/or s.where() but can't figure it out and have tried searching. I am looking to apply to the entire series at once, with the result being a series with the percentile ranks.

答:
You could use numpy broadcasting. First convert s to a numpy column array. Then use numpy broadcasting to count the number of items less than i for each i. Then count the number of items equal to i for each i (note that we need to subract 1 since, i is equal to i itself). Finally add them and build a Series:

```<code>tmp = s.to_numpy()
s_col = tmp[:, None]
less_than_i_count = (s_col>tmp).sum(axis=1)
eq_to_i_count = ((s_col==tmp).sum(axis=1) - 1) * 0.5
ranks = pd.Series((less_than_i_count + eq_to_i_count) / len(s), index=s.index)
</code>```

Output:

```<code>0     0.461538
1     0.230769
2     0.615385
3     0.076923
4     0.692308
5     0.346154
6     0.846154
7     0.769231
8     0.538462
9     0.076923
10    0.076923
11    0.346154
12    0.923077
dtype: float64
</code>```

Body:
I need to calculate the percentile using a specific algorithm that is not available using either pandas.rank() or numpy.rank().

The ranking algorithm is calculated as follows for a series:

rank[i] = (# of values in series less than i + # of values equal to
i*0.5)/total # of values

so if I had the following series

s=pd.Series(data=[5,3,8,1,9,4,14,12,6,1,1,4,15])

For the first element, 5 there are 6 values less than 5 and no other values = to 5.  The rank would be (6+0x0.5)/13 or 6/13.

For the fourth element (1) it would be (0+ 2x0.5)/13 or 1/13.

How could I calculate this without using a loop?  I assume a combination of s.apply and/or s.where() but can't figure it out and have tried searching. I am looking to apply to the entire series at once, with the result being a series with the percentile ranks.

Body:
You could use numpy broadcasting. First convert s to a numpy column array. Then use numpy broadcasting to count the number of items less than i for each i. Then count the number of items equal to i for each i (note that we need to subract 1 since, i is equal to i itself). Finally add them and build a Series:

tmp = s.to_numpy()
s_col = tmp[:, None]
less_than_i_count = (s_col>tmp).sum(axis=1)
eq_to_i_count = ((s_col==tmp).sum(axis=1) - 1) * 0.5
ranks = pd.Series((less_than_i_count + eq_to_i_count) / len(s), index=s.index)

Output:

0     0.461538
1     0.230769
2     0.615385
3     0.076923
4     0.692308
5     0.346154
6     0.846154
7     0.769231
8     0.538462
9     0.076923
10    0.076923
11    0.346154
12    0.923077
dtype: float64


来源: stackexchange

问:
Pygame (changing simple rectangle to image)
So I don't know how to turn the rectangle representing the player into an image (spaceship). I know it must be simple, but after a few hours with this I'm a little frustrated, so I'm looking for help :(

```<code>bg_color = pygame.Color('black')
text_color = pygame.Color('darkgrey')
obstacles_color = pygame.Color('darkred')
player_color = pygame.Color('yellow')

fps = 60

window_height = 1200
window_width = 1200

player_speed = 4
player_size = 8
player_max_up = 125

obstacle_spawn_rate = 1
obstacle_min_size = 3
obstacle_max_size = 6
obstacle_min_speed = 2
obstacle_max_speed = 2

class Player:
    def __init__(self):
        self.size = player_size
        self.speed = player_speed
        self.color = player_color
        self.position = (window_width / 2, (window_height - (window_height / 10)))

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self, x, y):
        newX = self.position[0] + x
        newY = self.position[1] + y
        if newX < 0 or newX > window_width - player_size:
            newX = self.position[0]
        if newY < window_height - player_max_up or newY > window_height - player_size:
            newY = self.position[0]
        self.position = (newX, newY)

    def collision_detection(self, rect):
        r = self.get_rect()
        return r.colliderect(rect)

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class Obstacles:
    def __init__(self):
        self.size = random.randint(obstacle_min_size, obstacle_max_size)
        self.speed = random.randint(obstacle_min_speed, obstacle_max_speed)
        self.color = obstacles_color
        self.position = (random.randint(0, window_width - self.size), 0 - self.size)

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self):
        self.position = (self.position[0], self.position[1] + self.speed)

    def is_off_window(self):
        return self.position[1] > window_height

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class World:
    def __init__(self):
        self.reset()

    def reset(self):
        self.player = Player()
        self.obstacles = []
        self.gameOver = False
        self.score = 0
        self.obstacles_counter = 0
        self.moveUp = False
        self.moveDown = False
        self.moveLeft = False
        self.moveRight = False

    def is_game_over(self):
        return self.gameOver

    def update(self):
        self.score += 1

        if self.moveUp:
            self.player.move(0, - player_speed)
        if self.moveUp:
            self.player.move(0, player_speed)
        if self.moveLeft:
            self.player.move(-player_speed, 0)
        if self.moveRight:
            self.player.move(player_speed, 0)

        for each in self.obstacles:
            each.move()
            if self.player.collision_detection(each.get_rect()):
                self.gameOver = True
            if each.is_off_window():
                self.obstacles.remove(each)

        self.obstacles_counter += 1
        if self.obstacles_counter > obstacle_spawn_rate:
            self.obstacles_counter = 0
            self.obstacles.append(Obstacles())

    def draw(self, surface):
        self.player.draw(surface)
        for each in self.obstacles:
            each.draw(surface)

    def movement_keys(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.moveUp = True
            if event.key == pygame.K_DOWN:
                self.moveDown = True
            if event.key == pygame.K_LEFT:
                self.moveLeft = True
            if event.key == pygame.K_RIGHT:
                self.moveRight = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                 self.moveUp = False
            if event.key == pygame.K_DOWN:
                 self.moveDown = False
            if event.key == pygame.K_LEFT:
                 self.moveLeft = False
            if event.key == pygame.K_RIGHT:
                 self.moveRight = False

def run():
    pygame.init()
    clock = pygame.time.Clock()
    window = pygame.display.set_mode((window_height, window_width))
    pygame.display.set_caption("Avoid Obstacles")
    surface = pygame.Surface(window.get_size())
    surface = surface.convert()

    world = World()

    font = pygame.font.SysFont("Times", 35, "bold")

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == ord("r"):
                world.reset()
            else:
                world.movement_keys(event)

        if not world.is_game_over():
            world.update()

        window.fill(bg_color)
        clock.tick(fps)
        world.draw(window)

        surface.blit(surface, (0, 0))
        text = font.render("Score {0}".format(world.score), 1, text_color)
        window.blit(text, (1, 1))
        if world.is_game_over():
            end = font.render("The end of your journey", 1, text_color)
            window.blit(end, (window_width / 2 - 220, window_height / 2))
            restart = font.render("Hit R to reset", 1, text_color)
            window.blit(restart, (window_width / 2 - 120, window_height / 2 + 45))
        pygame.display.update()

if __name__ == '__main__':
    run()
    pygame.quit()
</code>```

I tried changing the draw function in the Player class, but still couldn't figure out how to do it correctly. I'm drawing an image of the spaceship on the screen/window, but I can't get it to move to the player rectangle.

答:
I don't know what you've tried, but here's how to do this with a call to blit:

```<code>myimage = pygame.image.load("bar.png")

...

def draw(self, surface):
    r = self.get_rect()
    surface.blit(myimage, r)
</code>```

The key point here is that you're giving blit the same coordinates that you were using to draw the rectangle.  When I tried this, I got the correct/natural size of the image even though the r rectangle is of different dimensions.  If that turns out to cause a problem, you could adjust the dimensions of the rectangle to be the same as the image.  You also might want to adjust the coordinates of r such that the image is drawn centered on the location at which you wish to draw it.

ContentLicense: CC BY-SA 4.0

Body:
So I don't know how to turn the rectangle representing the player into an image (spaceship). I know it must be simple, but after a few hours with this I'm a little frustrated, so I'm looking for help :(

bg_color = pygame.Color('black')
text_color = pygame.Color('darkgrey')
obstacles_color = pygame.Color('darkred')
player_color = pygame.Color('yellow')

fps = 60

window_height = 1200
window_width = 1200

player_speed = 4
player_size = 8
player_max_up = 125

obstacle_spawn_rate = 1
obstacle_min_size = 3
obstacle_max_size = 6
obstacle_min_speed = 2
obstacle_max_speed = 2

class Player:
    def __init__(self):
        self.size = player_size
        self.speed = player_speed
        self.color = player_color
        self.position = (window_width / 2, (window_height - (window_height / 10)))

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self, x, y):
        newX = self.position[0] + x
        newY = self.position[1] + y
        if newX < 0 or newX > window_width - player_size:
            newX = self.position[0]
        if newY < window_height - player_max_up or newY > window_height - player_size:
            newY = self.position[0]
        self.position = (newX, newY)

    def collision_detection(self, rect):
        r = self.get_rect()
        return r.colliderect(rect)

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class Obstacles:
    def __init__(self):
        self.size = random.randint(obstacle_min_size, obstacle_max_size)
        self.speed = random.randint(obstacle_min_speed, obstacle_max_speed)
        self.color = obstacles_color
        self.position = (random.randint(0, window_width - self.size), 0 - self.size)

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self):
        self.position = (self.position[0], self.position[1] + self.speed)

    def is_off_window(self):
        return self.position[1] > window_height

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class World:
    def __init__(self):
        self.reset()

    def reset(self):
        self.player = Player()
        self.obstacles = []
        self.gameOver = False
        self.score = 0
        self.obstacles_counter = 0
        self.moveUp = False
        self.moveDown = False
        self.moveLeft = False
        self.moveRight = False

    def is_game_over(self):
        return self.gameOver

    def update(self):
        self.score += 1

        if self.moveUp:
            self.player.move(0, - player_speed)
        if self.moveUp:
            self.player.move(0, player_speed)
        if self.moveLeft:
            self.player.move(-player_speed, 0)
        if self.moveRight:
            self.player.move(player_speed, 0)

        for each in self.obstacles:
            each.move()
            if self.player.collision_detection(each.get_rect()):
                self.gameOver = True
            if each.is_off_window():
                self.obstacles.remove(each)

        self.obstacles_counter += 1
        if self.obstacles_counter > obstacle_spawn_rate:
            self.obstacles_counter = 0
            self.obstacles.append(Obstacles())

    def draw(self, surface):
        self.player.draw(surface)
        for each in self.obstacles:
            each.draw(surface)

    def movement_keys(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.moveUp = True
            if event.key == pygame.K_DOWN:
                self.moveDown = True
            if event.key == pygame.K_LEFT:
                self.moveLeft = True
            if event.key == pygame.K_RIGHT:
                self.moveRight = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                 self.moveUp = False
            if event.key == pygame.K_DOWN:
                 self.moveDown = False
            if event.key == pygame.K_LEFT:
                 self.moveLeft = False
            if event.key == pygame.K_RIGHT:
                 self.moveRight = False

def run():
    pygame.init()
    clock = pygame.time.Clock()
    window = pygame.display.set_mode((window_height, window_width))
    pygame.display.set_caption("Avoid Obstacles")
    surface = pygame.Surface(window.get_size())
    surface = surface.convert()

    world = World()

    font = pygame.font.SysFont("Times", 35, "bold")

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == ord("r"):
                world.reset()
            else:
                world.movement_keys(event)

        if not world.is_game_over():
            world.update()

        window.fill(bg_color)
        clock.tick(fps)
        world.draw(window)

        surface.blit(surface, (0, 0))
        text = font.render("Score {0}".format(world.score), 1, text_color)
        window.blit(text, (1, 1))
        if world.is_game_over():
            end = font.render("The end of your journey", 1, text_color)
            window.blit(end, (window_width / 2 - 220, window_height / 2))
            restart = font.render("Hit R to reset", 1, text_color)
            window.blit(restart, (window_width / 2 - 120, window_height / 2 + 45))
        pygame.display.update()

if __name__ == '__main__':
    run()
    pygame.quit()

I tried changing the draw function in the Player class, but still couldn't figure out how to do it correctly. I'm drawing an image of the spaceship on the screen/window, but I can't get it to move to the player rectangle.

Body:
I don't know what you've tried, but here's how to do this with a call to blit:

myimage = pygame.image.load("bar.png")

...

def draw(self, surface):
    r = self.get_rect()
    surface.blit(myimage, r)

The key point here is that you're giving blit the same coordinates that you were using to draw the rectangle.  When I tried this, I got the correct/natural size of the image even though the r rectangle is of different dimensions.  If that turns out to cause a problem, you could adjust the dimensions of the rectangle to be the same as the image.  You also might want to adjust the coordinates of r such that the image is drawn centered on the location at which you wish to draw it.


问:
Unable to install sentence-transformers, getting error
Running below command after installing python 3.10.

pip3 install -U sentence-transformers

List item

ERROR: Cannot install sentence-transformers==0.1.0, sentence-transformers==0.2.0, sentence-transformers==0.2.1, sentence-transformers==0.2.2, sentence-transformers==0.2.3, sentence-transformers==0.2.4, sentence-transformers==0.2.4.1, sentence-transformers==0.2.5, sentence-transformers==0.2.5.1, sentence-transformers==0.2.6.1, sentence-transformers==0.2.6.2, sentence-transformers==0.3.0, sentence-transformers==0.3.1, sentence-transformers==0.3.2, sentence-transformers==0.3.3, sentence-transformers==0.3.4, sentence-transformers==0.3.5, sentence-transformers==0.3.5.1, sentence-transformers==0.3.6, sentence-transformers==0.3.7, sentence-transformers==0.3.7.1, sentence-transformers==0.3.7.2, sentence-transformers==0.3.8, sentence-transformers==0.3.9, sentence-transformers==0.4.0, sentence-transformers==0.4.1, sentence-transformers==0.4.1.1, sentence-transformers==0.4.1.2, sentence-transformers==1.0.0, sentence-transformers==1.0.1, sentence-transformers==1.0.2, sentence-transformers==1.0.3, sentence-transformers==1.0.4, sentence-transformers==1.1.0, sentence-transformers==1.1.1, sentence-transformers==1.2.0, sentence-transformers==1.2.1, sentence-transformers==2.0.0 and sentence-transformers==2.1.0 because these package versions have conflicting dependencies.

The conflict is caused by:
sentence-transformers 2.1.0 depends on torch>=1.6.0

...............

To fix this you could try to:

loosen the range of package versions you've specified

remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies
WARNING: You are using pip version 21.2.4; however, version 22.0.3 is available.
You should consider upgrading via the '/Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10 -m pip install --upgrade pip' command.

答:
I encountered the same error, here is how I fixed it:

first install torch 1.10.0 using the following

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
```
<ul>
<li>then install sentence-transformers 2.1.0 by</li>
</ul>
<pre class="lang-sh prettyprint-override"><code>pip install -U sentence-transformers
</code>```

Body:
I encountered the same error, here is how I fixed it:

first install torch 1.10.0 using the following

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

then install sentence-transformers 2.1.0 by

pip install -U sentence-transformers


问:
Validating Data In A WinForm
I have created a dialog box in my WinForms application. This has many text boxes and ok/cancel buttons. When the user clicks ok, I only want the dialog box to close if all entries are valid. I can see how to do this with the "Validating" events for each control separately. That is fine. But these only seem to fire when a control loses focus. However, empty text boxes in my dialog are also invalid input which means the user may never have focused on that control. I would prefer to just validate all controls on clicking OK.

I can't work out how to do this though. Overriding the onclick of the OK button doesn't seem to have an option for stopping the window from closing. The Form IsClosing event does by setting Cancel = true. But this doesn't seem to be able to distinguish between whether the OK or Cancel button is clicked. Obviously if the cancel button is clicked I don't care about validation and want to allow the form to close regardless.

What is the best approach for doing this?]

Update:
I already had CausesValidation set to true on both my form and ok button but my validation event does not get fired when I click the ok button. I mention this as it was suggested as a solution below.

答:
Please select the form > Set the property CausesValidation to true

Select OK button and again set property CausesValidation to true

and then it will take care of all the validations.

Important points:
1) You must mention e.Cancel=true in all the validating eventhandlers

2) If your buttons are in panels then you must set panels (or any parent control's) CausesValidation property to true

Edit:

3) Validate fires just before loss of focus. While pressing Enter will
cause the default button to Click, it doesn't move the focus to that
button, hence no validation event will be fired if you have set forms AcceptButton Property to OK button

ContentLicense: CC BY-SA 3.0

Title: Validating Data In A WinForm


问:
java split with Greedy quantifiers
Anyone can explain the 12 outputs step by step?

```<code>public static void main(String[] args) {
    String[] splitStrs = "booo:and:fooo1o".split("o*", -1);
    printOutput(splitStrs);
}

static void printOutput(String[] input) {
        System.out.println("count:" + input.length);
        Stream.of(input).map(s -> "\"" + s + "\",").forEach(System.out::print);
        System.out.println();
}
</code>```

output:

count:12

"b","",":","a","n","d",":","f","","1","","",

答:
I found your output a little hard to read so I did it this way. o* will match on any string of o's including none (The * quantifier is 0 or more). So any place that didn't have a o was simply splitting on the space between any two characters.  So ab would yield a and b

Here is what may be confusing.  Consider the string boooob and the split uses o*.

the first split is at the beginning of the line which matches empty string (or null) and oooo.  So b is returned.

the second split is between the previous oooo and b which is empty, so an empty string is returned.

the third split is before and after b (empty on both sides), so b is returned.

the fourth split is after b and it matches null.  It is a trailing match delimiter and returns "" because of your -1.

So the above would return an array of {"b","","b",""}.  You would get the exact same results no matter how long your string of o's were between the two b's.

What you may have been expecting is splitting on o+ which, using -1 again, would return {"b",":and:f","1",""}.

So

```<code>val    split string

"b"    ""
""     "ooo"
":"    ""
"a"    ""
"n"    ""
"d"    ""
":"    ""
"f"    ""
""     "ooo"
"1"    ""
""     "o"
""     ""
</code>```

Here is the code used to generate the the above.  I pasted the second grouping to the right of the first.

Results of the split.

```<code>String str = "booo:and:fooo1o";
String[] s = str.split("o*",-1);
String[] result = Arrays.stream(s).map(a->"\""+a+"\"").toArray(String[]::new);
for (String st : result) {
     System.out.println(st);
}
</code>```

Capture of the split string.

```<code>Matcher m = Pattern.compile("(o*)").matcher(str);
while(m.find()) {
    System.out.println("\""+m.group(1)+"\"");
}

</code>```

Title: java split with Greedy quantifiers

Body:
Anyone can explain the 12 outputs step by step?

public static void main(String[] args) {
    String[] splitStrs = "booo:and:fooo1o".split("o*", -1);
    printOutput(splitStrs);
}

static void printOutput(String[] input) {
        System.out.println("count:" + input.length);
        Stream.of(input).map(s -> "\"" + s + "\",").forEach(System.out::print);
        System.out.println();
}

output:

count:12

"b","",":","a","n","d",":","f","","1","","",

Body:
I found your output a little hard to read so I did it this way. o* will match on any string of o's including none (The * quantifier is 0 or more). So any place that didn't have a o was simply splitting on the space between any two characters.  So ab would yield a and b

Here is what may be confusing.  Consider the string boooob and the split uses o*.

the first split is at the beginning of the line which matches empty string (or null) and oooo.  So b is returned.

the second split is between the previous oooo and b which is empty, so an empty string is returned.

the third split is before and after b (empty on both sides), so b is returned.

the fourth split is after b and it matches null.  It is a trailing match delimiter and returns "" because of your -1.

So the above would return an array of {"b","","b",""}.  You would get the exact same results no matter how long your string of o's were between the two b's.

What you may have been expecting is splitting on o+ which, using -1 again, would return {"b",":and:f","1",""}.

So

val    split string

"b"    ""
""     "ooo"
":"    ""
"a"    ""
"n"    ""
"d"    ""
":"    ""
"f"    ""
""     "ooo"
"1"    ""
""     "o"
""     ""

Here is the code used to generate the the above.  I pasted the second grouping to the right of the first.

Results of the split.

String str = "booo:and:fooo1o";
String[] s = str.split("o*",-1);
String[] result = Arrays.stream(s).map(a->"\""+a+"\"").toArray(String[]::new);
for (String st : result) {
     System.out.println(st);
}

Capture of the split string.

Matcher m = Pattern.compile("(o*)").matcher(str);
while(m.find()) {
    System.out.println("\""+m.group(1)+"\"");
}


问:
#line directive in #ifdef block
How is the C processor/compiler supposed to handle code like this:

```<code>/*1:*/
#line 3 "line.w"

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
printf("Before #ifdef: line %d of %s\n",__LINE__,__FILE__);
#ifdef STAT
printf("Inside #ifdef before section: line %d of %s\n",__LINE__,__FILE__);
/*2:*/
#line 19 "line.w"

printf("Inside section: line %d of %s\n",__LINE__,__FILE__);

/*:2*/
#line 12 "line.w"

printf("Inside #ifdef after section: line %d of %s\n",__LINE__,__FILE__);
#endif
printf("After #ifdef: line %d of %s\n",__LINE__,__FILE__);
return EXIT_SUCCESS;
}

/*:1*/
</code>```

C file line.c was created from CWEB file line.w by ctangle. Note the two #line directives inside the #ifdef ... #endif block.

When I run gcc -E line.c -o line-noSTAT.i and gcc -E -DSTAT line.c -o line-STAT.i, the two expanded *.i files differ in their output in the final printf after the #endif:

```<code>4d3
< # 31 "<command-line>"
6c5
< # 32 "<command-line>" 2
---
> # 1 "<command-line>" 2
1827,1828c1826,1835
< # 22 "line.w"
< printf("After #ifdef: line %d of %s\n",22,"line.w");
---
>
> printf("Inside #ifdef before section: line %d of %s\n",11,"line.w");
> # 19 "line.w"
>
> printf("Inside section: line %d of %s\n",20,"line.w");
> # 12 "line.w"
>
> printf("Inside #ifdef after section: line %d of %s\n",13,"line.w");
>
> printf("After #ifdef: line %d of %s\n",15,"line.w");
1830c1837
< # 23 "line.w" 3 4
---
> # 16 "line.w" 3 4
1832c1839
< # 23 "line.w"
---
> # 16 "line.w"
</code>```

and the compiled program deviates, too:

```<code>$ gcc line.c
$ ./a.out
Before #ifdef: line 9 of line.w
After #ifdef: line 22 of line.w
$ gcc -DSTAT line.c
$ ./a.out
Before #ifdef: line 9 of line.w
Inside #ifdef before section: line 11 of line.w
Inside section: line 20 of line.w
Inside #ifdef after section: line 13 of line.w
After #ifdef: line 15 of line.w
</code>```

Note the significant difference in the After #ifdef output.

AFAIKS, the incorrect After #ifdef: line 22 of line.w comes from the fact that the compiler/preprocessor picks the twenty-second line from line.c, not the fifteenth line from line.w.

This MWE was created with

```<code>$ gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
</code>```

but I have been informed that the MS Visual Studio debugger also has problems with similar (production) code. Also Apple clang version 13.0.0 (clang-1300.0.29.30) produces these differing outcomes.

Shouldn't all code between #ifdef STAT and #endif be eliminated when STAT is not defined?

答:
The C preprocessor – i.e., any variant, hence the consistent behaviour across systems – in fact eliminates the two #line statements in the #ifdef block, if STAT is undefined.

Starting from the first #line 3 "line.w" it continues through line.c, skips all of the #ifdef block, and catches the final printf in the twenty-second line of the C source file, which had been reset to "line.w" at the very beginning.

Duh, this appears to be a deficiency in CWEB's ctangle, which should add a correct #line statement after the #endif.

An intermediate manual way to keep the line numbers in sync is:

Add #line __LINE__ after #endif in the CWEB code line.w

Replace the concrete line number with perl -pi -e "s/#line __LINE__/#line $./" line.w

Convert CWEB to C with ctangle line

Compile C code with/out -DSTAT

Title: #line directive in #ifdef block

Body:
How is the C processor/compiler supposed to handle code like this:

/*1:*/
#line 3 "line.w"

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
printf("Before #ifdef: line %d of %s\n",__LINE__,__FILE__);
#ifdef STAT
printf("Inside #ifdef before section: line %d of %s\n",__LINE__,__FILE__);
/*2:*/
#line 19 "line.w"

printf("Inside section: line %d of %s\n",__LINE__,__FILE__);

/*:2*/
#line 12 "line.w"

printf("Inside #ifdef after section: line %d of %s\n",__LINE__,__FILE__);
#endif
printf("After #ifdef: line %d of %s\n",__LINE__,__FILE__);
return EXIT_SUCCESS;
}

/*:1*/

C file line.c was created from CWEB file line.w by ctangle. Note the two #line directives inside the #ifdef ... #endif block.

When I run gcc -E line.c -o line-noSTAT.i and gcc -E -DSTAT line.c -o line-STAT.i, the two expanded *.i files differ in their output in the final printf after the #endif:

4d3
< # 31 "<command-line>"
6c5
< # 32 "<command-line>" 2
---
> # 1 "<command-line>" 2
1827,1828c1826,1835
< # 22 "line.w"
< printf("After #ifdef: line %d of %s\n",22,"line.w");
---
>
> printf("Inside #ifdef before section: line %d of %s\n",11,"line.w");
> # 19 "line.w"
>
> printf("Inside section: line %d of %s\n",20,"line.w");
> # 12 "line.w"
>
> printf("Inside #ifdef after section: line %d of %s\n",13,"line.w");
>
> printf("After #ifdef: line %d of %s\n",15,"line.w");
1830c1837
< # 23 "line.w" 3 4
---
> # 16 "line.w" 3 4
1832c1839
< # 23 "line.w"
---
> # 16 "line.w"

and the compiled program deviates, too:

$ gcc line.c
$ ./a.out
Before #ifdef: line 9 of line.w
After #ifdef: line 22 of line.w
$ gcc -DSTAT line.c
$ ./a.out
Before #ifdef: line 9 of line.w
Inside #ifdef before section: line 11 of line.w
Inside section: line 20 of line.w
Inside #ifdef after section: line 13 of line.w
After #ifdef: line 15 of line.w

Note the significant difference in the After #ifdef output.

AFAIKS, the incorrect After #ifdef: line 22 of line.w comes from the fact that the compiler/preprocessor picks the twenty-second line from line.c, not the fifteenth line from line.w.

This MWE was created with

$ gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

but I have been informed that the MS Visual Studio debugger also has problems with similar (production) code. Also Apple clang version 13.0.0 (clang-1300.0.29.30) produces these differing outcomes.

Shouldn't all code between #ifdef STAT and #endif be eliminated when STAT is not defined?


问:
Creating custom android dialer
I am working on the new phone app for Android. Obviously it needs to make and receive phone calls.

My first problem is how to place a phone call from the app without invoking System default dialer. Making calls using Intent is very easy. However when I try to place a call without using Intent then that's entirely different ball of wax.

It seems that I need to use android.telephony but I can't find any good resources that could tell me where to start. Simple tutorial would be nice.

If you could point me to a resource that would help me that will be really appreciated.

答:
i faced same problem
couldn't ask default dialer in phone os >= Q android
check my asnwer
https://stackoverflow.com/a/71094871/15072590</p>

Title: Creating custom android dialer


问:
Javascript Multiplying Within an Array
I have an array with multiple arrays inside.  I would like to multiply the contents of each array.

Here is my code--currently not getting anything in console.
The desired output is 3 numbers-- the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}```

答:
You should iterate over rows. So you need to change inner loop on this :

 for (j = 0; j < arr[i].length; j++)

const array = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
];

for (i = 0; i < array.length; i++) {
let result = 1;
  for (j = 0; j < array[i].length; j++) {
    result *= array[i][j]
  }
  console.log(result);
}```

Title: Javascript Multiplying Within an Array


问:
YAML for python dictionaries: copying/referencing blocks
I'm writing a YAML file which contains some configuration data. It will be read in to Python as a dictionary of dictionaries. Some of the data needs to be repeated under a different key. Is there a way to do this without large amounts of cut and paste?

Here is an example of the yaml file:

```<code>BLOCK1:
  a: 1
  b: 2
  c: 3

BLOCK2:
  a: 4
  b: 5
  c: 6

BLOCK3: # Basically the same as BLOCK2
  a: 4  # Is there a way to make this a link to BLOCK2 or a copy of BLOCK2?
  b: 5
  c: 6
</code>```

答:
Yes, there is. Take a look at: http://pyyaml.org/wiki/PyYAMLDocumentation#Aliases

Basically, you should do:

```<code>BLOCK1:
  a: 1
  b: 2
  c: 3

BLOCK2: &block
  a: 4
  b: 5
  c: 6

BLOCK3: *block
</code>```

And the results will be:

```<code>{'BLOCK1': {'a': 1, 'b': 2, 'c': 3},
 'BLOCK2': {'a': 4, 'b': 5, 'c': 6},
 'BLOCK3': {'a': 4, 'b': 5, 'c': 6}}
</code>```

Body:
I'm writing a YAML file which contains some configuration data. It will be read in to Python as a dictionary of dictionaries. Some of the data needs to be repeated under a different key. Is there a way to do this without large amounts of cut and paste?

Here is an example of the yaml file:

BLOCK1:
  a: 1
  b: 2
  c: 3

BLOCK2:
  a: 4
  b: 5
  c: 6

BLOCK3: # Basically the same as BLOCK2
  a: 4  # Is there a way to make this a link to BLOCK2 or a copy of BLOCK2?
  b: 5
  c: 6

Body:
Yes, there is. Take a look at: http://pyyaml.org/wiki/PyYAMLDocumentation#Aliases

Basically, you should do:

BLOCK1:
  a: 1
  b: 2
  c: 3

BLOCK2: &block
  a: 4
  b: 5
  c: 6

BLOCK3: *block

And the results will be:

{'BLOCK1': {'a': 1, 'b': 2, 'c': 3},
 'BLOCK2': {'a': 4, 'b': 5, 'c': 6},
 'BLOCK3': {'a': 4, 'b': 5, 'c': 6}}


问:
Applescript -- How do I insert a class name into a list without the quotes?
I need to insert an AppleScript class name into a list without the quotes so I can enable AirPlay.

i.e. I would like my script to create the following list depending on user interaction:
{AirPlay device "Computer", AirPlay device "Apple TV"}

Note the placement of the quotes.

Then I can use this list to turn on AirPlay and stream to the selected devices.
e.g. tell iTunes to set current AirPlay devices to AirPlayDevicesSelectedList

Below is my script so far but it does not work because the quotes in the list of devices are in the wrong place!

So how do I insert the class name AirPlay device into a list without the quotes?

I suspect the fix may involve changing the AppleScript delimiters.

```<code>tell application "iTunes"

    if AirPlay enabled is true then
        display dialog "Would you like to turn off AirPlay?" buttons {"No", "Yes"} default button "yes" with title "AirPlay"
        if button returned of result = "Yes" then
            set current AirPlay devices to {AirPlay device "Computer"}
        end if
    else
        display dialog "Would you like to turn on AirPlay?" buttons {"No", "Yes"} default button "No" with title "AirPlay"
        if button returned of result = "Yes" then
            set airPlayDevices to (get name of every AirPlay device)
            log (airPlayDevices)
            set airPlayDevicesSelected to choose from list airPlayDevices with prompt "Select one or more AirPlay devices" default items {"Computer"} multiple selections allowed yes
            log (airPlayDevicesSelected)

            set airPlayDevicesSelectedFix to {}
            log (count of airPlayDevicesSelected)
            repeat with i from 1 to count of airPlayDevicesSelected
                set end of airPlayDevicesSelectedFix to "AirPlay device " & item i of airPlayDevicesSelected
            end repeat
            log (airPlayDevicesSelectedFix)
            set current AirPlay devices to airPlayDevicesSelectedFix
        end if
    end if
end tell
</code>```

答:
@red_menance provided the answer.  One cannot easily insert a class name into an existing list of objects.

In this case, one must use a name or ID of the AirPlay device to look up the device and add the required property to the list using code such as the following:

set end of deviceList to first item of (AirPlay devices whose name is "computer")

Using this technique, I have fixed my script which I have reproduced below:

```<code>tell application "iTunes"

    if AirPlay enabled is true then
        display dialog "Would you like to turn off AirPlay?" buttons {"No", "Yes"} default button "yes" with title "AirPlay"
        if button returned of result = "Yes" then
            set current AirPlay devices to {AirPlay device "Computer"}
        end if
    else
        display dialog "Would you like to turn on AirPlay?" buttons {"No", "Yes"} default button "No" with title "AirPlay"
        if button returned of result = "Yes" then
            set airPlayDeviceNames to (get name of every AirPlay device whose available is true)
            set airPlayDeviceNamesSelected to choose from list airPlayDeviceNames with prompt "Select one or more AirPlay devices" default items {"Computer"} multiple selections allowed yes
            if airPlayDeviceNamesSelected is not false then
                set airPlayDeviceList to {}
                repeat with apDevice in airPlayDeviceNamesSelected
                    set end of airPlayDeviceList to first item of (AirPlay devices whose name is apDevice)
                end repeat
                set current AirPlay devices to airPlayDeviceList
            end if
        end if
    end if
end tell
</code>```

Please note:  This script is really basic.  It will not properly handle two AirPlay devices with the same name (but different id's).

Body:
I need to insert an AppleScript class name into a list without the quotes so I can enable AirPlay.

i.e. I would like my script to create the following list depending on user interaction:
{AirPlay device "Computer", AirPlay device "Apple TV"}

Note the placement of the quotes.

Then I can use this list to turn on AirPlay and stream to the selected devices.
e.g. tell iTunes to set current AirPlay devices to AirPlayDevicesSelectedList

Below is my script so far but it does not work because the quotes in the list of devices are in the wrong place!

So how do I insert the class name AirPlay device into a list without the quotes?

I suspect the fix may involve changing the AppleScript delimiters.

tell application "iTunes"

    if AirPlay enabled is true then
        display dialog "Would you like to turn off AirPlay?" buttons {"No", "Yes"} default button "yes" with title "AirPlay"
        if button returned of result = "Yes" then
            set current AirPlay devices to {AirPlay device "Computer"}
        end if
    else
        display dialog "Would you like to turn on AirPlay?" buttons {"No", "Yes"} default button "No" with title "AirPlay"
        if button returned of result = "Yes" then
            set airPlayDevices to (get name of every AirPlay device)
            log (airPlayDevices)
            set airPlayDevicesSelected to choose from list airPlayDevices with prompt "Select one or more AirPlay devices" default items {"Computer"} multiple selections allowed yes
            log (airPlayDevicesSelected)

            set airPlayDevicesSelectedFix to {}
            log (count of airPlayDevicesSelected)
            repeat with i from 1 to count of airPlayDevicesSelected
                set end of airPlayDevicesSelectedFix to "AirPlay device " & item i of airPlayDevicesSelected
            end repeat
            log (airPlayDevicesSelectedFix)
            set current AirPlay devices to airPlayDevicesSelectedFix
        end if
    end if
end tell

Body:
@red_menance provided the answer.  One cannot easily insert a class name into an existing list of objects.

In this case, one must use a name or ID of the AirPlay device to look up the device and add the required property to the list using code such as the following:

set end of deviceList to first item of (AirPlay devices whose name is "computer")

Using this technique, I have fixed my script which I have reproduced below:

tell application "iTunes"

    if AirPlay enabled is true then
        display dialog "Would you like to turn off AirPlay?" buttons {"No", "Yes"} default button "yes" with title "AirPlay"
        if button returned of result = "Yes" then
            set current AirPlay devices to {AirPlay device "Computer"}
        end if
    else
        display dialog "Would you like to turn on AirPlay?" buttons {"No", "Yes"} default button "No" with title "AirPlay"
        if button returned of result = "Yes" then
            set airPlayDeviceNames to (get name of every AirPlay device whose available is true)
            set airPlayDeviceNamesSelected to choose from list airPlayDeviceNames with prompt "Select one or more AirPlay devices" default items {"Computer"} multiple selections allowed yes
            if airPlayDeviceNamesSelected is not false then
                set airPlayDeviceList to {}
                repeat with apDevice in airPlayDeviceNamesSelected
                    set end of airPlayDeviceList to first item of (AirPlay devices whose name is apDevice)
                end repeat
                set current AirPlay devices to airPlayDeviceList
            end if
        end if
    end if
end tell

Please note:  This script is really basic.  It will not properly handle two AirPlay devices with the same name (but different id's).


问:
How do I create a new column in a dataframe using values from another dataframe?
I have two dataframes, df_1 and df_2, where df_1 has several columns of "codes" and df_2 has the definitions for all of those codes:

```<code>df_1 = pd.DataFrame({
    'Age': [42, 35, 64, 53],
    'Code 1': [1234, 3452, 9583, 8753],
    'Code 2': [3857, np.nan, np.nan, 1234]})

df_2 = pd.DataFrame({
    'Code': [3452, 8753, 3857, 1234, 9583],
    'Code Def':['a', 'b', 'c', 'd', 'e']})
</code>```

How do I create a new column in df_1 that contains the definitions of all the codes from df_2 to look something like this?

```<code>Age  Code 1  Code 2  Code def
42    1234    3857    d, c
35    3452    NaN      a
64    9583    NaN      e
53    8753    1234    b, d
</code>```

I've tried using merge() to combine the two dataframes, but that doesn't work since I want to join on multiple columns in df_1 and just one column in df_2. I also tried creating empty columns in df_1 and filling them using if statements, but that got quite complicated.

Thanks!

答:
You could first stack and groupby+agg to form the new column, then merge with the original dataset:

```<code>s = df_2.set_index(['Code'])['Code Def']

df_1.merge(df_1.set_index('Age')
               .stack().map(s)
               .groupby(level='Age').agg(','.join)
               .rename('Code def'),
           left_on='Age', right_index=True
           )
</code>```

output:

```<code>   Age  Code 1  Code 2 Code def
0   42    1234  3857.0      d,c
1   35    3452     NaN        a
2   64    9583     NaN        e
3   53    8753  1234.0      b,d
</code>```

Body:
I have two dataframes, df_1 and df_2, where df_1 has several columns of "codes" and df_2 has the definitions for all of those codes:

df_1 = pd.DataFrame({
    'Age': [42, 35, 64, 53],
    'Code 1': [1234, 3452, 9583, 8753],
    'Code 2': [3857, np.nan, np.nan, 1234]})

df_2 = pd.DataFrame({
    'Code': [3452, 8753, 3857, 1234, 9583],
    'Code Def':['a', 'b', 'c', 'd', 'e']})

How do I create a new column in df_1 that contains the definitions of all the codes from df_2 to look something like this?

Age  Code 1  Code 2  Code def
42    1234    3857    d, c
35    3452    NaN      a
64    9583    NaN      e
53    8753    1234    b, d

I've tried using merge() to combine the two dataframes, but that doesn't work since I want to join on multiple columns in df_1 and just one column in df_2. I also tried creating empty columns in df_1 and filling them using if statements, but that got quite complicated.

Thanks!

Body:
You could first stack and groupby+agg to form the new column, then merge with the original dataset:

s = df_2.set_index(['Code'])['Code Def']

df_1.merge(df_1.set_index('Age')
               .stack().map(s)
               .groupby(level='Age').agg(','.join)
               .rename('Code def'),
           left_on='Age', right_index=True
           )

output:

   Age  Code 1  Code 2 Code def
0   42    1234  3857.0      d,c
1   35    3452     NaN        a
2   64    9583     NaN        e
3   53    8753  1234.0      b,d


问:
converting multiple list in dictionary and build dataframe to write a csv file
I'm trying to read multiple files, converting to a dictionary and then save it into a csv.
This is what I did, but I only keeps the last iteration of the files.
'''
list_keys = ["hostname", "linuxVersion", "ifconfig",
"listApplications", "nonJavaProcess", "javaProcess", "tomcatIfRunning",          "tomcatVersion"]
files = glob.glob('data/*', recursive=True)

```<code>new_data = []
for file in files:
    with open(file, 'r') as json_file:
        data = json_file.read()
        split_json = data.split('][')
        new_data.append(split_json)

dictionary = {}
final_dictionary = {}

for list in new_data:
    dictionary = dict(zip(list_keys, list))
        final_dictionary.update(dictionary)

dataframe = pandas.DataFrame(final_dictionary, index=[0], columns=list_keys)
dataframe.to_csv("relevamiento.csv", index=False)
</code>```

'''
The formating is OK in the CSV, but I only have the last file I read.

any ideas?
Thanks!!

答:
@stefan_aus_hannover I could solve the duplicate issue adding the following prior to save to csv file:

'''

```<code>final_dataframe = dataframe.drop_duplicates(subset="hostname")
final_dataframe.to_csv("relevamiento.csv", index=False)
</code>```

'''
Thank you very much for your help!!

Body:
I'm trying to read multiple files, converting to a dictionary and then save it into a csv.
This is what I did, but I only keeps the last iteration of the files.
'''
list_keys = ["hostname", "linuxVersion", "ifconfig",
"listApplications", "nonJavaProcess", "javaProcess", "tomcatIfRunning",          "tomcatVersion"]
files = glob.glob('data/*', recursive=True)

new_data = []
for file in files:
    with open(file, 'r') as json_file:
        data = json_file.read()
        split_json = data.split('][')
        new_data.append(split_json)

dictionary = {}
final_dictionary = {}

for list in new_data:
    dictionary = dict(zip(list_keys, list))
        final_dictionary.update(dictionary)

dataframe = pandas.DataFrame(final_dictionary, index=[0], columns=list_keys)
dataframe.to_csv("relevamiento.csv", index=False)

'''
The formating is OK in the CSV, but I only have the last file I read.

any ideas?
Thanks!!

Body:
@stefan_aus_hannover I could solve the duplicate issue adding the following prior to save to csv file:

'''

final_dataframe = dataframe.drop_duplicates(subset="hostname")
final_dataframe.to_csv("relevamiento.csv", index=False)

'''
Thank you very much for your help!!


问:
How can you redefine a POD type such that it is considered a distinct type while maintaining the semantics?
Imagine the following scenario where we have a pod container type that applies to many different scenarios:

```<code>struct vec2 {
  float x, y;
};
</code>```

Some of these scenarios might be storing a velocity, a position, an acceleration, etc. Now suppose we want to be able to handle all these scenarios independently while putting the type system to work and also maintaining the semantics of vec2, i.e. velocity.x, acceleration.y, etc.:

```<code>struct Simulation {
    template<typename T>
    static void handle() { fprintf( stdout, "Generic handler\n" ); }
};

template<>
void Simulation::handle<vec2>() { fprintf( stdout, "generic vec2 handler\n" ); }

template<>
void Simulation::handle<position>() { fprintf( stdout, "position handler\n" ); }

template<>
void Simulation::handle<velocity>() { fprintf( stdout, "velocity handler\n" ); }

template<>
void Simulation::handle<acceleration>() { fprintf( stdout, "acceleration handler\n" ); }
</code>```

In the above case using either typedef or using will not do the job as they do not affect the typeid of the alias as per the standard, so one cannot do:

```<code>using position = vec2;
</code>```

The next attempt might be to try and inherit from the pod, i.e.:

```<code>struct position : public vec2 {}
</code>```

however this has the disadvantage that new and delete are now broken as there is no virtual destructor on the pod type, and also the qualification of the position being a pod has been lost due to the inheritance.

Then it could be argued that simply copying and pasting the code for vec2 and renaming it to the desired type would satisfy all the requirement, but there are also a couple of issues with this:

Copy-Pasting code is bad*

In the example above vec2 has no associated operators or anything like that, but any useful vec2 class would most certainly have this and copying and pasting while renaming the data structure in this case would be pretty error prone especially if a fix is required in one of the operators

The vec2 could also be encapsulated in the new type:

```<code>struct position {
  vec2 pos;
};
</code>```

but this solution breaks the requirement for maintaining the semantics.

Another thing to note is that we might not have control over the implementation of vec2 (i.e. in the case where a library like GLM is used).

I feel that templating should provide the necessary solution, but can't work out how it would work. So the question is what is the correct way of going about redefining a type, while maintaining the semantics of the type, but ending up with a different type id?

*-not in all scenarios, but this one definitely

答:
Something along these lines, perhaps.

```<code>template <typename Tag>
struct vec2 {
  float x, y;
};

using position = vec2<struct PositionTag>;
using velocity = vec2<struct VelocityTag>;
</code>```

position and velocity would have similar behavior, but are distinct types.

Body:
Imagine the following scenario where we have a pod container type that applies to many different scenarios:

struct vec2 {
  float x, y;
};

Some of these scenarios might be storing a velocity, a position, an acceleration, etc. Now suppose we want to be able to handle all these scenarios independently while putting the type system to work and also maintaining the semantics of vec2, i.e. velocity.x, acceleration.y, etc.:

struct Simulation {
    template<typename T>
    static void handle() { fprintf( stdout, "Generic handler\n" ); }
};

template<>
void Simulation::handle<vec2>() { fprintf( stdout, "generic vec2 handler\n" ); }

template<>
void Simulation::handle<position>() { fprintf( stdout, "position handler\n" ); }

template<>
void Simulation::handle<velocity>() { fprintf( stdout, "velocity handler\n" ); }

template<>
void Simulation::handle<acceleration>() { fprintf( stdout, "acceleration handler\n" ); }

In the above case using either typedef or using will not do the job as they do not affect the typeid of the alias as per the standard, so one cannot do:

using position = vec2;

The next attempt might be to try and inherit from the pod, i.e.:

struct position : public vec2 {}

however this has the disadvantage that new and delete are now broken as there is no virtual destructor on the pod type, and also the qualification of the position being a pod has been lost due to the inheritance.

Then it could be argued that simply copying and pasting the code for vec2 and renaming it to the desired type would satisfy all the requirement, but there are also a couple of issues with this:

Copy-Pasting code is bad*

In the example above vec2 has no associated operators or anything like that, but any useful vec2 class would most certainly have this and copying and pasting while renaming the data structure in this case would be pretty error prone especially if a fix is required in one of the operators

The vec2 could also be encapsulated in the new type:

struct position {
  vec2 pos;
};

but this solution breaks the requirement for maintaining the semantics.

Another thing to note is that we might not have control over the implementation of vec2 (i.e. in the case where a library like GLM is used).

I feel that templating should provide the necessary solution, but can't work out how it would work. So the question is what is the correct way of going about redefining a type, while maintaining the semantics of the type, but ending up with a different type id?

*-not in all scenarios, but this one definitely

Body:
Something along these lines, perhaps.

template <typename Tag>
struct vec2 {
  float x, y;
};

using position = vec2<struct PositionTag>;
using velocity = vec2<struct VelocityTag>;

position and velocity would have similar behavior, but are distinct types.


问:
JPQL query that give me the highest value
I'm trying to do a JPQL query that give me the highest PK of the PKs in my table (https://drive.google.com/file/d/1_kaklkKdCbhT0-byqCtz6HgfluKKp8J-/view?usp=sharing). Here is my query :

```<code>@Override
public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
    int nb = 1;
    try {
        String jpql = "SELECT max(e) FROM " + cl.getSimpleName() + " e";
        Query query = em.createQuery(jpql);
        nb = (int) query.getSingleResult();
    } catch (Exception ex) {
        throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
    }
    return nb;
}
</code>```

The error says that the syntax of my query is wrong. Can someone please help me ? Thank you for your help :)

答:
Thank you for your comments ! It allowed me to solve my problem. I've indeed needed to get the int ID property of my entity class. Here is my function :</p>
```<code>@Override
    public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
        int nb = 1;
        try {
            String jpql = "SELECT max(e." + nomPkElement + ") FROM " + cl.getSimpleName() + " e";
            Query query = em.createQuery(jpql);
            nb = (int) query.getSingleResult();
        } catch (Exception ex) {
            throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
        }
        return nb;
    }
</code>```

Body:
I'm trying to do a JPQL query that give me the highest PK of the PKs in my table (https://drive.google.com/file/d/1_kaklkKdCbhT0-byqCtz6HgfluKKp8J-/view?usp=sharing). Here is my query :

@Override
public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
    int nb = 1;
    try {
        String jpql = "SELECT max(e) FROM " + cl.getSimpleName() + " e";
        Query query = em.createQuery(jpql);
        nb = (int) query.getSingleResult();
    } catch (Exception ex) {
        throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
    }
    return nb;
}

The error says that the syntax of my query is wrong. Can someone please help me ? Thank you for your help :)

Body:
Thank you for your comments ! It allowed me to solve my problem. I've indeed needed to get the int ID property of my entity class. Here is my function :

@Override
    public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
        int nb = 1;
        try {
            String jpql = "SELECT max(e." + nomPkElement + ") FROM " + cl.getSimpleName() + " e";
            Query query = em.createQuery(jpql);
            nb = (int) query.getSingleResult();
        } catch (Exception ex) {
            throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
        }
        return nb;
    }


问:
jQuery how to check if uploaded file is an image without checking extensions?
Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validator but to no avail... This is a snippet from my current code:

```<code><input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />
</code>```

Script:

```<code>App.Dispatcher.on("uploadpic", function() {
        $(":file").change(function() {
            if (this.files && this.files[0] && this.files[0].name.match(/\.(jpg|jpeg|png|gif)$/) ) {
                if(this.files[0].size>1048576) {
                    alert('File size is larger than 1MB!');
                }
                else {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;
                    reader.readAsDataURL(this.files[0]);
                }
            } else alert('This is not an image file!');
        });
        function imageIsLoaded(e) {
            result = e.target.result;
            $('#image').attr('src', result);
        };
    });
</code>```

It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!

答:
Using jQuery version 3.3.1:

<!DOCTYPE html>

  <title>Page Title</title>

  Select Image

  <input type="file" class="custom-file-input" id="customFile">

```

Body:
Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validator but to no avail... This is a snippet from my current code:

<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />

Script:

App.Dispatcher.on("uploadpic", function() {
        $(":file").change(function() {
            if (this.files && this.files[0] && this.files[0].name.match(/\.(jpg|jpeg|png|gif)$/) ) {
                if(this.files[0].size>1048576) {
                    alert('File size is larger than 1MB!');
                }
                else {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;
                    reader.readAsDataURL(this.files[0]);
                }
            } else alert('This is not an image file!');
        });
        function imageIsLoaded(e) {
            result = e.target.result;
            $('#image').attr('src', result);
        };
    });

It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!

Body:
Using jQuery version 3.3.1:

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <label class="custom-file-label" for="customFile">Select Image</label>
  <br>
  <input type="file" class="custom-file-input" id="customFile">
</body>

<script>
  $(document).ready(function() {
    $(document).on("change", ".custom-file-input", function() {
      var myImg = this.files[0];
      var myImgType = myImg["type"];
      var validImgTypes = ["image/gif", "image/jpeg", "image/png"];

      if ($.inArray(myImgType, validImgTypes) < 0) {
        alert("Not an image")
      } else {
        alert("Is an image")
      }

    });
  });
</script>

</html>


问:
How might I store in a variable the string read by fgets() without leaking memory?
I want the following code to accomplish to store the content of the file it reads in a variable
content without leaking memory:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1);
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1);
    return result;
}

int main() {

char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"r");
char line[200];
char * content = "";

if (archivo == NULL)
        exit(1);
else {

fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
        printf("\nThe content of %s is:\n", path);
        while (feof(archivo) == 0) {
        fgets(line, 200, archivo); //reads one line at a time - comment out the while loop to find out
        content = concat(content, line);
       //free(content);//No leaks but no content either
            }
          }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
      fclose(archivo);
      exit(0);
        }
      }
fclose(archivo);
puts(content);
free(content);
return 0;
}
</code>```

much the same as this code that uses fread() does it:

```<code>#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <sys/types.h>

int main() {

int count;
char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"rb");

 if (archivo == NULL) {
     puts("Does not exist.");
     exit(1);
       }
 else {

  fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  char contenido[sz];
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
    count = fread(&contenido, 10 * sizeof(char), sz, archivo);//reads 10 characters at a time.
    }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
        }
  fclose(archivo);
  // Printing data to check validity
  printf("Data read from file: %s \n", contenido);
  printf("Elements read: %i, read %li byte at a time.\n", count, 10 * sizeof(char));

 }
return 0;
}
</code>```

The first code snippet leaks memory, as evidenced by valgrind:

```<code>...
total heap usage: 44 allocs, 4 frees, 23,614 bytes allocated
...
==404853== LEAK SUMMARY:
==404853==    definitely lost: 17,198 bytes in 40 blocks
...
</code>```

When I attempt to prevent such leak by executing free() within the while loop I get no value stored in content. How might I store the string read by fgets without leaking memory?

答:
When you call concat the second time, the value from the first call is overwritten by the malloc call. That is the memory leak.

I presume that you want content to be one long string that contains the data from all lines.

You want to use realloc (vs. malloc) in concat and just append s2 to the enlarged s1.

With this modified scheme, instead of char *content = "";, you want: char *content = NULL;

Also, don't use feof

And, ftell returns long and not int. And, it's better to not use pow to compare against the limit.

Here is the refactored code (I've compiled it but not tested it):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

char *
concat(char *s1, const char *s2)
{
    size_t len1;
    size_t len2;

    if (s1 != NULL)
        len1 = strlen(s1);
    else
        len1 = 0;

    len2 = strlen(s2);

    s1 = realloc(s1,len1 + len2 + 1);
    if (s1 == NULL) {
        perror("realloc");
        exit(1);
    }

    memcpy(s1 + len1, s2, len2 + 1);

    return s1;
}

int
main(void)
{

    char path[] = "/home/jim/trackers_best.txt";
    FILE *archivo = fopen(path, "r");
    char line[200];
#if 0
    char *content = "";
#else
    char *content = NULL;
#endif

    if (archivo == NULL)
        exit(1);

    fseek(archivo, 0L, SEEK_END);
    long sz = ftell(archivo);
    fseek(archivo, 0L, SEEK_SET);

    if (sz < (10 * 1024 * 1024)) {
        printf("\nThe content of %s is:\n", path);

        while (fgets(line, sizeof(line), archivo) != NULL)
            content = concat(content, line);
    }
    else {
        puts("File take up more than 10 MBs, I refuse to read it.");
        fclose(archivo);
        exit(0);
    }

    fclose(archivo);

    if (content != NULL)
        puts(content);

    free(content);

    return 0;
}
</code>```

Body:
I want the following code to accomplish to store the content of the file it reads in a variable
content without leaking memory:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1);
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1);
    return result;
}

int main() {

char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"r");
char line[200];
char * content = "";

if (archivo == NULL)
        exit(1);
else {

fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
        printf("\nThe content of %s is:\n", path);
        while (feof(archivo) == 0) {
        fgets(line, 200, archivo); //reads one line at a time - comment out the while loop to find out
        content = concat(content, line);
       //free(content);//No leaks but no content either
            }
          }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
      fclose(archivo);
      exit(0);
        }
      }
fclose(archivo);
puts(content);
free(content);
return 0;
}

much the same as this code that uses fread() does it:

#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <sys/types.h>

int main() {

int count;
char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"rb");

 if (archivo == NULL) {
     puts("Does not exist.");
     exit(1);
       }
 else {

  fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  char contenido[sz];
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
    count = fread(&contenido, 10 * sizeof(char), sz, archivo);//reads 10 characters at a time.
    }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
        }
  fclose(archivo);
  // Printing data to check validity
  printf("Data read from file: %s \n", contenido);
  printf("Elements read: %i, read %li byte at a time.\n", count, 10 * sizeof(char));

 }
return 0;
}

The first code snippet leaks memory, as evidenced by valgrind:

...
total heap usage: 44 allocs, 4 frees, 23,614 bytes allocated
...
==404853== LEAK SUMMARY:
==404853==    definitely lost: 17,198 bytes in 40 blocks
...

When I attempt to prevent such leak by executing free() within the while loop I get no value stored in content. How might I store the string read by fgets without leaking memory?

Body:
When you call concat the second time, the value from the first call is overwritten by the malloc call. That is the memory leak.

I presume that you want content to be one long string that contains the data from all lines.

You want to use realloc (vs. malloc) in concat and just append s2 to the enlarged s1.

With this modified scheme, instead of char *content = "";, you want: char *content = NULL;

Also, don't use feof

And, ftell returns long and not int. And, it's better to not use pow to compare against the limit.

Here is the refactored code (I've compiled it but not tested it):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

char *
concat(char *s1, const char *s2)
{
    size_t len1;
    size_t len2;

    if (s1 != NULL)
        len1 = strlen(s1);
    else
        len1 = 0;

    len2 = strlen(s2);

    s1 = realloc(s1,len1 + len2 + 1);
    if (s1 == NULL) {
        perror("realloc");
        exit(1);
    }

    memcpy(s1 + len1, s2, len2 + 1);

    return s1;
}

int
main(void)
{

    char path[] = "/home/jim/trackers_best.txt";
    FILE *archivo = fopen(path, "r");
    char line[200];
#if 0
    char *content = "";
#else
    char *content = NULL;
#endif

    if (archivo == NULL)
        exit(1);

    fseek(archivo, 0L, SEEK_END);
    long sz = ftell(archivo);
    fseek(archivo, 0L, SEEK_SET);

    if (sz < (10 * 1024 * 1024)) {
        printf("\nThe content of %s is:\n", path);

        while (fgets(line, sizeof(line), archivo) != NULL)
            content = concat(content, line);
    }
    else {
        puts("File take up more than 10 MBs, I refuse to read it.");
        fclose(archivo);
        exit(0);
    }

    fclose(archivo);

    if (content != NULL)
        puts(content);

    free(content);

    return 0;
}


问:
Cant find “Manage In-App purchases” under itunes connect
I know i am going to ask something that might sound bit odd, but still asking

I am developing an application that has In App Purchase functionality, i have integrated the code but for testing i need to make a test account under iTunes connect. During R&D i came to know that i have to go through following way to make test account for in app purchase:

iTunes Connect-> “Manage In-App purchases”

My problem is that i am not able to see the option “Manage In-App purchases” under iTunes connect. Any kind of input to this question would be great help.

Thanks in Advance

答: Now it stays on the details of the app. Access iTunesConnect and select a app. The 'Manage In App Purchase' will be in the right-top menu.</p>

ContentLicense: CC BY-SA 2.5


答:
You can define vec2 as a template class and use an enum flag to represent its storage type.

```<code>enum class data_type {
  position, velocity, acceleration
};

template<data_type>
struct vec2 {
  float x, y;
};

vec2<data_type::position> p;
vec2<data_type::velocity> v;
vec2<data_type::acceleration> a;
</code>```

Title: How can you redefine a POD type such that it is considered a distinct type while maintaining the semantics?

Body:
You can define vec2 as a template class and use an enum flag to represent its storage type.

enum class data_type {
  position, velocity, acceleration
};

template<data_type>
struct vec2 {
  float x, y;
};

vec2<data_type::position> p;
vec2<data_type::velocity> v;
vec2<data_type::acceleration> a;


答:
You could map the result of the nested multiplying.

const
    multiply = (a, b) => a * b,
    array = [[1, 2, 3], [3, 4], [7, 8, 9]],
    result = array.map(a => a.reduce(multiply, 1));

console.log(result);```

Title: Javascript Multiplying Within an Array

Body:
I have an array with multiple arrays inside.  I would like to multiply the contents of each array.

Here is my code--currently not getting anything in console.
The desired output is 3 numbers-- the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}


问:
add 1 to c++ bitset
I have a c++ bitset of given length. I want to generate all possible combinations of this bitset for which I thought of adding 1 2^bitset.length times. How to do this? Boost library solution is also acceptable</p>

答:
Not best, but brute force way, but you can add 1 by converting using to_ulong()

bitset<32> b (13);
b = b.to_ulong() + 1;
```

Title: add 1 to c++ bitset


问:
Dynamic CSS for 2 columns
Is there a way to create a dynamic CSS for 2 columns? What I mean is, there are 2 columns in my webpage, the left and right column. It is similar to Facebook, where the profile picture is the left column and the right column is where your feeds are located. When a link is selected from the left column, without refreshing the page, the right column will display the page automatically. The left column is where my links are located and it is fixed. The only change factor is my right column. How can I create and apply the CSS?</p>

答:
There are css3 columns but they are not supported by IE. What a surprise!

It sounds more like you just need a css layout framework. Search for css frameworks / templates.
I of course recommend simpl.css.

The page is ugly at the moment but will be updated soon.

Title: Dynamic CSS for 2 columns


问:
How to get sentiment (pos/neg/neu) for each topic in each review? after getting topics from LDA?
Imagine I have a reviews from Amazon.
I will pass those reviews into LDA model to get 4 topics.

Now each review might talk about more than 1 topic. It might contain 2/3/4 topic words. So Now is there any way where I could extract sentiments from those reviews for each topic

This is how I am expecting the function to be

```<code>def assign_topics_to_sentences(topics_dict,review):

   return sentences_topic_dict

#topics_dict is a dictionary that contains keys as topic number or name and values contain list like  {'topic1':[(word1,porb)(word2,prob)........],'topic2':[[(word1,porb)(word2,prob)........],.....}

#sentence_topic_dict {'topic1':(sentiment,score),'topic2':(sentiment,score)...}
</code>```

Actually my main task is to get topic wise sentiment label(positive,negative,neutral for each topic for each review. If a user in a particular review doesn't talk about certain topic then its sentiment will be neutral

```<code>
       Topic_0          Topic_1               Topic_2       Topic_3         Reviews
0   (positive, 0.4404)  (positive, 0.9612)  (neutral, 0.0)  (neutral, 0.0)  george super friendly easy going apartment gre...
1   (positive, 0.7269)  (positive, 0.9648)  (neutral, 0.0)  (neutral, 0.0)  wonderful love love love location place george...
2   (positive, 0.3182)  (positive, 0.9459)  (neutral, 0.0)  (positive, 0.4215)  brilliant time visit apartment huge great view...
3   (neutral, 0.0)      (positive, 0.9517)  (neutral, 0.0516)(neutral, 0.0)    martin great host although apartment building ...
4   (positive, 0.6705)  (positive, 0.7845)  (neutral, 0.1531)   (positive, 0.34)    would love leaving review apartment unfortunat...
5   (neutral, 0.0)  (positive, 0.946)   (positive, 0.2755)  (neutral, 0.0)  george one colleague meet location not difficu..
</code>```

I want something like this for all reviews. If we could get a function for 1 review which I mentioned above we could replicate it to entire reviews .

答: Regardless of the topics, you can have sentiment of each of your sentences using one of the many tools for sentiment analysis, then proceed with assigning each sentence, a topic. Finally, put these two together.</p>

Body:
Imagine I have a reviews from Amazon.
I will pass those reviews into LDA model to get 4 topics.

Now each review might talk about more than 1 topic. It might contain 2/3/4 topic words. So Now is there any way where I could extract sentiments from those reviews for each topic

This is how I am expecting the function to be

def assign_topics_to_sentences(topics_dict,review):

   return sentences_topic_dict

#topics_dict is a dictionary that contains keys as topic number or name and values contain list like  {'topic1':[(word1,porb)(word2,prob)........],'topic2':[[(word1,porb)(word2,prob)........],.....}

#sentence_topic_dict {'topic1':(sentiment,score),'topic2':(sentiment,score)...}

Actually my main task is to get topic wise sentiment label(positive,negative,neutral for each topic for each review. If a user in a particular review doesn't talk about certain topic then its sentiment will be neutral

       Topic_0          Topic_1               Topic_2       Topic_3         Reviews
0   (positive, 0.4404)  (positive, 0.9612)  (neutral, 0.0)  (neutral, 0.0)  george super friendly easy going apartment gre...
1   (positive, 0.7269)  (positive, 0.9648)  (neutral, 0.0)  (neutral, 0.0)  wonderful love love love location place george...
2   (positive, 0.3182)  (positive, 0.9459)  (neutral, 0.0)  (positive, 0.4215)  brilliant time visit apartment huge great view...
3   (neutral, 0.0)      (positive, 0.9517)  (neutral, 0.0516)(neutral, 0.0)    martin great host although apartment building ...
4   (positive, 0.6705)  (positive, 0.7845)  (neutral, 0.1531)   (positive, 0.34)    would love leaving review apartment unfortunat...
5   (neutral, 0.0)  (positive, 0.946)   (positive, 0.2755)  (neutral, 0.0)  george one colleague meet location not difficu..

I want something like this for all reviews. If we could get a function for 1 review which I mentioned above we could replicate it to entire reviews .


问:
Execute multiline bash command from Python and get its output
I am under Python 3.8.10 in Ubuntu 20.04 trying to execute a multiline bash command and get its output. For this I am trying to combine this and this. My bash command is this:

/home/foo/.drsosc/drs-5.0.6/drscl << ASD
info
exit
ASD
```
<p>and it works as I want. Now in Python I have this:</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
import subprocess

PATH_TO_drscl = Path.home()/Path('.drsosc/drs-5.0.6/drscl')

def send_command(cmd: str):
    execute_this = f'''{PATH_TO_drscl} << ASD
{cmd}
exit
ASD'''
    return subprocess.run([execute_this], stdout=subprocess.PIPE)

print(send_command('info'))
</code>```

but I get

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.drsosc/drs-5.0.6/drscl << ASD\ninfo\nexit\nASD'
</code>```

It seems that the problem is with the '\n' not being properly interpreted?

答:
No, the problem is that you're trying to run small shell script but
you're calling an executable that has a name composed of all commands
in the script. Try with shell=True:

```<code>return subprocess.run([execute_this], stdout=subprocess.PIPE, shell=True)
</code>```

Body:
I am under Python 3.8.10 in Ubuntu 20.04 trying to execute a multiline bash command and get its output. For this I am trying to combine this and this. My bash command is this:

/home/foo/.drsosc/drs-5.0.6/drscl << ASD
info
exit
ASD

and it works as I want. Now in Python I have this:

from pathlib import Path
import subprocess

PATH_TO_drscl = Path.home()/Path('.drsosc/drs-5.0.6/drscl')

def send_command(cmd: str):
    execute_this = f'''{PATH_TO_drscl} << ASD
{cmd}
exit
ASD'''
    return subprocess.run([execute_this], stdout=subprocess.PIPE)

print(send_command('info'))

but I get

FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.drsosc/drs-5.0.6/drscl << ASD\ninfo\nexit\nASD'

It seems that the problem is with the '\n' not being properly interpreted?

Body:
No, the problem is that you're trying to run small shell script but
you're calling an executable that has a name composed of all commands
in the script. Try with shell=True:

return subprocess.run([execute_this], stdout=subprocess.PIPE, shell=True)


问:
Create a list of combinations recursively
I am trying to implement a combination method using recursion. I have already done it using a for loop but want to approach it via recursion.

The method gets two inputs and creates all possible combinations. It is supposed to store the combination in an instance variable that I have called "combination". I tried different codes but they don't work properly. I think recursive back-tracking is the best way to approach this.

For example, object.pe1.combination(4,3) would create something like this:
image of combination list

```<code>
    // Instance variable needed for this problem
    ArrayList<Integer[]> combination;
    private int size;

    // To calculate all the possible combinations
    private int factorial(int x){
        if (x == 0) {
            return 1;
        }
        else {
            return x * factorial(x - 1);
        }
    }

    void combination(int n, int r) {

        // formula for calculating the combination of r items selected among n: n! / (r! * (n - r)!)
        int noc = factorial (n) / (factorial (r) * factorial (n - r)); // number of combinations

        this.combination = new ArrayList<Integer[]>(noc); // 2D array. Each slot stores a combination

        if (noc == 0) {

        }
        else {
            this.combination = new ArrayList<Integer[]>(noc);
            int[] arr = new int[n];
            int[] temparr = new int[r];
            arr = createCombination(temparr, 0, r);
        }
    }

        private int[] createCombination(int[] temparr, int index, int r) {
        // this is where I am stuck
        temparr[0] = index;

        if (temparr[r] == 0) {
            temparr = new int[r - 1];
            temparr = createCombination(temparr, index + 1, r - 1);
        }

        else {
            return temparr;
        }
    }

</code>```

答:
A recursive implementation of any algorithm is comprised of two parts:

base case - a condition that terminates a branch of recursive calls and represents an edge case for which result is known in advance;

recursive case - a part where the logic resides and the recursive calls are made.

For this task a base case will be a situation when size of the combination equals to a target size (denoted as r in your code, in the code below I gave it a name targetSize).

Explanation of the recursive logic:

Every method call tracks its own combination;

Every combination unless it reaches the targetSize is used as a blue-print for other combinations;

Each item from the source of data can be used only once, hence when it's being added to a combination it must be removed from the source.

The type ArrayList<Integer[]> which you are using to store the combination isn't a good choice. Arrays and generics do not play well together. List<List<Integer>> will be more appropriate for this purpose.

Also in my code List is used as a source of data instead of an array, which isn't a complicated conversion and can be achieved easily.

Pay attention to the comments in the code.

```<code>    private List<List<Integer>> createCombination(List<Integer> source, List<Integer> comb, int targetSize) {
        if (comb.size() == targetSize) { // base condition of the recursion
            List<List<Integer>> result = new ArrayList<>();
            result.add(comb);
            return result;
        }

        List<List<Integer>> result = new ArrayList<>();
        Iterator<Integer> iterator = source.iterator();
        while (iterator.hasNext()) {
            // taking an element from a source
            Integer item = iterator.next();
            iterator.remove(); // in order not to get repeated the element has to be removed

            // creating a new combination using existing as a base
            List<Integer> newComb = new ArrayList<>(comb);
            newComb.add(item); // adding the element that was removed from the source
            result.addAll(createCombination(new ArrayList<>(source), newComb, targetSize)); // adding all the combinations generated
        }
        return result;
    }
</code>```

For the input

```<code>    createCombination(new ArrayList<>(List.of(1, 2, 3)), new ArrayList<>(), 2));
</code>```

It'll produce the output

```<code>[[1, 2], [1, 3], [2, 3]]
</code>```

Body:
I am trying to implement a combination method using recursion. I have already done it using a for loop but want to approach it via recursion.

The method gets two inputs and creates all possible combinations. It is supposed to store the combination in an instance variable that I have called "combination". I tried different codes but they don't work properly. I think recursive back-tracking is the best way to approach this.

For example, object.pe1.combination(4,3) would create something like this:
image of combination list

    // Instance variable needed for this problem
    ArrayList<Integer[]> combination;
    private int size;

    // To calculate all the possible combinations
    private int factorial(int x){
        if (x == 0) {
            return 1;
        }
        else {
            return x * factorial(x - 1);
        }
    }

    void combination(int n, int r) {

        // formula for calculating the combination of r items selected among n: n! / (r! * (n - r)!)
        int noc = factorial (n) / (factorial (r) * factorial (n - r)); // number of combinations

        this.combination = new ArrayList<Integer[]>(noc); // 2D array. Each slot stores a combination

        if (noc == 0) {

        }
        else {
            this.combination = new ArrayList<Integer[]>(noc);
            int[] arr = new int[n];
            int[] temparr = new int[r];
            arr = createCombination(temparr, 0, r);
        }
    }

        private int[] createCombination(int[] temparr, int index, int r) {
        // this is where I am stuck
        temparr[0] = index;

        if (temparr[r] == 0) {
            temparr = new int[r - 1];
            temparr = createCombination(temparr, index + 1, r - 1);
        }

        else {
            return temparr;
        }
    }

Body:
A recursive implementation of any algorithm is comprised of two parts:

base case - a condition that terminates a branch of recursive calls and represents an edge case for which result is known in advance;

recursive case - a part where the logic resides and the recursive calls are made.

For this task a base case will be a situation when size of the combination equals to a target size (denoted as r in your code, in the code below I gave it a name targetSize).

Explanation of the recursive logic:

Every method call tracks its own combination;

Every combination unless it reaches the targetSize is used as a blue-print for other combinations;

Each item from the source of data can be used only once, hence when it's being added to a combination it must be removed from the source.

The type ArrayList<Integer[]> which you are using to store the combination isn't a good choice. Arrays and generics do not play well together. List<List<Integer>> will be more appropriate for this purpose.

Also in my code List is used as a source of data instead of an array, which isn't a complicated conversion and can be achieved easily.

Pay attention to the comments in the code.

    private List<List<Integer>> createCombination(List<Integer> source, List<Integer> comb, int targetSize) {
        if (comb.size() == targetSize) { // base condition of the recursion
            List<List<Integer>> result = new ArrayList<>();
            result.add(comb);
            return result;
        }

        List<List<Integer>> result = new ArrayList<>();
        Iterator<Integer> iterator = source.iterator();
        while (iterator.hasNext()) {
            // taking an element from a source
            Integer item = iterator.next();
            iterator.remove(); // in order not to get repeated the element has to be removed

            // creating a new combination using existing as a base
            List<Integer> newComb = new ArrayList<>(comb);
            newComb.add(item); // adding the element that was removed from the source
            result.addAll(createCombination(new ArrayList<>(source), newComb, targetSize)); // adding all the combinations generated
        }
        return result;
    }

For the input

    createCombination(new ArrayList<>(List.of(1, 2, 3)), new ArrayList<>(), 2));

It'll produce the output

[[1, 2], [1, 3], [2, 3]]


问:
Location Background - Network Connection
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here</p>

```<code>    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager
       didUpdateToLocationCLLocation *)newLocation
       fromLocationCLLocation *)oldLocation
     {

      NSLog(@"Location Change");
     }
     This Method Call Only Once.
</code>```

答: In order to run location services in the background, you need to modify your plist such that the UIBackgroundModes key contains location.</p>

Body:
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here

    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager
       didUpdateToLocationCLLocation *)newLocation
       fromLocationCLLocation *)oldLocation
     {

      NSLog(@"Location Change");
     }
     This Method Call Only Once.


问:
Identify the text type in NASM
My purpose is to create a program in NASM, where one of its functions needs to know what type of data is being used, (string, decimal, hexadecimal, etc). But I don't know very well how to do it without it taking up a lot of lines of code. Someone could help me, please. Thank you.</p>

答:
Don’t trust user input.
Your algorithm must positively confirm supplied data is indeed a numeric string.

Once you’ve determined the type, you can select and call one of three (sub‑)functions foo_decimal, foo_hexadecimal, foo_string.
This is how compilers for high-level languages (can) implement (static) function overloading.

A struc with a data type prefix like Mario August suggested is definitely nice to have if you are processing the same data multiple times.
Your functions will still need to have some kind of branching though.

Title: Identify the text type in NASM


问:
Detecting HTTP redirects
I have a problem with a website called www.webhallen.com. I want to put any numbers and character after www.webhallen.com/ for example www.webhallen.com/3459gdfg. I then want to se if that website exist the problem is that the site rederect me to there own 404 page. How can I via requests see if they redirect me?</p>

答: You can check for the response status code. If you get response.status_code as 404. You will have been redirected to there 404 site.

Title: Detecting HTTP redirects


问:
How to stop printing items in a list when the counter is reached
I am trying to run a loop that prints lines of lyrics in a list, then stops when it hits the variable limit amount. Though i've tried it two ways with two different outcomes, neither are correct.

The problem I was given:

```<code>lyrics = ["I wanna be your endgame", "I wanna be your first string",
          "I wanna be your A-Team", "I wanna be your endgame, endgame"]
lines_of_sanity = 6

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#Recall the Earworm problem (3.3.5 Coding Exercise 2). The
#first time, you would still finish printing the entire list
#of lyrics after lines_of_sanity was exceeded.
#
#Revise that code so that you always stop when lines_of_sanity
#is reached. If lines_of_sanity is 6, you would print 6 lines,
#no matter how many lines are in the list. If there are fewer
#than 6 lines in the list, then you'd repeat the list until
#the number of lines is reached.
#
#For example, with the values above, you'd print:
#I wanna be your endgame
#I wanna be your first string
#I wanna be your A-Team
#I wanna be your endgame, endgame
#I wanna be your endgame
#I wanna be your first string
#MAKE IT STOP
#
#That's 6 lines: the entire list once, then the first two lines
#again to reach 6. As before, print MAKE IT STOP when you're
#done.
#
#HINT: There are multiple ways to do this: some involve a small
#change to our earlier answer, others involve a more wholesale
#rewrite. If you're stuck on one, try to think of a totally
#different way!

#Add your code here! Using the initial inputs from above, this
#should print 7 lines: all 4 lines of the list, then the first
#two lines again, then MAKE IT STOP
</code>```

My answers and what they produce:

```<code>counter = 0
while counter <= lines_of_sanity:
    for item in (lyrics):
        print(item)
        counter += len(lyrics)
print("MAKE IT STOP")
</code>```

We tested your code with lyrics = ["I wanna be your endgame", "I wanna
be your first string", "I wanna be your A-Team", "I wanna be your
endgame, endgame"], lines_of_sanity = 6. We expected your code to
print this:

I wanna be your endgame I wanna be your first string I wanna be your
A-Team I wanna be your endgame, endgame I wanna be your endgame I
wanna be your first string MAKE IT STOP

However, it printed this:

I wanna be your endgame I wanna be your first string I wanna be your
A-Team I wanna be your endgame, endgame MAKE IT STOP

On this one it seems it's just printing one less line than lines_of_sanity

or my first attempt was:

```<code>counter = 0
while counter <= lines_of_sanity:
    for item in (lyrics):
        print(item)
        counter += 1
print("MAKE IT STOP")
</code>```

Which seems to print every item in the list twice (till lines_of_sanity is exceeded) which gives me 8 lines

答:
```<code>      lyrics = ["I wanna be your endgame", "I wanna be your first string",
      "I wanna be your A-Team", "I wanna be your endgame, endgame"]
      lines_of_sanity = 2

      `while lines_of_sanity > len(lyrics):
           for i in lyrics:
               print(i)
           lines_of_sanity -= len(lyrics)

      for i in range(len(lyrics)):
         print(lyrics[i])

      print("MAKE IT STOP")
</code>```
<p>`</p>

Body:
I am trying to run a loop that prints lines of lyrics in a list, then stops when it hits the variable limit amount. Though i've tried it two ways with two different outcomes, neither are correct.

The problem I was given:

lyrics = ["I wanna be your endgame", "I wanna be your first string",
          "I wanna be your A-Team", "I wanna be your endgame, endgame"]
lines_of_sanity = 6

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#Recall the Earworm problem (3.3.5 Coding Exercise 2). The
#first time, you would still finish printing the entire list
#of lyrics after lines_of_sanity was exceeded.
#
#Revise that code so that you always stop when lines_of_sanity
#is reached. If lines_of_sanity is 6, you would print 6 lines,
#no matter how many lines are in the list. If there are fewer
#than 6 lines in the list, then you'd repeat the list until
#the number of lines is reached.
#
#For example, with the values above, you'd print:
#I wanna be your endgame
#I wanna be your first string
#I wanna be your A-Team
#I wanna be your endgame, endgame
#I wanna be your endgame
#I wanna be your first string
#MAKE IT STOP
#
#That's 6 lines: the entire list once, then the first two lines
#again to reach 6. As before, print MAKE IT STOP when you're
#done.
#
#HINT: There are multiple ways to do this: some involve a small
#change to our earlier answer, others involve a more wholesale
#rewrite. If you're stuck on one, try to think of a totally
#different way!

#Add your code here! Using the initial inputs from above, this
#should print 7 lines: all 4 lines of the list, then the first
#two lines again, then MAKE IT STOP

My answers and what they produce:

counter = 0
while counter <= lines_of_sanity:
    for item in (lyrics):
        print(item)
        counter += len(lyrics)
print("MAKE IT STOP")

We tested your code with lyrics = ["I wanna be your endgame", "I wanna
be your first string", "I wanna be your A-Team", "I wanna be your
endgame, endgame"], lines_of_sanity = 6. We expected your code to
print this:

I wanna be your endgame I wanna be your first string I wanna be your
A-Team I wanna be your endgame, endgame I wanna be your endgame I
wanna be your first string MAKE IT STOP

However, it printed this:

I wanna be your endgame I wanna be your first string I wanna be your
A-Team I wanna be your endgame, endgame MAKE IT STOP

On this one it seems it's just printing one less line than lines_of_sanity

or my first attempt was:

counter = 0
while counter <= lines_of_sanity:
    for item in (lyrics):
        print(item)
        counter += 1
print("MAKE IT STOP")

Which seems to print every item in the list twice (till lines_of_sanity is exceeded) which gives me 8 lines

Body:
      lyrics = ["I wanna be your endgame", "I wanna be your first string",
      "I wanna be your A-Team", "I wanna be your endgame, endgame"]
      lines_of_sanity = 2

      `while lines_of_sanity > len(lyrics):
           for i in lyrics:
               print(i)
           lines_of_sanity -= len(lyrics)

      for i in range(len(lyrics)):
         print(lyrics[i])

      print("MAKE IT STOP")

`