问:
Pygame: How to make two objects stop moving once they collide
I'm attempting to make a simulation by generating particles (mainly circles) in pygame. One objective is to have the particle move randomly on the screen and once they collide, they should stick to each other and stay in their fixed position. I created a class called Particle which takes the following attributes: Particles(pos_x, pos_y, size, colour, screen). Then I generate a list of these particles on the screen so that they move randomly. However, I'm having a hard time conceptualizing how to loop through every particle and check if the distance between their respective x coordinates is less than 2*radius. (Example: if the radius of a particle is 5pixels, then particle_a(4, 8) would collide with particle_b(6, 8).

How would I go about checking each particle to see if they collide with each other? looping through a list of particles and then checking with a copy of that list but I'm not sure I'm going about this the right way. I can use all the help I can get. I'm still a beginner so I'd appreciate any help.

import sys
import pygame
import random
from dla_settings import Settings
from particles import Particles

PARTICLE_SIZE = 5
PARTICLE_COLOUR = (random.choice((200, 240)), 100, 0)

def dla_simulation():
    dla_settings = Settings()
    pygame.init()
    screen = pygame.display.set_mode((dla_settings.screen_width, dla_settings.screen_height))
    pygame.display.set_caption("DLA")

    screen.fill((10, 10, 10))
    pygame.display.update()

    main_particle = Particles(dla_settings.screen_width // 2,
                                dla_settings.screen_height // 2,
                                PARTICLE_SIZE,
                                PARTICLE_COLOUR,
                                screen)

    particles = []

    for particle in range(20):
        x = random.randint(400, 500)
        y = random.randint(400, 500)
        particle = Particles(x,
                                y,
                                PARTICLE_SIZE,
                                PARTICLE_COLOUR,
                                screen)
        particles.append(particle)
        particles_copy = particles.copy()
        print(particles_copy)

    # Start the main loop for the game.
    while True:
        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill((10, 10, 10))
        main_particle.draw_particle()

        for particle in particles:
            particle.draw_particle()
            particle.random_move()
            for particle_copy in particles_copy:
                if particle.pos_x - particle_copy < 2:
                    particle.position_locked()

        # Update screen
        pygame.display.flip()

dla_simulation()
```

答:
You have to compute and evaluate the distance from each particle to each other particle.

Use 2 nested loops. Each loop iterates through the particles. If the

for particle_a in particles:
    for particle_b in particles:
```

<p>If <code>particle_a</code> and <code>particle_b</code> is the same, then <code>continue</code> the inner loop without doing anything:</p>

<pre class="lang-py prettyprint-override"><code>if particle_a == particle_b:
    continue
</code>```

Compute the Euclidean distance between the particles by math.sqrt(dx*dx + dy*dy) or hypot(dx, dy):

dx = particle_a.pos_x - particle_b.pos_x
dy = particle_a.pos_y - particle_b.pos_y
distance = math.sqrt(dx*dx + dy*dy)
```

<p>Stop both particles, if the distance is below or equal <code>2*radius</code>:</p>

<pre class="lang-py prettyprint-override"><code>if distance <= 2*radius:
    particle_a.position_locked()
    particle_b.position_locked()
</code>```

Algorithm

import math
```

<pre class="lang-py prettyprint-override"><code>for particle_a in particles:
    for particle_b in particles:
        if particle_a == particle_b:
            continue

        dx = particle_a.pos_x - particle_b.pos_x
        dy = particle_a.pos_y - particle_b.pos_y
        distance = math.sqrt(dx*dx + dy*dy)

        if distance <= 2*radius:
            particle_a.position_locked()
            particle_b.position_locked()
</code>```

Body:
You have to compute and evaluate the distance from each particle to each other particle.

Use 2 nested loops. Each loop iterates through the particles. If the

for particle_a in particles:
    for particle_b in particles:

If particle_a and particle_b is the same, then continue the inner loop without doing anything:

if particle_a == particle_b:
    continue

Compute the Euclidean distance between the particles by math.sqrt(dx*dx + dy*dy) or hypot(dx, dy):

dx = particle_a.pos_x - particle_b.pos_x
dy = particle_a.pos_y - particle_b.pos_y
distance = math.sqrt(dx*dx + dy*dy)

Stop both particles, if the distance is below or equal 2*radius:

if distance <= 2*radius:
    particle_a.position_locked()
    particle_b.position_locked()

Algorithm

import math

for particle_a in particles:
    for particle_b in particles:
        if particle_a == particle_b:
            continue

        dx = particle_a.pos_x - particle_b.pos_x
        dy = particle_a.pos_y - particle_b.pos_y
        distance = math.sqrt(dx*dx + dy*dy)

        if distance <= 2*radius:
            particle_a.position_locked()
            particle_b.position_locked()


来源: stackexchange

问:
Filtering ls output to only display dirs/files less than certain size
I am using ls -lRa to recursively go through my file structure.

However, when I get to large directories it takes a long time to go through them.

How do you filter this ls -lRa command so that if the dir it is ls on is over a certain size then it will just use ls -la and not waste time going recursively through the dir.

I would like to maintain the ls -la format.

Some basic pseudo code might be:

```<code>for each fileSize
do
if fileSize is greater than x
then ls -lRa on that directory
else
ls -la dir on that directory
fi
done
</code>```

How would I obtain the fileSize variable in this example.

I know I can use -ls -la | awk '{print $5}' but how do I perform the check to see if this number is less/greater than in relation to the dir the size belongs to?

答:
Obligatory: Don't parse ls

You can use find to count the number of files in a directory, so try something like this:

```<code>for dir in ./*/; do
    count="$(find "$dir" -printf '.' | wc -c)"
    if [[ $count -gt $x ]]; then
        ls -lRa "$dir"
    else
        ls -la "$dir"
    fi
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using ls -lRa to recursively go through my file structure.

However, when I get to large directories it takes a long time to go through them.

How do you filter this ls -lRa command so that if the dir it is ls on is over a certain size then it will just use ls -la and not waste time going recursively through the dir.

I would like to maintain the ls -la format.

Some basic pseudo code might be:

for each fileSize
do
if fileSize is greater than x
then ls -lRa on that directory
else
ls -la dir on that directory
fi
done

How would I obtain the fileSize variable in this example.

I know I can use -ls -la | awk '{print $5}' but how do I perform the check to see if this number is less/greater than in relation to the dir the size belongs to?

Body:
Obligatory: Don't parse ls

You can use find to count the number of files in a directory, so try something like this:

for dir in ./*/; do
    count="$(find "$dir" -printf '.' | wc -c)"
    if [[ $count -gt $x ]]; then
        ls -lRa "$dir"
    else
        ls -la "$dir"
    fi
done


问:
Pandas group by column and count values
I have a dataframe:

```<code>date        code     result
2020-01-01  2069.0   Negative
2020-01-29  2069.0   Negative
2020-02-06  2069.0   Positive
2020-02-06  2070.0   Negative
2020-02-07  2070.0   Positive
</code>```

Grouping by code, I want to find how many results = 'Positive', and how many results = 'Positive' AND 'Negative'. I'm quite new to pandas so I'm quite confused with all the functions that are available.

Thanks!

答:
You can try groupby.agg:

```<code>d = dict(zip(['sum','count'],['Positive','Both']))
(df['result'].eq('Positive').view('i1').groupby(df['code']).
agg(['sum','count']).rename(columns=d))
</code>```

```<code>        Positive  Both
code
2069.0         1     3
2070.0         1     2
</code>```

Title: Pandas group by column and count values

Body:
I have a dataframe:

date        code     result
2020-01-01  2069.0   Negative
2020-01-29  2069.0   Negative
2020-02-06  2069.0   Positive
2020-02-06  2070.0   Negative
2020-02-07  2070.0   Positive

Grouping by code, I want to find how many results = 'Positive', and how many results = 'Positive' AND 'Negative'. I'm quite new to pandas so I'm quite confused with all the functions that are available.

Thanks!

Body:
You can try groupby.agg:

d = dict(zip(['sum','count'],['Positive','Both']))
(df['result'].eq('Positive').view('i1').groupby(df['code']).
agg(['sum','count']).rename(columns=d))

        Positive  Both
code
2069.0         1     3
2070.0         1     2


问:
Thread blocked when using Infinispan 9 embedded cache with L1
I'm using Infinispan 9.4.16 in embedded mode. Here is the config of a cache:

```<code><distributed-cache name="mycache" mode="SYNC" remote-timeout="15000" l1-lifespan="60000" owners="1" segments="80">
    <locking striping="false" concurrency-level="100" acquire-timeout="60000"/>
    <persistence>
        ...
    </persistence>
    <state-transfer chunk-size="512" timeout="240000"/>
</distributed-cache>
</code>```

I run a cluster of 4 nodes. The entries in this cache could be read, updated or removed concurrently.
So randomly, a thread got blocked (waiting indefinitely) with this stack trace:

```<code>"a-thread-1" #403 daemon prio=5 os_prio=0 tid=0x0000000023acf800 nid=0x5257 waiting on condition [0x00007fc801941000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000066c879658> (a org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:997)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync.innerGet(L1WriteSynchronizer.java:93)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.get(L1WriteSynchronizer.java:142)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.abortL1UpdateOrWait(L1NonTxInterceptor.java:335)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.removeFromL1Command(L1NonTxInterceptor.java:405)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.lambda$handleDataWriteCommand$10(L1NonTxInterceptor.java:382)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor$$Lambda$1347/746020467.apply(Unknown Source)
    at org.infinispan.interceptors.impl.SimpleAsyncInvocationStage.addCallback(SimpleAsyncInvocationStage.java:70)
    at org.infinispan.interceptors.InvocationStage.andHandle(InvocationStage.java:65)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:190)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.handleDataWriteCommand(L1NonTxInterceptor.java:362)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitRemoveCommand(L1NonTxInterceptor.java:247)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.impl.DistCacheWriterInterceptor.visitRemoveCommand(DistCacheWriterInterceptor.java:107)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitRemoveCommand(CacheLoaderInterceptor.java:164)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.setSkipRemoteGetsAndInvokeNextForDataCommand(EntryWrappingInterceptor.java:671)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitRemoveExpiredCommand(EntryWrappingInterceptor.java:363)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitDataWriteCommand(L1LastChanceInterceptor.java:136)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitRemoveCommand(L1LastChanceInterceptor.java:82)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitNonTxDataWriteCommand(AbstractLockingInterceptor.java:124)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataWriteCommand(NonTransactionalLockingInterceptor.java:40)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitRemoveCommand(AbstractLockingInterceptor.java:102)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleNonTxWriteCommand(StateTransferInterceptor.java:309)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleWriteCommand(StateTransferInterceptor.java:252)
    at org.infinispan.statetransfer.StateTransferInterceptor.visitRemoveCommand(StateTransferInterceptor.java:108)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitRemoveCommand(CacheMgmtInterceptor.java:431)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.IsMarshallableInterceptor.visitRemoveCommand(IsMarshallableInterceptor.java:63)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invokeAsync(AsyncInterceptorChainImpl.java:234)
    at org.infinispan.cache.impl.CacheImpl.executeCommandAndCommitIfNeededAsync(CacheImpl.java:1930)
    at org.infinispan.cache.impl.CacheImpl.performRemoveExpiredCommand(CacheImpl.java:717)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:698)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:690)
    at org.infinispan.expiration.impl.ClusterExpirationManager.handleLifespanExpireEntry(ClusterExpirationManager.java:143)
    at org.infinispan.expiration.impl.ClusterExpirationManager.entryExpiredInMemory(ClusterExpirationManager.java:201)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:168)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:178)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.runL1UpdateIfPossible(L1WriteSynchronizer.java:173)
    at org.infinispan.distribution.impl.L1ManagerImpl.remoteValueFound(L1ManagerImpl.java:196)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.lambda$remoteGetSingleKey$1(BaseDistributionInterceptor.java:211)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor$$Lambda$1388/1407890021.accept(Unknown Source)
    at java.util.concurrent.CompletableFuture.uniAccept(CompletableFuture.java:670)
    at java.util.concurrent.CompletableFuture.uniAcceptStage(CompletableFuture.java:683)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:2010)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:110)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.remoteGetSingleKey(BaseDistributionInterceptor.java:200)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetCommand(BaseDistributionInterceptor.java:666)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetKeyValueCommand(BaseDistributionInterceptor.java:672)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performL1Lookup(L1NonTxInterceptor.java:157)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performCommandWithL1WriteIfAble(L1NonTxInterceptor.java:132)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitDataReadCommand(L1NonTxInterceptor.java:123)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitGetKeyValueCommand(L1NonTxInterceptor.java:112)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitGetKeyValueCommand(CacheLoaderInterceptor.java:130)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitDataReadCommand(EntryWrappingInterceptor.java:204)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitGetKeyValueCommand(EntryWrappingInterceptor.java:192)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataReadCommand(NonTransactionalLockingInterceptor.java:34)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitGetKeyValueCommand(AbstractLockingInterceptor.java:107)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.handleReadCommand(BaseStateTransferInterceptor.java:193)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.visitGetKeyValueCommand(BaseStateTransferInterceptor.java:168)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitDataReadCommand(CacheMgmtInterceptor.java:120)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitGetKeyValueCommand(CacheMgmtInterceptor.java:95)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invoke(AsyncInterceptorChainImpl.java:248)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:527)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:520)
    at org.infinispan.cache.impl.AbstractDelegatingCache.get(AbstractDelegatingCache.java:438)
    at org.infinispan.cache.impl.EncoderCache.get(EncoderCache.java:660)
</code>```

After some investigation, I found out that the thread is blocked by itself. But I don't know how it is possible. Is this an issue of Infinispan ?

答:
From the stack trace it appears that the entry had expired via lifespan expiration at the same time. I would suggest logging a JIRA to https://issues.redhat.com/projects/ISPN. This seems to be an unexpected interaction between expiration and L1 usage.

I am assuming you must be using the programmatic method with lifespan when inserting values as well, since your configuration does not have expiration enabled.

Body:
I'm using Infinispan 9.4.16 in embedded mode. Here is the config of a cache:

<distributed-cache name="mycache" mode="SYNC" remote-timeout="15000" l1-lifespan="60000" owners="1" segments="80">
    <locking striping="false" concurrency-level="100" acquire-timeout="60000"/>
    <persistence>
        ...
    </persistence>
    <state-transfer chunk-size="512" timeout="240000"/>
</distributed-cache>

I run a cluster of 4 nodes. The entries in this cache could be read, updated or removed concurrently.
So randomly, a thread got blocked (waiting indefinitely) with this stack trace:

"a-thread-1" #403 daemon prio=5 os_prio=0 tid=0x0000000023acf800 nid=0x5257 waiting on condition [0x00007fc801941000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000066c879658> (a org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:997)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync.innerGet(L1WriteSynchronizer.java:93)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.get(L1WriteSynchronizer.java:142)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.abortL1UpdateOrWait(L1NonTxInterceptor.java:335)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.removeFromL1Command(L1NonTxInterceptor.java:405)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.lambda$handleDataWriteCommand$10(L1NonTxInterceptor.java:382)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor$$Lambda$1347/746020467.apply(Unknown Source)
    at org.infinispan.interceptors.impl.SimpleAsyncInvocationStage.addCallback(SimpleAsyncInvocationStage.java:70)
    at org.infinispan.interceptors.InvocationStage.andHandle(InvocationStage.java:65)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:190)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.handleDataWriteCommand(L1NonTxInterceptor.java:362)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitRemoveCommand(L1NonTxInterceptor.java:247)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.impl.DistCacheWriterInterceptor.visitRemoveCommand(DistCacheWriterInterceptor.java:107)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitRemoveCommand(CacheLoaderInterceptor.java:164)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.setSkipRemoteGetsAndInvokeNextForDataCommand(EntryWrappingInterceptor.java:671)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitRemoveExpiredCommand(EntryWrappingInterceptor.java:363)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitDataWriteCommand(L1LastChanceInterceptor.java:136)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitRemoveCommand(L1LastChanceInterceptor.java:82)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitNonTxDataWriteCommand(AbstractLockingInterceptor.java:124)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataWriteCommand(NonTransactionalLockingInterceptor.java:40)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitRemoveCommand(AbstractLockingInterceptor.java:102)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleNonTxWriteCommand(StateTransferInterceptor.java:309)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleWriteCommand(StateTransferInterceptor.java:252)
    at org.infinispan.statetransfer.StateTransferInterceptor.visitRemoveCommand(StateTransferInterceptor.java:108)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitRemoveCommand(CacheMgmtInterceptor.java:431)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.IsMarshallableInterceptor.visitRemoveCommand(IsMarshallableInterceptor.java:63)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invokeAsync(AsyncInterceptorChainImpl.java:234)
    at org.infinispan.cache.impl.CacheImpl.executeCommandAndCommitIfNeededAsync(CacheImpl.java:1930)
    at org.infinispan.cache.impl.CacheImpl.performRemoveExpiredCommand(CacheImpl.java:717)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:698)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:690)
    at org.infinispan.expiration.impl.ClusterExpirationManager.handleLifespanExpireEntry(ClusterExpirationManager.java:143)
    at org.infinispan.expiration.impl.ClusterExpirationManager.entryExpiredInMemory(ClusterExpirationManager.java:201)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:168)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:178)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.runL1UpdateIfPossible(L1WriteSynchronizer.java:173)
    at org.infinispan.distribution.impl.L1ManagerImpl.remoteValueFound(L1ManagerImpl.java:196)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.lambda$remoteGetSingleKey$1(BaseDistributionInterceptor.java:211)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor$$Lambda$1388/1407890021.accept(Unknown Source)
    at java.util.concurrent.CompletableFuture.uniAccept(CompletableFuture.java:670)
    at java.util.concurrent.CompletableFuture.uniAcceptStage(CompletableFuture.java:683)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:2010)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:110)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.remoteGetSingleKey(BaseDistributionInterceptor.java:200)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetCommand(BaseDistributionInterceptor.java:666)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetKeyValueCommand(BaseDistributionInterceptor.java:672)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performL1Lookup(L1NonTxInterceptor.java:157)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performCommandWithL1WriteIfAble(L1NonTxInterceptor.java:132)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitDataReadCommand(L1NonTxInterceptor.java:123)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitGetKeyValueCommand(L1NonTxInterceptor.java:112)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitGetKeyValueCommand(CacheLoaderInterceptor.java:130)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitDataReadCommand(EntryWrappingInterceptor.java:204)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitGetKeyValueCommand(EntryWrappingInterceptor.java:192)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataReadCommand(NonTransactionalLockingInterceptor.java:34)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitGetKeyValueCommand(AbstractLockingInterceptor.java:107)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.handleReadCommand(BaseStateTransferInterceptor.java:193)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.visitGetKeyValueCommand(BaseStateTransferInterceptor.java:168)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitDataReadCommand(CacheMgmtInterceptor.java:120)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitGetKeyValueCommand(CacheMgmtInterceptor.java:95)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invoke(AsyncInterceptorChainImpl.java:248)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:527)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:520)
    at org.infinispan.cache.impl.AbstractDelegatingCache.get(AbstractDelegatingCache.java:438)
    at org.infinispan.cache.impl.EncoderCache.get(EncoderCache.java:660)

After some investigation, I found out that the thread is blocked by itself. But I don't know how it is possible. Is this an issue of Infinispan ?


问:
CakePHP custom route w/ %20 in url want to replace w/ "-" not sure how to make this happen in the route
My link:

```<code>echo $link->link($planDetailsByCompany['PlanDetail']['name'],
    array('controller' => 'plan_details', 'action' => 'view_benefit_schedule',
    'id' => $planDetailsByCompany['PlanDetail']['id'],
    'slug' =>  $planDetailsByCompany['PlanDetail']['name']));
</code>```

My custom route:

```<code>Router::connect('/pd/:id-:slug',
    array('controller' => 'plan_details', 'action' => 'view_benefit_schedule'),
    array('pass' => array('id', 'slug'),
    'id' => '[0-9]+'));
</code>```

My url is displaying like so:

```<code>..pd/44-Primary%20Indemnity
</code>```

I cannot determine how to remove the %20 and replace it with a  "-". There is a space in the company name that is causing this. Is this possible within the CakePHP router functionality? If so, how? Or another method.

答:
Geeze.. I just solved this!

In my link above, replace the 'slug' line with:

```<code>...'slug' =>  Inflector::slug($planDetailsByCompany['PlanDetail']['name'])...
</code>```

The Inflector handles the spaces in the url. And my result url is:

```<code>...pd/44-Primary_Indemnity
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My link:

echo $link->link($planDetailsByCompany['PlanDetail']['name'],
    array('controller' => 'plan_details', 'action' => 'view_benefit_schedule',
    'id' => $planDetailsByCompany['PlanDetail']['id'],
    'slug' =>  $planDetailsByCompany['PlanDetail']['name']));

My custom route:

Router::connect('/pd/:id-:slug',
    array('controller' => 'plan_details', 'action' => 'view_benefit_schedule'),
    array('pass' => array('id', 'slug'),
    'id' => '[0-9]+'));

My url is displaying like so:

..pd/44-Primary%20Indemnity

I cannot determine how to remove the %20 and replace it with a  "-". There is a space in the company name that is causing this. Is this possible within the CakePHP router functionality? If so, how? Or another method.

Body:
Geeze.. I just solved this!

In my link above, replace the 'slug' line with:

...'slug' =>  Inflector::slug($planDetailsByCompany['PlanDetail']['name'])...

The Inflector handles the spaces in the url. And my result url is:

...pd/44-Primary_Indemnity


问:
What is the best way to check if a file contains a key before adding a new line?
I have a CSV file containing the following columns -

Key,Value

First,Line

Second,Line

Third,Line

I want to add a new Key-Value to this file given the key is not already present in the file using C#? What would be the best way to do this? Would I have to traverse line by line and check for the Keys or is there any other better way?

I am not using the CSVHelper package or any other CSV writer.

答:
You could do this:

```<code>string path = @"PathToFile.csv";
string Content = string.Empty;

using (StreamReader reader = new StreamReader(path))
{
    Content = reader.ReadToEnd();
    reader.Close();
}

if (!Content.Contains("YourKey"))
{
    using (StreamWriter sw = new StreamWriter(path))
    {
        sw.WriteLine(Content + "\nYourkey,YourValue");
        sw.Close();
    }
}
</code>```

Read the file and write all text to a string variable, check the variable if the key exists, if it doesn't then write content back to the file along with your new key. as the file grows it will take longer and longer to search the whole file but it'll work well for a couple thousand lines.

Body:
You could do this:

string path = @"PathToFile.csv";
string Content = string.Empty;

using (StreamReader reader = new StreamReader(path))
{
    Content = reader.ReadToEnd();
    reader.Close();
}

if (!Content.Contains("YourKey"))
{
    using (StreamWriter sw = new StreamWriter(path))
    {
        sw.WriteLine(Content + "\nYourkey,YourValue");
        sw.Close();
    }
}

Read the file and write all text to a string variable, check the variable if the key exists, if it doesn't then write content back to the file along with your new key. as the file grows it will take longer and longer to search the whole file but it'll work well for a couple thousand lines.


问:
Difference between vector and array in p_threads initialisation
I'm inclined towards using vectors and smart pointers instead of arrays as it is safer. The problem is that when initialised as an array, my threads join the main thread successfully. However, this is not the case when initialised as a vector. This is expected as the array elements are accessed by reference.

1. As array

```<code>pthread_t threads[numCPU]; // Initialised as an array

// Creating threads
for(long unsigned int i=0; i<numCPU; i++){
        rc = pthread_create(&threads[i], &attr, myfunc, (void *) args[i] );
        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Created Thread " + std::to_string(i)));
        }
}

// Joining thread
for(long unsigned int i=0; i<numCPU;i++){
      rc = pthread_join(threads[i], NULL);

        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Joined Thread " + std::to_string(i)));
}
</code>```

The signatures of pthread_create and pthread_join would be respected when:

```<code>std::vector<pthread_t *> threads(numCPU);
</code>```

A vector of pointers doesn't make sense and I may have to manage memory. Is there a safer way to create threads?

答:
I'm inclined towards using vectors and smart pointers instead of arrays as it is safer.

Vectors and smart pointers aren't safer than arrays.

Using vector instead of an array would be useful if you want the number of threads to be determined at runtime, without a constant upper limit. Otherwise it won't be useful.

It is unclear why you would create a vector of pointers.

Body:
I'm inclined towards using vectors and smart pointers instead of arrays as it is safer. The problem is that when initialised as an array, my threads join the main thread successfully. However, this is not the case when initialised as a vector. This is expected as the array elements are accessed by reference.

1. As array

pthread_t threads[numCPU]; // Initialised as an array

// Creating threads
for(long unsigned int i=0; i<numCPU; i++){
        rc = pthread_create(&threads[i], &attr, myfunc, (void *) args[i] );
        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Created Thread " + std::to_string(i)));
        }
}

// Joining thread
for(long unsigned int i=0; i<numCPU;i++){
      rc = pthread_join(threads[i], NULL);

        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Joined Thread " + std::to_string(i)));
}

The signatures of pthread_create and pthread_join would be respected when:

std::vector<pthread_t *> threads(numCPU);

A vector of pointers doesn't make sense and I may have to manage memory. Is there a safer way to create threads?


问:
Text over animated javascript div
I have an animated background that randomly displays 0s and 1s in pastel shades and fills the whole screen and Im trying to get text over that but it doesn't seem to be working. Could someone please help?
This is the html code

```<code><p style="font-size:20px;z-index:-1;" class="back"></p>
<div class="main">
<p style="font-size:100px;z-index:1;">Hello!There!</p>
</div>
</div>
</code>```

And this is the JavaScript code

```<code>var lines=10;
var lenght=100;
function getcolor()
{ var color='#';
    var letters = "BCDEF";
   for(var i=0;i<6;i++)
   {color+= letters[Math.floor(Math.random() * 5)];}
    return color;}
function genstring()
{var letters="01010101010101"
 var string="<p>"
 for(var i=0;i<2000;i++)
 {for(var j=0;j<Math.floor(Math.random()*10);j++)
  {
    string+=letters[Math.floor(Math.random()*2)];
  }
  string+=" "
 }
 string+="</p>"
return string;
}
function changer()
{var x=genstring()
var y=document.querySelector(".back")
var color=getcolor()
y.innerHTML=x
y.style.color=color}
setInterval("changer()",1300)
</code>```

The complete code is on repl : https://repl.it/@Ajkallivayalil/about#script.js
And the output currently looks like this: https://about--ajkallivayalil.repl.co/.
Thank you in advance for your help ^^

答:
Your text ("Hello! There!") exists, it is just under field of screen (because it is in another
 block, that is placed via engine under first
 according default order of
 on webpage). You can inspect your div.main element via Chrome Developer Tools or change scale of page to see where it is.

What you can do with that:

Add attributes position: absolute; top: 40px; left: 40px; to style of
Hello!There!

Then it will looks this way:

Hello!There!

Just place div.main over
 (div with 01010101010101) in HTML code

Title: Text over animated javascript div

Body:
I have an animated background that randomly displays 0s and 1s in pastel shades and fills the whole screen and Im trying to get text over that but it doesn't seem to be working. Could someone please help?
This is the html code

Hello!There!

And this is the JavaScript code

var lines=10;
var lenght=100;
function getcolor()
{ var color='#';
    var letters = "BCDEF";
   for(var i=0;i<6;i++)
   {color+= letters[Math.floor(Math.random() * 5)];}
    return color;}
function genstring()
{var letters="01010101010101"
 var string="
"
 for(var i=0;i<2000;i++)
 {for(var j=0;j<Math.floor(Math.random()*10);j++)
  {
    string+=letters[Math.floor(Math.random()*2)];
  }
  string+=" "
 }
 string+="
"
return string;
}
function changer()
{var x=genstring()
var y=document.querySelector(".back")
var color=getcolor()
y.innerHTML=x
y.style.color=color}
setInterval("changer()",1300)

The complete code is on repl : https://repl.it/@Ajkallivayalil/about#script.js
And the output currently looks like this: https://about--ajkallivayalil.repl.co/.
Thank you in advance for your help ^^

Body:
Your text ("Hello! There!") exists, it is just under field of screen (because it is in another <div> block, that is placed via engine under first <div> according default order of <div> on webpage). You can inspect your div.main element via Chrome Developer Tools or change scale of page to see where it is.

What you can do with that:

Add attributes position: absolute; top: 40px; left: 40px; to style of <p style="font-size:100px;z-index:1;">Hello!There!</p>

Then it will looks this way:
<p style="font-size:100px;z-index:1;position: absolute; top: 40px; left: 40px;">Hello!There!</p>

Just place div.main over <div style="width:100%;height:100%;overflow:hidden;"> (div with 01010101010101) in HTML code


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
Just use your echo like this:</p>

```<code>echo '<td ><div class="iddiv"> <input name="" type="text" value="' . $row['username'] . '" />   <div>    </td> ';
</code>```

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
Just use your echo like this:

echo '<td ><div class="iddiv"> <input name="" type="text" value="' . $row['username'] . '" />   <div>    </td> ';


问:
Laravel UUID as primary key and ID as foreign key
I've defined a uuid as primary key, and would like to use id (auto increment) as foreign key to define relationships.

Both Posts and Comments have in their migration:

```<code>$table->uuid('uuid')->primary();
$table->bigInteger('id');
</code>```

Their models have:

```<code>protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;
</code>```

And the comments migration has

```<code>$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
</code>```

But if I run the migration I get General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade) of which I'm not sure why it's happening? Before adding the UUID logic it was working fine so I'm sure I've made a mistake there, but I'm not sure what as the error is generic.

答:
Adding a foreign key requires the referenced key and the foreign one to have the same type and sign. According to your migrations, both posts.id and comments.id are signed bigints but you are trying to add a foreign key to a unsigned bigint.

In your migrations for posts and comments, change

```<code>$table->bigInteger('id');
</code>```

to

```<code>$table->bigInteger('id')->unsigned();
</code>```

and migrate them again.

Body:
I've defined a uuid as primary key, and would like to use id (auto increment) as foreign key to define relationships.

Both Posts and Comments have in their migration:

$table->uuid('uuid')->primary();
$table->bigInteger('id');

Their models have:

protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;

And the comments migration has

$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

But if I run the migration I get General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade) of which I'm not sure why it's happening? Before adding the UUID logic it was working fine so I'm sure I've made a mistake there, but I'm not sure what as the error is generic.

Body:
Adding a foreign key requires the referenced key and the foreign one to have the same type and sign. According to your migrations, both posts.id and comments.id are signed bigints but you are trying to add a foreign key to a unsigned bigint.

In your migrations for posts and comments, change

$table->bigInteger('id');

to

$table->bigInteger('id')->unsigned();

and migrate them again.


问:
Replace specific chinese words in every row of a Dataframe
I'm trying to split a long string of Chinese characters but when I try to replace the "headers" of each column, python does not make the replacement:</p>

```<code>data= pd.DataFrame({'DETAILS': ['厂名: 进口地扪玉米粒 厂址: 进口地扪玉米粒 厂家联系方式: 02081977626 配料.', '厂名: Hill View Packing Co. 厂址: 美国地们 厂家联系方式: 0', '厂名: 5 厂址: 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期']
                       })
data.DETAILS.replace(['厂名:','厂址:'],'$',inplace=True)
</code>```

答:
I would do a regex replace:

```<code> lst = ['厂名:','厂址:']

 data['DETAILS'] = data.DETAILS.replace('|'.join(lst), '$', regex=True)
</code>```

Output:

```<code>                                       DETAILS
0  $ 进口地扪玉米粒 $ 进口地扪玉米粒 厂家联系方式: 02081977626 配料.
1     $ Hill View Packing Co. $ 美国地们 厂家联系方式: 0
2        $ 5 $ 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期
</code>```

Body:
I'm trying to split a long string of Chinese characters but when I try to replace the "headers" of each column, python does not make the replacement:

data= pd.DataFrame({'DETAILS': ['厂名: 进口地扪玉米粒 厂址: 进口地扪玉米粒 厂家联系方式: 02081977626 配料.', '厂名: Hill View Packing Co. 厂址: 美国地们 厂家联系方式: 0', '厂名: 5 厂址: 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期']
                       })
data.DETAILS.replace(['厂名:','厂址:'],'$',inplace=True)

Body:
I would do a regex replace:

 lst = ['厂名:','厂址:']

 data['DETAILS'] = data.DETAILS.replace('|'.join(lst), '$', regex=True)

Output:

                                       DETAILS
0  $ 进口地扪玉米粒 $ 进口地扪玉米粒 厂家联系方式: 02081977626 配料.
1     $ Hill View Packing Co. $ 美国地们 厂家联系方式: 0
2        $ 5 $ 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期


问:
Location service which allows creating and modifying data with REST API
I was wondering if there is a REST API where I can create/update/delete data. For example, what I would like to do is to create a pin on the map or save favorite place I find on the map through REST API.

Google Maps had this feature before but it is deprecated as from this post: https://cloud.google.com/blog/products/maps-platform/announcing-deprecation-of-place-add

I was going through Google Maps API and can't see this option, also I've checked HERE maps API but it doesn't seem to provide this.

Is there any API where I could do this, basically send POST/PUT/DELETE requests to check how maps/location service works?

答:
You can use directly Fleet Telematics Custom Locations REST api or you can use HERE maps for JavaScript API to communicate with this REST api.

Second option is to use HERE studio which is very easy to use.

Here is simple example how to upload point geometry (Marker) using HERE maps for JavaScript API:

// assuming there is already H.Map (map) & H.service.Platform (platform) instance

const layerId = 'MY_LAYER';
const cleService = platform.getCustomLocationService();

// check if layer in fleet telematics custom location service exists.
// if yes, upload data.
// If not create new layer, then upload data
cleService.getLayer(layerId, uploadData, createLayer);

/*
 * this method creates marker with random position and uploads it to the server
 */
function uploadData(table) {
  let row = table.addRow(),
      bearing = Math.random() * 360,
      distance = Math.random() * 3000,
      // marker with random position in radius 3km from map's center
      marker = new H.map.Marker(map.getCenter().walk(bearing, distance));

  // add marker to the map
  map.addObject(marker);

  row.setCell('NAME', 'Test name'); // optional
  row.setCell('WKT', marker.getGeometry()); // mandatory

  // push the marker's geometry to the fleet telematics custom location service
  cleService.appendRows([row], () => {console.log('O.K.')}, console.log);
}

/*
 * this method creates new layer in fleet telematics custom location service
 */
function createLayer() {
  // only WKT is mandatory column name
  let metaInfo = {
    layerId,
    columnNames: ['NAME', 'GEOMETRY_ID', 'WKT']
  };

  cleService.createLayer(metaInfo, uploadData, console.error);
}

```

<p>Here is simple example how to show uploaded point geometries on the map using HERE maps for JavaScript API:</p>

<pre class="lang-js prettyprint-override"><code>// assuming there is already H.Map (map) & H.service.Platform (platform) instance

const layerId = 'MY_LAYER';
const cleService = platform.getCustomLocationService();

// Create a tile layer:
cleLayer = cleService.createTileLayer({layerId}, {
  resultType: H.service.extension.TileProvider.ResultType.MARKER
});

// Add the tile layer to the map
map.addLayer(cleLayer); // uploaded geometries start to show from zoom 12
</code>```

Body:
You can use directly Fleet Telematics Custom Locations REST api or you can use HERE maps for JavaScript API to communicate with this REST api.

Second option is to use HERE studio which is very easy to use.

Here is simple example how to upload point geometry (Marker) using HERE maps for JavaScript API:

// assuming there is already H.Map (map) & H.service.Platform (platform) instance

const layerId = 'MY_LAYER';
const cleService = platform.getCustomLocationService();

// check if layer in fleet telematics custom location service exists.
// if yes, upload data.
// If not create new layer, then upload data
cleService.getLayer(layerId, uploadData, createLayer);

/*
 * this method creates marker with random position and uploads it to the server
 */
function uploadData(table) {
  let row = table.addRow(),
      bearing = Math.random() * 360,
      distance = Math.random() * 3000,
      // marker with random position in radius 3km from map's center
      marker = new H.map.Marker(map.getCenter().walk(bearing, distance));

  // add marker to the map
  map.addObject(marker);

  row.setCell('NAME', 'Test name'); // optional
  row.setCell('WKT', marker.getGeometry()); // mandatory

  // push the marker's geometry to the fleet telematics custom location service
  cleService.appendRows([row], () => {console.log('O.K.')}, console.log);
}

/*
 * this method creates new layer in fleet telematics custom location service
 */
function createLayer() {
  // only WKT is mandatory column name
  let metaInfo = {
    layerId,
    columnNames: ['NAME', 'GEOMETRY_ID', 'WKT']
  };

  cleService.createLayer(metaInfo, uploadData, console.error);
}

Here is simple example how to show uploaded point geometries on the map using HERE maps for JavaScript API:

// assuming there is already H.Map (map) & H.service.Platform (platform) instance

const layerId = 'MY_LAYER';
const cleService = platform.getCustomLocationService();

// Create a tile layer:
cleLayer = cleService.createTileLayer({layerId}, {
  resultType: H.service.extension.TileProvider.ResultType.MARKER
});

// Add the tile layer to the map
map.addLayer(cleLayer); // uploaded geometries start to show from zoom 12


问:
Jenkins + Docker: Cannot connect to the Docker daemon at tcp://dind:2375. Is the docker daemon running?
I create a jenkins with this docker-compose.yml:

```<code>version: '3'
services:
  dind:
    image: docker:dind
    privileged: true
    expose:
      - 2375
      - 2376
    volumes:
      - .docker/jenkins_data:/var/jenkins_home
    environment:
      DOCKER_TLS_CERTDIR: ""
  jenkins:
    build: .docker
    environment:
      DOCKER_HOST: tcp://dind:2375
    ports:
      - 8081:8080
      - 50000:50000
    links:
      - dind
    volumes:
      - .docker/jenkins_data:/var/jenkins_home
      - .myProject:/home/project
</code>```

.docker/Dokerfile:

```<code>FROM jenkins/jenkins:lts

LABEL maintainer="Antoine Descamps <antoine.descamps@ineat-conseil.fr>"

USER root

RUN echo "deb http://ppa.launchpad.net/ansible/ansible/ubuntu trusty main" >> /etc/apt/sources.list
RUN apt-key adv --keyserver https://keyserver.ubuntu.com:443 --recv-keys 93C4A3FD7BB9C367

RUN apt-get update

RUN curl -fsSL https://get.docker.com | bash -
RUN curl -L "https://github.com/docker/compose/releases/download/1.22.0/docker-compose-Linux-x86_64" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose

RUN usermod -aG docker jenkins

USER jenkins
</code>```

My error is:

```<code>docker inspect -f . node:7-alpine

Cannot connect to the Docker daemon at tcp://dind:2375. Is the docker daemon running?
</code>```

答:
When running your docker-compose, in the logs it says DinD is listening on port 2376.

dind_1     | time="2020-05-28T15:41:13.544954400Z" level=info msg="API listen on [::]:2376"

1st way:

use environment: DOCKER_TLS_CERTDIR: "" in dind

So, you use DOCKER_HOST: tcp://dind:2375

2nd way:

remove environment: DOCKER_TLS_CERTDIR: ""

So, you use DOCKER_HOST: tcp://dind:2376

Body:
I create a jenkins with this docker-compose.yml:

version: '3'
services:
  dind:
    image: docker:dind
    privileged: true
    expose:
      - 2375
      - 2376
    volumes:
      - .docker/jenkins_data:/var/jenkins_home
    environment:
      DOCKER_TLS_CERTDIR: ""
  jenkins:
    build: .docker
    environment:
      DOCKER_HOST: tcp://dind:2375
    ports:
      - 8081:8080
      - 50000:50000
    links:
      - dind
    volumes:
      - .docker/jenkins_data:/var/jenkins_home
      - .myProject:/home/project

.docker/Dokerfile:

FROM jenkins/jenkins:lts

LABEL maintainer="Antoine Descamps <antoine.descamps@ineat-conseil.fr>"

USER root

RUN echo "deb http://ppa.launchpad.net/ansible/ansible/ubuntu trusty main" >> /etc/apt/sources.list
RUN apt-key adv --keyserver https://keyserver.ubuntu.com:443 --recv-keys 93C4A3FD7BB9C367

RUN apt-get update

RUN curl -fsSL https://get.docker.com | bash -
RUN curl -L "https://github.com/docker/compose/releases/download/1.22.0/docker-compose-Linux-x86_64" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose

RUN usermod -aG docker jenkins

USER jenkins

My error is:

docker inspect -f . node:7-alpine

Cannot connect to the Docker daemon at tcp://dind:2375. Is the docker daemon running?


问:
Using correctly and cleanly onNewIntent() with setIntent()
I have 3 activities (A, B, C), 2 of which communicate with intents.
Here is the call order: A -> B -> C.
In activity B, I use intent.putExtra("key", gameMode) to start activity C.
When activity C is launched for the first time, there is no problem. But if C ends and I go back to B and change the game_mode, activity C always reads the very first intent.
I know this question will have been asked many times, but even if I try with onNewIntent() (with setIntent(intent) inside), or even with FLAG_ACTIVITY_CLEAR_TOP, it doesn't change anything...
I guess (I'm sure...) I'm the one doing everything wrong, but I'm asking for your help for a complete and clear answer.
The goal being to update the intent (or at least its extras). Should I call the onNewIntent() method, or does Android do it on its own? etc

A huge thank you to the people who took the time to answer my question.

B activity :

```<code>@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MenuPrincipal.this, GameCard.class);
        intent.putExtra("key", gameMode);
        onNewIntent(intent);
        startActivity(intent);
    }
});
</code>```

C activity :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    int gameMode;
    Bundle extras = getIntent().getExtras();
    if(extras != null) {
        gameMode = extras.getInt("key", 0);
    }
}

@Override
public void onBackPressed() {
    // do nothing.
    //default value : super.onBackPressed();
}
</code>```

答:
Thanks to Ajay K S who managed to find the answer:
By using extras.getInt("key"), the application works perfectly (you can read the last - and not only the first - intent without any problem).
Also, after testing, it is not necessary to call the onNewIntent(intent) method yourself to update the intent. It seems that Android does this itself.
Many thanks again!

Body:
I have 3 activities (A, B, C), 2 of which communicate with intents.
Here is the call order: A -> B -> C.
In activity B, I use intent.putExtra("key", gameMode) to start activity C.
When activity C is launched for the first time, there is no problem. But if C ends and I go back to B and change the game_mode, activity C always reads the very first intent.
I know this question will have been asked many times, but even if I try with onNewIntent() (with setIntent(intent) inside), or even with FLAG_ACTIVITY_CLEAR_TOP, it doesn't change anything...
I guess (I'm sure...) I'm the one doing everything wrong, but I'm asking for your help for a complete and clear answer.
The goal being to update the intent (or at least its extras). Should I call the onNewIntent() method, or does Android do it on its own? etc

A huge thank you to the people who took the time to answer my question.

B activity :

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MenuPrincipal.this, GameCard.class);
        intent.putExtra("key", gameMode);
        onNewIntent(intent);
        startActivity(intent);
    }
});

C activity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    int gameMode;
    Bundle extras = getIntent().getExtras();
    if(extras != null) {
        gameMode = extras.getInt("key", 0);
    }
}

@Override
public void onBackPressed() {
    // do nothing.
    //default value : super.onBackPressed();
}


问:
Functions In CoffeeScript
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

```<code>function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}
</code>```

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

```<code><script type="text/javascript" src="../coffee/convert.js"></script>

<script type="text/javascript">
    convert(6, 3, 10);
</script>
</code>```

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

答:
You should check these awesome slides just released today by godfoca http://www.slideshare.net/godfoca/lets-have-a-cup-of-coffeescript  Also, you can try code out through-the-web at http://jashkenas.github.com/coffee-script/</p>

```<code>convert = (num1, num2, num3) ->
  num1 + num2 * num3
</code>```

Title: Functions In CoffeeScript

Body:
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

Body:
You should check these awesome slides just released today by godfoca http://www.slideshare.net/godfoca/lets-have-a-cup-of-coffeescript  Also, you can try code out through-the-web at http://jashkenas.github.com/coffee-script/

convert = (num1, num2, num3) ->
  num1 + num2 * num3


问:
Finding Max Date Along with User ID with One Group By in MySQL
I am trying to figure out the number of visits a site has, the most recent visit and who the user was in the most recent visit. The only item I'm unable to get at the moment is the user who visited the site most recently.There is a user_id column in the data. My current query is below. I'm thinking I will have to use a subquery but want to see if someone has a better method.</p>

```<code>Select
  site_id,
  COUNT(id),
  MAX(date_visit)
FROM site_views
GROUP BY 1
</code>```

答:
The most efficient method with the right indexes is usually:</p>

```<code>select sv.*
from site_views sv
where sv.date_visit = (select max(sv2.site_visit) from site_views sv2 where sv2.site_id = sv.sidte_id);
</code>```

Body:
I am trying to figure out the number of visits a site has, the most recent visit and who the user was in the most recent visit. The only item I'm unable to get at the moment is the user who visited the site most recently.There is a user_id column in the data. My current query is below. I'm thinking I will have to use a subquery but want to see if someone has a better method.

Select
  site_id,
  COUNT(id),
  MAX(date_visit)
FROM site_views
GROUP BY 1

Body:
The most efficient method with the right indexes is usually:

select sv.*
from site_views sv
where sv.date_visit = (select max(sv2.site_visit) from site_views sv2 where sv2.site_id = sv.sidte_id);


问:
problem with voiceStateUpdate in JavaScript
I'm trying to get this discord bot work. The idea is simple, make the bot send a notification when someone joins in the voice chat.
Im making this on Atom, the error i got is this one:

```<code>TypeError: Cannot read property 'send' of undefined
at Client.client.on (C:\Users\Franco\Desktop\bot\bot.js:15:20)
at emitTwo (events.js:126:13)
at Client.emit (events.js:214:7)
at VoiceStateUpdateHandler.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\handlers\VoiceStateUpdate.js:39:16)
at WebSocketPacketManager.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\Franco\Desktop\bot\node_modules\ws\lib\event-target.js:120:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
</code>```

the code attempt:

```<code>client.on("message", function(message) {
  client.on('voiceStateUpdate', (oldMember, newMember) => {
    console.log('lol');
    let newUserChannel = newMember.voiceChannel
    let oldUserChannel = oldMember.voiceChannel
    var channel = client.channels.get('353996293154144259');
    if(oldUserChannel === 353996293154144260 && newUserChannel !== 489674797261783041) {
      channel.send('has joined a voice channel');
      // User Joins a voice channel
    } else if(newUserChannel === 489674797261783041){
       channel.send('has left a voice channel');
    // User leaves a voice channel
    }
  })
})
</code>```

The console.log is just for testing if voiceStateUpdate is working.

When I try to run it I get this error:

"TypeError: Cannot read property 'send' of undefined"

As i understand the error is because .send function is undefined

i got almost everything from here:

https://www.reddit.com/r/discordapp/comments/6p85uf/discordjs_any_way_to_detect_when_someone_enter_a/

https://discord.js.org/#/docs/main/stable/general/welcome

Everything I've tried:

Add client.on("message", function(message) {

Edit .send to .message and .sendMessage

try to define .send

change client.channels.get to lient.channelid.get

Change/delete var channel = client.channels.get('353996293154144259');

Move client.on('voiceStateUpdate', (oldMember, newMember) => { out of client.on("message", function(message) { When i do that i got another error

"Second error i got when i move client.on out: "(node:18196) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added. Use emitter.setMaxListeners() to increase limit"

Maybe some useless info:

353996293154144259 = id of General chat on discord server

353996293154144260 = id of the first voice chat

489674797261783041 = id of the second voice chat

UPDATE

Okay, i solved part of the problem, i need use message.channel.send('has joined a voice channel'); instead of channel.send('has joined a voice channel'); But i can't make it work as i want.

Special thanks for YakovL. He helps me to make this post more complete and better.

答:
```<code>var channel = client.channels.get('353996293154144259');
</code>```

this didn't work for me so I used this instead:

```<code>const channel = client.channels.cache.filter((channel) => channel.name === 'name').first();
</code>```

and it would be better to use this but searching for the ID:

```<code>const channel = client.channels.cache.filter((channel) => channel.id === '353996293154144259').first();
</code>```

Body:
I'm trying to get this discord bot work. The idea is simple, make the bot send a notification when someone joins in the voice chat.
Im making this on Atom, the error i got is this one:

TypeError: Cannot read property 'send' of undefined
at Client.client.on (C:\Users\Franco\Desktop\bot\bot.js:15:20)
at emitTwo (events.js:126:13)
at Client.emit (events.js:214:7)
at VoiceStateUpdateHandler.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\handlers\VoiceStateUpdate.js:39:16)
at WebSocketPacketManager.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\Franco\Desktop\bot\node_modules\ws\lib\event-target.js:120:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)

the code attempt:

client.on("message", function(message) {
  client.on('voiceStateUpdate', (oldMember, newMember) => {
    console.log('lol');
    let newUserChannel = newMember.voiceChannel
    let oldUserChannel = oldMember.voiceChannel
    var channel = client.channels.get('353996293154144259');
    if(oldUserChannel === 353996293154144260 && newUserChannel !== 489674797261783041) {
      channel.send('has joined a voice channel');
      // User Joins a voice channel
    } else if(newUserChannel === 489674797261783041){
       channel.send('has left a voice channel');
    // User leaves a voice channel
    }
  })
})

The console.log is just for testing if voiceStateUpdate is working.

When I try to run it I get this error:

"TypeError: Cannot read property 'send' of undefined"

As i understand the error is because .send function is undefined

i got almost everything from here:

https://www.reddit.com/r/discordapp/comments/6p85uf/discordjs_any_way_to_detect_when_someone_enter_a/

https://discord.js.org/#/docs/main/stable/general/welcome

Everything I've tried:

Add client.on("message", function(message) {

Edit .send to .message and .sendMessage

try to define .send

change client.channels.get to lient.channelid.get

Change/delete var channel = client.channels.get('353996293154144259');

Move client.on('voiceStateUpdate', (oldMember, newMember) => { out of client.on("message", function(message) { When i do that i got another error

"Second error i got when i move client.on out: "(node:18196) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added. Use emitter.setMaxListeners() to increase limit"

Maybe some useless info:

353996293154144259 = id of General chat on discord server

353996293154144260 = id of the first voice chat

489674797261783041 = id of the second voice chat

UPDATE

Okay, i solved part of the problem, i need use message.channel.send('has joined a voice channel'); instead of channel.send('has joined a voice channel'); But i can't make it work as i want.

Special thanks for YakovL. He helps me to make this post more complete and better.

Body:
var channel = client.channels.get('353996293154144259');

this didn't work for me so I used this instead:

const channel = client.channels.cache.filter((channel) => channel.name === 'name').first();

and it would be better to use this but searching for the ID:

const channel = client.channels.cache.filter((channel) => channel.id === '353996293154144259').first();


问:
RDF standard datatype for currency
I'm developing an ontology for banks and I need to attach datatype properties that are filleed with currency amount. Is there any standard way to do this. </p>

<p>Thanks Luciano </p>

答:
I would say to use xsd:double

Moreover, because you are working in a banking system, maybe you will find this information helpful: http://www.currency2currency.org/EUR#

Title: RDF standard datatype for currency

Body:
I'm developing an ontology for banks and I need to attach datatype properties that are filleed with currency amount. Is there any standard way to do this.

Thanks Luciano


问:
Which Rust data structures are non deterministic
When writing smart contracts it's important to make sure that all data structures used are deterministic.

Specifically, if HashMap or HashSet are used - is there a possible non determinism coming from Rust standard library?

答: Since Wasm runtime doesn't have access to non-deterministic inputs, the entire execution is deterministic. HashSet and HashMap use seed from the available source, in case of Wasm compilation there are no available source, the execution will always be the same. It should be easy to confirm.


问:
Permanently and reliably set gcc include path globally
System: LMDE4, 64bit, gcc-8.3.0, VS Code

Target File: https://github.com/opencv/opencv/blob/master/samples/cpp/videocapture_camera.cpp

Now as the title says, this starts pissing me off. Nothing is working to fix such a simple issue. And NO I don't want to always use "-I" to tell pretty obvious things to the compiler. Here is what I've done so far.

in c_cpp_properties.json of VS Code:

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "/usr/include/"
                ]
            }
        }
    ],
    "version": 4
}
</code>```

in .bashrc:

```<code>#C Include
export C_INCLUDE_PATH="/usr/include"
export C_INCLUDE_PATH=$C_INCLUDE_PATH:"/usr/include/opencv2"

#C++ Include
export CPLUS_INCLUDE_PATH="/usr/include"
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:"/usr/include/c++/8/"
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:"/usr/include/opencv2"

#C/C++ Include
export CPATH="/usr/include"
</code>```

I am pretty sure that all the .bashrc exports are already a dirty workaround and still I get the following message on compile:

```<code>In file included from /usr/include/c++/8/bits/stl_algo.h:59,
                 from /usr/include/c++/8/algorithm:62,
                 from /usr/include/opencv2/core/base.hpp:55,
                 from /usr/include/opencv2/core.hpp:54,
                 from ~/LearnDummy/helloworld.cpp:1:
/usr/include/c++/8/cstdlib:75:15: fatal error: stdlib.h: Datei oder Verzeichnis nicht gefunden
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.
</code>```

Well fine... stdlib.h is unknown (Jesus!)... find /usr -name stdlib.h gives me

```<code>/usr/include/stdlib.h
/usr/include/c++/8/stdlib.h
/usr/include/c++/8/tr1/stdlib.h
/usr/include/x86_64-linux-gnu/bits/stdlib.h
/usr/include/i386-linux-gnu/bits/stdlib.h
</code>```

In addition VS Code already knows(!) where the file is once I click on "Go to Definition" and still gcc is blind. How do I get realiably rid of this?

答:
Here is a minimal repro of your problem on Ubuntu 20.04.

```<code>$ g++ --version
g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0
...

$ cat main.cpp
#include <cstdlib>

int main ()
{
  return EXIT_SUCCESS;
}

$ export CPLUS_INCLUDE_PATH="/usr/include"; g++ -c main.cpp
In file included from main.cpp:1:
/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
compilation terminated.
</code>```

Note that export CPLUS_INCLUDE_PATH="/usr/include" here has the same effect as your
identical setting in your .bashrc.

The error does not occur if we remove that environment setting:

```<code>$ export CPLUS_INCLUDE_PATH=; g++ -c main.cpp; echo Done
Done
</code>```

The effect of that environment setting, as per the GCC Manual: 3.21 Environment Variables Affecting GCC
is the same as:

```<code>$ g++ -isystem /usr/include -c main.cpp
In file included from main.cpp:1:
/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
compilation terminated.
</code>```

which accordingly reproduces the error.

The -isystem option is documented in the GCC Manual: 3.16 Options for Directory Search

The general solution to your problem is: Don't run a g++ compilation in any way
that has the effect of g++ ... -isystem /usr/include ...

You can avoid running a g++ command in such a way because the option
-isystem /usr/include is unnecessary. /usr/include is a default search directory
for the preprocessor. You don't need to tell it to look for system header files there -
either via environment settings, or via a VS Code configuration, or any other way.

See the preprocessor's default search order for C++:-

```<code>$ echo | g++ -x c++ -E -Wp,-v -
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/9
 /usr/include/x86_64-linux-gnu/c++/9
 /usr/include/c++/9/backward
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include           ### <- There it is ###
End of search list.
...
</code>```

So your comment:

I am pretty sure that all the .bashrc exports are already a dirty workaround

is on the money1. But what's worse, the .bashrc setting:

```<code>export CPLUS_INCLUDE_PATH="/usr/include"
</code>```

turns the problem into a persistent feature of your bash profile.

How does the error happen?

The difference that is made to the preprocessor's search order by -isystem /usr/include
can be seen here:

```<code>$ echo | g++ -x c++ -isystem /usr/include -E -Wp,-v -
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"
ignoring duplicate directory "/usr/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include           ### <- Was previously last, now is first ###
 /usr/include/c++/9
 /usr/include/x86_64-linux-gnu/c++/9
 /usr/include/c++/9/backward
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
End of search list.
...
</code>```

As you see, /usr/include is detected now as a duplicated directory in the <...> search
order; the second occurrence - which was last, previously - is deleted and the first occurrence is
retained, coming first in the search order.

Now recall the diagnostic:

```<code>/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
</code>```

The preprocessor directive #include_next is not a standard directive, it is
a GCC extension, documented in the GCC manual: 2.7 Wrapper Headers

Whereas #include <stdlib.h> means:

Include the first file called stdlib.h discovered in the <...> search order, starting from the start

#include_next <stdlib.h> means:

Include the next file called stdlib.h discovered in the <...> search order, starting from the
directory right after that of the file being processed now.

The only directory in the <...> search order that contains stdlib.h is /usr/include. So,
if #include_next <stdlib.h> is encountered by the preprocessor in any file in any directory dir in the <...>
search order, while /usr/include is first in the <...> search order, there can be no directory
later than dir in the <...> search order where <stdlib.h> will be found. And so the error.

#include_next <foobar.h> can only work if the <...> search order places the directory containing
<foobar.h> after the one that contains the file that contains the directive. As a rule of thumb,
just don't mess with the <...> search order.

The problem just discussed was the subject of a regression bug-report raised against GCC 6.0.
As you can see there, the resolution was WONTFIX.

[1] All of your .bashrc exports as posted are, as you suspect, poor practice.

It isn't necessary to tell the preprocessor about any search directories in
its default search order. You can only make things wrong.

Directories that will not be found by default should be specified by
-I dir options specified on the commandline (typically injected via parameters
of the build configuration), so that these non-default options are visible in build logs
for trouble shooting. "Invisible hands" are to be avoided in build systems to the
utmost practical extent.

Body:
System: LMDE4, 64bit, gcc-8.3.0, VS Code

Target File: https://github.com/opencv/opencv/blob/master/samples/cpp/videocapture_camera.cpp

Now as the title says, this starts pissing me off. Nothing is working to fix such a simple issue. And NO I don't want to always use "-I" to tell pretty obvious things to the compiler. Here is what I've done so far.

in c_cpp_properties.json of VS Code:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "/usr/include/"
                ]
            }
        }
    ],
    "version": 4
}

in .bashrc:

#C Include
export C_INCLUDE_PATH="/usr/include"
export C_INCLUDE_PATH=$C_INCLUDE_PATH:"/usr/include/opencv2"

#C++ Include
export CPLUS_INCLUDE_PATH="/usr/include"
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:"/usr/include/c++/8/"
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:"/usr/include/opencv2"

#C/C++ Include
export CPATH="/usr/include"

I am pretty sure that all the .bashrc exports are already a dirty workaround and still I get the following message on compile:

In file included from /usr/include/c++/8/bits/stl_algo.h:59,
                 from /usr/include/c++/8/algorithm:62,
                 from /usr/include/opencv2/core/base.hpp:55,
                 from /usr/include/opencv2/core.hpp:54,
                 from ~/LearnDummy/helloworld.cpp:1:
/usr/include/c++/8/cstdlib:75:15: fatal error: stdlib.h: Datei oder Verzeichnis nicht gefunden
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.

Well fine... stdlib.h is unknown (Jesus!)... find /usr -name stdlib.h gives me

/usr/include/stdlib.h
/usr/include/c++/8/stdlib.h
/usr/include/c++/8/tr1/stdlib.h
/usr/include/x86_64-linux-gnu/bits/stdlib.h
/usr/include/i386-linux-gnu/bits/stdlib.h

In addition VS Code already knows(!) where the file is once I click on "Go to Definition" and still gcc is blind. How do I get realiably rid of this?

Body:
Here is a minimal repro of your problem on Ubuntu 20.04.

$ g++ --version
g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0
...

$ cat main.cpp
#include <cstdlib>

int main ()
{
  return EXIT_SUCCESS;
}

$ export CPLUS_INCLUDE_PATH="/usr/include"; g++ -c main.cpp
In file included from main.cpp:1:
/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
compilation terminated.

Note that export CPLUS_INCLUDE_PATH="/usr/include" here has the same effect as your
identical setting in your .bashrc.

The error does not occur if we remove that environment setting:

$ export CPLUS_INCLUDE_PATH=; g++ -c main.cpp; echo Done
Done

The effect of that environment setting, as per the GCC Manual: 3.21 Environment Variables Affecting GCC
is the same as:

$ g++ -isystem /usr/include -c main.cpp
In file included from main.cpp:1:
/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
compilation terminated.

which accordingly reproduces the error.

The -isystem option is documented in the GCC Manual: 3.16 Options for Directory Search

The general solution to your problem is: Don't run a g++ compilation in any way
that has the effect of g++ ... -isystem /usr/include ...

You can avoid running a g++ command in such a way because the option
-isystem /usr/include is unnecessary. /usr/include is a default search directory
for the preprocessor. You don't need to tell it to look for system header files there -
either via environment settings, or via a VS Code configuration, or any other way.

See the preprocessor's default search order for C++:-

$ echo | g++ -x c++ -E -Wp,-v -
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/9
 /usr/include/x86_64-linux-gnu/c++/9
 /usr/include/c++/9/backward
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include           ### <- There it is ###
End of search list.
...

So your comment:

I am pretty sure that all the .bashrc exports are already a dirty workaround

is on the money1. But what's worse, the .bashrc setting:

export CPLUS_INCLUDE_PATH="/usr/include"

turns the problem into a persistent feature of your bash profile.

How does the error happen?

The difference that is made to the preprocessor's search order by -isystem /usr/include
can be seen here:

$ echo | g++ -x c++ -isystem /usr/include -E -Wp,-v -
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"
ignoring duplicate directory "/usr/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include           ### <- Was previously last, now is first ###
 /usr/include/c++/9
 /usr/include/x86_64-linux-gnu/c++/9
 /usr/include/c++/9/backward
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
End of search list.
...

As you see, /usr/include is detected now as a duplicated directory in the <...> search
order; the second occurrence - which was last, previously - is deleted and the first occurrence is
retained, coming first in the search order.

Now recall the diagnostic:

/usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~

The preprocessor directive #include_next is not a standard directive, it is
a GCC extension, documented in the GCC manual: 2.7 Wrapper Headers

Whereas #include <stdlib.h> means:

Include the first file called stdlib.h discovered in the <...> search order, starting from the start

#include_next <stdlib.h> means:

Include the next file called stdlib.h discovered in the <...> search order, starting from the
directory right after that of the file being processed now.

The only directory in the <...> search order that contains stdlib.h is /usr/include. So,
if #include_next <stdlib.h> is encountered by the preprocessor in any file in any directory dir in the <...>
search order, while /usr/include is first in the <...> search order, there can be no directory
later than dir in the <...> search order where <stdlib.h> will be found. And so the error.

#include_next <foobar.h> can only work if the <...> search order places the directory containing
<foobar.h> after the one that contains the file that contains the directive. As a rule of thumb,
just don't mess with the <...> search order.

The problem just discussed was the subject of a regression bug-report raised against GCC 6.0.
As you can see there, the resolution was WONTFIX.

[1] All of your .bashrc exports as posted are, as you suspect, poor practice.

It isn't necessary to tell the preprocessor about any search directories in
its default search order. You can only make things wrong.

Directories that will not be found by default should be specified by
-I dir options specified on the commandline (typically injected via parameters
of the build configuration), so that these non-default options are visible in build logs
for trouble shooting. "Invisible hands" are to be avoided in build systems to the
utmost practical extent.