问:
How to avoid cross-origin access errors
In my code I am paring some CSS rules with code like below:

```<code>const sheet = style.sheet;
const length = sheet ? sheet.rules.length : 0;

for (let i = 0; i < length; i++) {
        result.push(sheet.rules[i].cssText);
}
</code>```

but it is causing cross-origin access errors (COMPONENT ERROR: CSSStyleSheet.rules getter: Not allowed to access cross-origin stylesheet) since some CSS styles rules have url which points to external site.

```<code>@font-face {
    font-family: "OpenSans";
    src: url("https://my_server.com/fonts/OpenSans.woff2") format("woff2");
}
</code>```

Now it is causing errors and crashing the whole app. I am trying if there is a way to just avoid this (but not fix it).I tried to put the code inside a try catch block, but still triggering the error. Is there a way to make it fail siliently?

答:
The server is configured to not allow cross origin access. A request is considered cross-origin if the website requesting the resource is not the same domain, port or protocol as the webserver providing the resource.

If you want to allow cross-origin access, then the server must implement the CORS protocol, which namely involves 2 things:

Respond to requests with Access-Control http headers, e.g: Access-Control-Allow-Origin: https://myOtherServer.com

Respond to the OPTIONS request with Access-Control headers. The OPTIONS response should have no body.

If you don't have control over the server to set the response, then you either need to request your administrator to configure the server for you or use a proxy server.

Further reading:

https://breautek.com/articles/enabling-cors.html (Disclaimer: I'm the author. It involves around Cordova webviews, but the same concept applies)

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Title: How to avoid cross-origin access errors

Body:
In my code I am paring some CSS rules with code like below:

const sheet = style.sheet;
const length = sheet ? sheet.rules.length : 0;

for (let i = 0; i < length; i++) {
        result.push(sheet.rules[i].cssText);
}

but it is causing cross-origin access errors (COMPONENT ERROR: CSSStyleSheet.rules getter: Not allowed to access cross-origin stylesheet) since some CSS styles rules have url which points to external site.

@font-face {
    font-family: "OpenSans";
    src: url("https://my_server.com/fonts/OpenSans.woff2") format("woff2");
}

Now it is causing errors and crashing the whole app. I am trying if there is a way to just avoid this (but not fix it).I tried to put the code inside a try catch block, but still triggering the error. Is there a way to make it fail siliently?


来源: stackexchange

问:
Is there a jest config that will fail tests on console.warn?
How do I configure jest tests to fail on warnings?</p>

```<code>console.warn('stuff');
// fail test
</code>```

答:
There is a useful npm package that helps you to achieve that: jest-fail-on-console

It's easily configurable.

Install:

```<code>npm i -D jest-fail-on-console
</code>```

Configure:

In a file used in the setupFilesAfterEnv option of Jest, add this code:

```<code>import failOnConsole from 'jest-fail-on-console'

failOnConsole()

// or with options:
failOnConsole({ shouldFailOnWarn: false })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I configure jest tests to fail on warnings?

console.warn('stuff');
// fail test

Body:
There is a useful npm package that helps you to achieve that: jest-fail-on-console

It's easily configurable.

Install:

npm i -D jest-fail-on-console

Configure:

In a file used in the setupFilesAfterEnv option of Jest, add this code:

import failOnConsole from 'jest-fail-on-console'

failOnConsole()

// or with options:
failOnConsole({ shouldFailOnWarn: false })

ContentLicense: CC BY-SA 4.0


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
Even if a and b are automatic-duration Boolean flags, that doesn't mean that an expression like a||b will be evaluated by checking the state of one flag, and then if necessary checking the state of the other.  If a section of code performs:

```<code>x = y+z;
flag1 = (x==0);
... code that uses flag1
</code>```

a compiler could replace that with:

```<code>x = y+z;
if (processor's Z flag was set)
{
... copy of that uses flag1, but where flag is replaced with constant 1
}
else
{
... copy of that uses flag1, but where flag is replaced with constant 0
}
</code>```

Although hardly required to do so, a compiler may base some of its decisions about whether to perform such substitution upon a programmer's choice of whether ot write (flag1 || flag2) or (flag1 | flag2), and many factors may cause the aforementioned substitution to run faster or slower than the original code.

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

Body:
Even if a and b are automatic-duration Boolean flags, that doesn't mean that an expression like a||b will be evaluated by checking the state of one flag, and then if necessary checking the state of the other.  If a section of code performs:

x = y+z;
flag1 = (x==0);
... code that uses flag1

a compiler could replace that with:

x = y+z;
if (processor's Z flag was set)
{
... copy of that uses flag1, but where flag is replaced with constant 1
}
else
{
... copy of that uses flag1, but where flag is replaced with constant 0
}

Although hardly required to do so, a compiler may base some of its decisions about whether to perform such substitution upon a programmer's choice of whether ot write (flag1 || flag2) or (flag1 | flag2), and many factors may cause the aforementioned substitution to run faster or slower than the original code.


问:
Javascript mousemove event
I have this snippet.
I have the div bar on which I act with a listener for the mousemove event. Depending on the coordinates of the mouse, the hello elements move on the x-axis.

How can I, when the mouse is no longer on the bar, that is, outside, the hello elements in the bar, return to the initial position?
For example, while the mouse is over the bar, the hello elements move to the right, and when the mouse is no longer on the bar, they return to their original position.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

bar.addEventListener('mousemove', eff);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}</code>```

Hello

Hello

```

答:
You can add another listener for the mouseleave event and then simply reset the translation to 0px for each layer.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

const reset = function(mouse) {
  layer.forEach(layer => {
    layer.style.transform = `translateX(0px)translateY(0px)`;
  })
};

bar.addEventListener('mousemove', eff);
bar.addEventListener('mouseleave', reset);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}</code>```

Hello

Hello

```

Title: Javascript mousemove event

Body:
I have this snippet.
I have the div bar on which I act with a listener for the mousemove event. Depending on the coordinates of the mouse, the hello elements move on the x-axis.

How can I, when the mouse is no longer on the bar, that is, outside, the hello elements in the bar, return to the initial position?
For example, while the mouse is over the bar, the hello elements move to the right, and when the mouse is no longer on the bar, they return to their original position.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

bar.addEventListener('mousemove', eff);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}

Hello

Hello

Body:
You can add another listener for the mouseleave event and then simply reset the translation to 0px for each layer.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

const reset = function(mouse) {
  layer.forEach(layer => {
    layer.style.transform = `translateX(0px)translateY(0px)`;
  })
};

bar.addEventListener('mousemove', eff);
bar.addEventListener('mouseleave', reset);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}

<div class="bar">
  <div class="hello">
    <h2 id='red' class='layer'>Hello</h2>
    <h2 id='blue' class='layer'>Hello</h2>
  </div>
</div>


问:
turning a Networkx graph into a dictionary
I generate a networkx graph with the following function:

```<code>import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations, groupby
import random
def gnp_random_connected_graph(n, p):
    """
    Generates a random undirected graph, similarly to an Erdős-Rényi
    graph, but enforcing that the resulting graph is connected
    """
    edges = combinations(range(n), 2)
    G = nx.Graph()
    G.add_nodes_from(range(n))
    if p <= 0:
        return G
    if p >= 1:
        return nx.complete_graph(n, create_using=G)
    for _, node_edges in groupby(edges, key=lambda x: x[0]):
        node_edges = list(node_edges)
        random_edge = random.choice(node_edges)
        G.add_edge(*random_edge)
        for e in node_edges:
            if random.random() < p:
                G.add_edge(*e)
    return G
</code>```

I would then like to color the created graph using the following function:

```<code>def coloring(adj, V):

    result = [-1] * V
    result[0] = 0
    available = [False] * V

    for y in range(0, V):
        for x in adj[y]:
            if y not in adj[x]:
                adj[x].append(y)

    for u in range(1, V):
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = True
        cr = 0
        while cr < V:
            if (available[cr] == False):
                break

            cr += 1

        result[u] = cr

        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = False

    for u in range(V):
        print("Vertec", u, " --->  Color", result[u])
</code>```

The problem is that I need to have the networkx graph as a dictionary to then insert it into coloring by doing the following:

```<code>coloring([node for node in g.values()], 5)
</code>```

where g is the graph as dictionary
So how can I turn the networkx graph into a dictionary where the nodes are the keys and the nodes to which each node is connected is it's associated value? Is there a way to do this without converting the networkx graph into a dictionary?

node: don't mind the planarity of the graph, I'll deal with it later on

答:
Not sure if this is what you are looking for, but using a dictionary comprehension might help:

# this creates a dictionary where each node maps to list of neighbours
G_dict = {node: list(G[node]) for node in G}
```

Body:
I generate a networkx graph with the following function:

import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations, groupby
import random
def gnp_random_connected_graph(n, p):
    """
    Generates a random undirected graph, similarly to an Erdős-Rényi
    graph, but enforcing that the resulting graph is connected
    """
    edges = combinations(range(n), 2)
    G = nx.Graph()
    G.add_nodes_from(range(n))
    if p <= 0:
        return G
    if p >= 1:
        return nx.complete_graph(n, create_using=G)
    for _, node_edges in groupby(edges, key=lambda x: x[0]):
        node_edges = list(node_edges)
        random_edge = random.choice(node_edges)
        G.add_edge(*random_edge)
        for e in node_edges:
            if random.random() < p:
                G.add_edge(*e)
    return G

I would then like to color the created graph using the following function:

def coloring(adj, V):

    result = [-1] * V
    result[0] = 0
    available = [False] * V

    for y in range(0, V):
        for x in adj[y]:
            if y not in adj[x]:
                adj[x].append(y)

    for u in range(1, V):
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = True
        cr = 0
        while cr < V:
            if (available[cr] == False):
                break

            cr += 1

        result[u] = cr

        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = False

    for u in range(V):
        print("Vertec", u, " --->  Color", result[u])

The problem is that I need to have the networkx graph as a dictionary to then insert it into coloring by doing the following:

coloring([node for node in g.values()], 5)

where g is the graph as dictionary
So how can I turn the networkx graph into a dictionary where the nodes are the keys and the nodes to which each node is connected is it's associated value? Is there a way to do this without converting the networkx graph into a dictionary?

node: don't mind the planarity of the graph, I'll deal with it later on


问:
Django: While loop doesn't work correctly
i'm buildint a warehouse management application, i have a product model and an placement for each product, every placement has a volume, once i put a product in a placement, the volume of this placement must be reduced. The problem is when the app finds a placement for the product, the placement volume stay the same

models.py

```<code>class Emplacement(models.Model):

    address = models.CharField(max_length=25, blank=True)
    volume = models.DecimalField(max_digits=10, decimal_places=2, null=True)

class Product(models.Model):
    name = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    is_disponible = models.BooleanField(default=False)
    volume = models.DecimalField(max_digits=20, decimal_places=2, null=True)
    emplacement = models.ForeignKey(Emplacement, on_delete=models.CASCADE, null=True)
</code>```

views.py

```<code>def product_detail(request, pk):
    product = get_object_or_404(Product, id=pk)

    if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True
            all_emplacements = Emplacement.objects.all()
            i=1
            while i <= product.quantity:
                for emplacement in all_emplacements:
                    if product.volume < emplacement.volume:
                        product.emplacement = emplacement
                        emplacement.volume -= product.volume
                i+=1
            product.save()
            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)

    context = {
        'product': product,
        'form': form,
    }
    return render(request, 'dashboard/product_detail.html', context)
</code>```

答:
You're not saving the emplacement object.

Try this:

if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True
            all_emplacements = Emplacement.objects.all()
            i=1
            while i <= product.quantity:
                for emplacement in all_emplacements:
                    if product.volume < emplacement.volume:
                        product.emplacement = emplacement
                        emplacement.volume -= product.volume
                        emplacement.save()
                i+=1
            product.save()
            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)
```
<p><strong>Edit</strong><br />
Your Product model indicates that each Product has only ONE Emplacement, since that's where the ForeignKey is.  But, a single Emplacement, can have MANY Product objects.  ForeignKey is a ManyToOne relationship.  When iterating through ALL Emplacements, you are using the SAME Product, and that's why they are all getting the same number in your admin.  I'm guessing, but perhaps what you're after is to find the SINGLE appropriate Emplacement model that the specific Product object has, nad then update just that one.  In other words, NO iterating at all.</p>
<pre class="lang-py prettyprint-override"><code>if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True

            # Here are my proposed changes:
            product.save()                        # Update the product
            emplacement = product.emplacement     # Get the correct Emplacement
            emplacement.volume -= product.volume  # Adjust the volume
            emplacement.save()                    # Save the emplacement

            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)
</code>```

Body:
i'm buildint a warehouse management application, i have a product model and an placement for each product, every placement has a volume, once i put a product in a placement, the volume of this placement must be reduced. The problem is when the app finds a placement for the product, the placement volume stay the same

models.py

class Emplacement(models.Model):

    address = models.CharField(max_length=25, blank=True)
    volume = models.DecimalField(max_digits=10, decimal_places=2, null=True)

class Product(models.Model):
    name = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    is_disponible = models.BooleanField(default=False)
    volume = models.DecimalField(max_digits=20, decimal_places=2, null=True)
    emplacement = models.ForeignKey(Emplacement, on_delete=models.CASCADE, null=True)

views.py

def product_detail(request, pk):
    product = get_object_or_404(Product, id=pk)

    if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True
            all_emplacements = Emplacement.objects.all()
            i=1
            while i <= product.quantity:
                for emplacement in all_emplacements:
                    if product.volume < emplacement.volume:
                        product.emplacement = emplacement
                        emplacement.volume -= product.volume
                i+=1
            product.save()
            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)

    context = {
        'product': product,
        'form': form,
    }
    return render(request, 'dashboard/product_detail.html', context)

Body:
You're not saving the emplacement object.

Try this:

if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True
            all_emplacements = Emplacement.objects.all()
            i=1
            while i <= product.quantity:
                for emplacement in all_emplacements:
                    if product.volume < emplacement.volume:
                        product.emplacement = emplacement
                        emplacement.volume -= product.volume
                        emplacement.save()
                i+=1
            product.save()
            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)

Edit

Your Product model indicates that each Product has only ONE Emplacement, since that's where the ForeignKey is.  But, a single Emplacement, can have MANY Product objects.  ForeignKey is a ManyToOne relationship.  When iterating through ALL Emplacements, you are using the SAME Product, and that's why they are all getting the same number in your admin.  I'm guessing, but perhaps what you're after is to find the SINGLE appropriate Emplacement model that the specific Product object has, nad then update just that one.  In other words, NO iterating at all.

if request.method == 'POST':
        form = ValidateProductForm(request.POST, instance=product)
        if form.is_valid():
            product = form.save(commit=False)
            product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur']
            product.is_disponible = True

            # Here are my proposed changes:
            product.save()                        # Update the product
            emplacement = product.emplacement     # Get the correct Emplacement
            emplacement.volume -= product.volume  # Adjust the volume
            emplacement.save()                    # Save the emplacement

            return redirect('print-barcode', product.id)
    else:
        form = ValidateProductForm(instance=product)


问:
How to make parser decide on which alternative to use, based on the rule in the previous step
I'm using ANTLR 4 to parse a protocol's messages, let's name it 'X'. Before extracting a message's information , I have to check if it complies with X's rules.

Suppose we have to parse X's 'FOO' message that follows the following rules:

Message starts with the 'messageIdentifier' that consists of the 3-letter reserved word FOO.

Message contains 5 fields, of which the first 2 are mandatory (must be included) and the rest 3 are optional (can be not included).

Message's fields are separated by the character '/'. If there is no information in a field (that means that the field is optional and is omitted) the '/' character must be preserved. Optional fields and their associated filed separators '/' at the end of the message may be omitted where no further information within the message is reported.

A message can expand in multiple lines. Each line must have at least one non-empty field (mandatory or optional). Moreover, each line must start with a '/' character and end with a non-empty field following a '\n' character. Exception is the first line that always starts with the reserved word FOO.

Each message's field also has its own rules regarding the accepted tokens, which will be shown in the grammar below.

Sample examples of valid FOO messages:

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2\n

/OPT 1\n

/HELLO\n

/100\n

FOO/MANDATORY_1/MANDATORY2\n

FOO/MANDATORY_1/MANDATORY2//HELLO/100\n

FOO/MANDATORY_1/MANDATORY2///100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1\n

FOO/MANDATORY_1/MANDATORY2
///100\n

Sample examples of non-valid FOO messages:

FOO\n

/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/\n

MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1//\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/\n

/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100

Below follows the grammar for the above message:

```<code>grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? optionalField_3 ;

optionalField_3 : '/' field_3 NL? optionalField_4
                | '/' optionalField_4
                | optionalField_4
                ;

optionalField_4 : '/' field_4 NL? optionalField_5
                | '/' optionalField_5
                | optionalField_5
                ;

optionalField_5 : '/' field_5 NL?
                | NL
                ;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;

</code>```

The above grammar parses correctly any input that complies with FOO message's rules.
The problem resides in parsing a line that ends with the '/' character, which according to the protocol's FOO message's rules is an invalid input.
I understand that the second alternatives of rules 'optionalField_3', 'optionalField_4' and 'optionalField_5' lead to this behavior but I can't figure out how to make a rule for this.
Somehow I need the parser to remember that he came to 'optionalField_5' rule after seeing a non-omitted field in the previous rule, which if I am not mistaken can't be done in ANTLR as I can't check from which alternative of the previous rule I reached the current rule.

Is there a way to make the parser 'remember' this by some explicit option-rule? Or does my grammar need to be rearranged and if yes how?

答:
This grammar accepts all examples, character for character copied/pasted from your post, and flags a parse error all "non-valid FOO messages".

```<code>grammar X;
file_ : s* EOF ;
s : FOO '/' f1 '/' f2 (
    | NL? '/' f3
    | NL? ('/' f3 NL? | '/' ) '/' f4
    | NL? ('/' f3 NL? | '/' ) ('/' f4 NL? | '/') '/' f5
 ) NL;
f1 : (A | N | B | S)+ ;
f2 : (A | N | B)+ ;
f3 : (A | N | B)+ ;
f4 : A+ ;
f5 : N+ ;
FOO: 'FOO';
A : [A-Z]+ ;
N : [0-9]+ ;
B : ' ';
S : [*&@#\-_<>?!]+ ;
NL : '\r'? '\n' ;
</code>```

One can easily refactor this with folds and groupings.

In your previous grammar, lexer symbol B was marked as "skip". Skipped symbols do not appear on any token stream, and they should not be used directly on the right-hand side of a parser rule (see field_1 from your original grammar). It is innocuous because it is alted with other symbols, i.e. field_3:(A|N|B)+; will operate the same as field_3:(A|N)+;, but the rule field_3:(A|N|B)+; may be misleading to others because B will never appear in the parse tree. I felt that you wanted to include spaces in the fields, because perhaps you would want to compute the text for a field. Therefore, I changed the rule for B to appear as a token.

#5 from "non-valid FOO messages" is exactly the same character for character of #1 from "valid FOO messages", which you can see here:

```<code>#1: FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n
#5: FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n
</code>```

I don't understand your comment "this allows the optional fields of the FOO message to come in any order". The grammar here and the previous grammar I mentioned in the comments force field3 to occur before field4, which occurs before field5. There is no way that field5 could occur before a field3: the requisite number of '/' must appear before field5. Fields can be empty (see #4 of "valid FOO messages"). To handle that, the field specified is a grouping, e.g., ('/' f3 NL? | '/' ). For this grouping, the only sentential forms are "/", "/f3", "/f3\n". Note, this grouping can only occur with a succeeding field, so it is impossible for two "\n" to be next to each other.

The other way to approach this is to use semantic predicates or evaluate the semantic equations after the entire parse.

If there are many more fields, then you will likely not want to add alts for f6, f7, ...., f10000. In that case, I would suggest that you allow an arbitrary type for each field in the parse:

```<code>s : FOO '/' f1 '/' f2 (
    | NL? ('/' f NL? | '/' )* '/' f
 ) NL;
</code>```

and validate the semantics afterwards.

Body:
I'm using ANTLR 4 to parse a protocol's messages, let's name it 'X'. Before extracting a message's information , I have to check if it complies with X's rules.

Suppose we have to parse X's 'FOO' message that follows the following rules:

Message starts with the 'messageIdentifier' that consists of the 3-letter reserved word FOO.

Message contains 5 fields, of which the first 2 are mandatory (must be included) and the rest 3 are optional (can be not included).

Message's fields are separated by the character '/'. If there is no information in a field (that means that the field is optional and is omitted) the '/' character must be preserved. Optional fields and their associated filed separators '/' at the end of the message may be omitted where no further information within the message is reported.

A message can expand in multiple lines. Each line must have at least one non-empty field (mandatory or optional). Moreover, each line must start with a '/' character and end with a non-empty field following a '\n' character. Exception is the first line that always starts with the reserved word FOO.

Each message's field also has its own rules regarding the accepted tokens, which will be shown in the grammar below.

Sample examples of valid FOO messages:

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2\n

/OPT 1\n

/HELLO\n

/100\n

FOO/MANDATORY_1/MANDATORY2\n

FOO/MANDATORY_1/MANDATORY2//HELLO/100\n

FOO/MANDATORY_1/MANDATORY2///100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1\n

FOO/MANDATORY_1/MANDATORY2
///100\n

Sample examples of non-valid FOO messages:

FOO\n

/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/\n

MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1//\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/\n

/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100

Below follows the grammar for the above message:

grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? optionalField_3 ;

optionalField_3 : '/' field_3 NL? optionalField_4
                | '/' optionalField_4
                | optionalField_4
                ;

optionalField_4 : '/' field_4 NL? optionalField_5
                | '/' optionalField_5
                | optionalField_5
                ;

optionalField_5 : '/' field_5 NL?
                | NL
                ;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;

The above grammar parses correctly any input that complies with FOO message's rules.
The problem resides in parsing a line that ends with the '/' character, which according to the protocol's FOO message's rules is an invalid input.
I understand that the second alternatives of rules 'optionalField_3', 'optionalField_4' and 'optionalField_5' lead to this behavior but I can't figure out how to make a rule for this.
Somehow I need the parser to remember that he came to 'optionalField_5' rule after seeing a non-omitted field in the previous rule, which if I am not mistaken can't be done in ANTLR as I can't check from which alternative of the previous rule I reached the current rule.

Is there a way to make the parser 'remember' this by some explicit option-rule? Or does my grammar need to be rearranged and if yes how?

Body:
This grammar accepts all examples, character for character copied/pasted from your post, and flags a parse error all "non-valid FOO messages".

grammar X;
file_ : s* EOF ;
s : FOO '/' f1 '/' f2 (
    | NL? '/' f3
    | NL? ('/' f3 NL? | '/' ) '/' f4
    | NL? ('/' f3 NL? | '/' ) ('/' f4 NL? | '/') '/' f5
 ) NL;
f1 : (A | N | B | S)+ ;
f2 : (A | N | B)+ ;
f3 : (A | N | B)+ ;
f4 : A+ ;
f5 : N+ ;
FOO: 'FOO';
A : [A-Z]+ ;
N : [0-9]+ ;
B : ' ';
S : [*&@#\-_<>?!]+ ;
NL : '\r'? '\n' ;

One can easily refactor this with folds and groupings.

In your previous grammar, lexer symbol B was marked as "skip". Skipped symbols do not appear on any token stream, and they should not be used directly on the right-hand side of a parser rule (see field_1 from your original grammar). It is innocuous because it is alted with other symbols, i.e. field_3:(A|N|B)+; will operate the same as field_3:(A|N)+;, but the rule field_3:(A|N|B)+; may be misleading to others because B will never appear in the parse tree. I felt that you wanted to include spaces in the fields, because perhaps you would want to compute the text for a field. Therefore, I changed the rule for B to appear as a token.

#5 from "non-valid FOO messages" is exactly the same character for character of #1 from "valid FOO messages", which you can see here:

#1: FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n
#5: FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

I don't understand your comment "this allows the optional fields of the FOO message to come in any order". The grammar here and the previous grammar I mentioned in the comments force field3 to occur before field4, which occurs before field5. There is no way that field5 could occur before a field3: the requisite number of '/' must appear before field5. Fields can be empty (see #4 of "valid FOO messages"). To handle that, the field specified is a grouping, e.g., ('/' f3 NL? | '/' ). For this grouping, the only sentential forms are "/", "/f3", "/f3\n". Note, this grouping can only occur with a succeeding field, so it is impossible for two "\n" to be next to each other.

The other way to approach this is to use semantic predicates or evaluate the semantic equations after the entire parse.

If there are many more fields, then you will likely not want to add alts for f6, f7, ...., f10000. In that case, I would suggest that you allow an arbitrary type for each field in the parse:

s : FOO '/' f1 '/' f2 (
    | NL? ('/' f NL? | '/' )* '/' f
 ) NL;

and validate the semantics afterwards.


问:
Problem with position:absolute on input
I have this code :

```<code><div class="areaButton">
    <input type="submit" value="Add">
</div>

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}
</code>```

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?

答: Setting position:absolute removes the element from the document flow, meaning it basically doesn't occupy any space. Since this is the only element in the div, and there is no height width or padding on it, it doesn't take up any space either, so you cannot see the background.

Title: Problem with position:absolute on input

Body:
I have this code :

    <input type="submit" value="Add">

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?


问:
How to "merge" 2 VR180 video files to get a 360 video (2xVR180) output with ffmpeg?
I'm wondering how to actually use ffmpeg to create a 2xVR180 video file from 2 different VR180 videos.
That's to say, on the front side, a stereoscopic 3D video, and on the back side, another stereoscopic 3D video.

Videos are taken with an Insta360 EVO in 3D mode, so I can either deal with 4 video files (2 INSV files for the left eye and other 2 INSV files for the right eye), o directly with the 2 stitched HEVC/MP4 files.

I know the result won't be a 360 3D stereoscopic video, that's why I'm talking about "2xVR180".

Thank you for your help

答:
I finally found a solution!

The "algorithm" is :

Separate left eye from right eye of both video files

Join both left eyes

Join both right eyes

Join left eyes with right eyes

Resize the video

The resulting is something like :

```<code>Front left eye | Back left eye | Front right eye | Back right eye
</code>```

To get this using ffmpeg, i used the following syntax

```<code>ffmpeg -i front_vr180.mp4 -i back_vr180.mp4 -filter_complex "[0:v]crop=2880:2880:0:0[aleft];[0:v]crop=2880:2880:iw-2880:0[aright];[1:v]crop=2880:2880:0:0[bleft];[1:v]crop=2880:2880:iw-2880:0[bright];[aleft][bleft]hstack=inputs=2[left];[aright][bright]hstack=inputs=2[right];[left][right]hstack=inputs=2[full];[full]scale=7680:-1[v]" -map "[v]" -b:v 200M -preset slow -crf 6 full_360VR_test.mp4
</code>```

I'm chaining the crop filter (eye separation) with the hstack filter (video concatenation) to finally resize the video thanks to the scale filter.

With more details:

-i front_vr180.mp4 : The VR180 video file I want to see in front of me

-i back_vr180.mp4 : The VR180 video file I want to see behind me

-filter_complex : a chain of filters I have to apply to get this working

[0:v]crop=2880:2880:0:0[aleft]:

[0:v] means "First input, video channel" and placed before a filter means that's the input of this filter

crop=2880:2880:0:0[aleft] means the input will be cropped to result in a 2880x2880 size from (0,0) (top left corner). In other words, the left square of the first video (video A or front). [aleft] is just a label to identify the result of this filter (left part of video A)

Same thing to get the right part of the A video (aright), and both left and right parts of the B video

[aleft][bleft]hstack=inputs=2[left] That means I will concatenate, side by side, both left eye videos into one unique [left] video. If aleft and bleft were 2880x2880 videos, [left] will be a 5760x2880 video.

Same thing with the right eye to get [right] as a 5760x2880 video.

[left][right]hstack=inputs=2[full] : Same logic as before, [left] and [right] are put together into [full], side by side, to achieve the 3D SBS effect.

At this point, we would have a 2xVR180 video, but size is too huge (11520x2880) and need to be scale down (for instance, 8K).  This is done with [full]scale=7680:-1[v]. 7680 is the width, -1 as height means we let ffmpeg determinate the correct height to keep ratio aspect. The result of this scale down, [v] will be 7680x1920.

-map "[v]" : means only the video channel is required

-b:v 200M : this option sets the bitrate. Value depends on the input video files... More bitrate means more details, but if the input have a low bitrate, ffmpeg won't invent details. I chose a bitrate = sum(input bitrates).

crf 6 : CRF means constant rate factor. 0 = lossless, 51 = worst quality, using x264.

preset slow: well, I think the ffmepg documentation would be better than me to explain this. More slower, better quality :)

Body:
I finally found a solution!

The "algorithm" is :

Separate left eye from right eye of both video files

Join both left eyes

Join both right eyes

Join left eyes with right eyes

Resize the video

The resulting is something like :

Front left eye | Back left eye | Front right eye | Back right eye

To get this using ffmpeg, i used the following syntax

ffmpeg -i front_vr180.mp4 -i back_vr180.mp4 -filter_complex "[0:v]crop=2880:2880:0:0[aleft];[0:v]crop=2880:2880:iw-2880:0[aright];[1:v]crop=2880:2880:0:0[bleft];[1:v]crop=2880:2880:iw-2880:0[bright];[aleft][bleft]hstack=inputs=2[left];[aright][bright]hstack=inputs=2[right];[left][right]hstack=inputs=2[full];[full]scale=7680:-1[v]" -map "[v]" -b:v 200M -preset slow -crf 6 full_360VR_test.mp4

I'm chaining the crop filter (eye separation) with the hstack filter (video concatenation) to finally resize the video thanks to the scale filter.

With more details:

-i front_vr180.mp4 : The VR180 video file I want to see in front of me

-i back_vr180.mp4 : The VR180 video file I want to see behind me

-filter_complex : a chain of filters I have to apply to get this working

[0:v]crop=2880:2880:0:0[aleft]:

[0:v] means "First input, video channel" and placed before a filter means that's the input of this filter

crop=2880:2880:0:0[aleft] means the input will be cropped to result in a 2880x2880 size from (0,0) (top left corner). In other words, the left square of the first video (video A or front). [aleft] is just a label to identify the result of this filter (left part of video A)

Same thing to get the right part of the A video (aright), and both left and right parts of the B video

[aleft][bleft]hstack=inputs=2[left] That means I will concatenate, side by side, both left eye videos into one unique [left] video. If aleft and bleft were 2880x2880 videos, [left] will be a 5760x2880 video.

Same thing with the right eye to get [right] as a 5760x2880 video.

[left][right]hstack=inputs=2[full] : Same logic as before, [left] and [right] are put together into [full], side by side, to achieve the 3D SBS effect.

At this point, we would have a 2xVR180 video, but size is too huge (11520x2880) and need to be scale down (for instance, 8K).  This is done with [full]scale=7680:-1[v]. 7680 is the width, -1 as height means we let ffmpeg determinate the correct height to keep ratio aspect. The result of this scale down, [v] will be 7680x1920.

-map "[v]" : means only the video channel is required

-b:v 200M : this option sets the bitrate. Value depends on the input video files... More bitrate means more details, but if the input have a low bitrate, ffmpeg won't invent details. I chose a bitrate = sum(input bitrates).

crf 6 : CRF means constant rate factor. 0 = lossless, 51 = worst quality, using x264.

preset slow: well, I think the ffmepg documentation would be better than me to explain this. More slower, better quality :)


问:
How can I show the number of items inside a shopping cart?
I have a shopping cart in one of my projects about e-commerces, and I want to show in the side of the cart icon the number of items on it. There's so many ways to make it, but honestly my brain is so blocked right now, and I need help...

I thought about looping through the array to get the "cant" key value of each object within it and then adding them together to display them next to the shopping cart, but I still don't know how to do it yet...

答:
You just got to loop through and keep a counter.</p>
```<code>var counter = 0;
cartArray.forEach(i => {
   counter += i.cant;
});
return counter;
</code>```

Body:
You just got to loop through and keep a counter.

var counter = 0;
cartArray.forEach(i => {
   counter += i.cant;
});
return counter;


问:
How to use `remotes::install_gitlab` to install from a branch?
I wanted to install the interp package from the "spline" branch in the Gitlab repository at https://gitlab.aau.at/agebhard/interp .  When I select that branch on the web page, the URL changes to https://gitlab.aau.at/agebhard/interp/-/tree/spline .  However, using that URL in the obvious way gives an error:

remotes::install_gitlab("agebhard/interp",
                        subdir = "-/tree/spline",
                        host = "https://gitlab.aau.at")
#> Error: Failed to install 'unknown package' from GitLab:
#>   cannot open URL 'https://gitlab.aau.at/api/v4/projects/agebhard%2Finterp/repository/files/-%2Ftree%2Fspline%2FDESCRIPTION/raw?ref=HEAD'
```

Created on 2022-02-09 by the reprex package (v2.0.1.9000)

I ended up cloning the whole repository and then using git branch to select the branch, and installing locally.  But surely remotes::install_gitlab() would offer a way to install directly from a branch?  The install_github() function has ref to select a branch or tag, but I don't see an equivalent of that argument in install_gitlab().

答:
Thanks to @danlooo's answer and some debuggging, I worked out the right way to use install_gitlab itself.  You just put the branch at the end of the name with an @ sign, e.g.

```<code>remotes::install_gitlab("agebhard/interp@spline",
                        host = "gitlab.aau.at")
</code>```

Body:
I wanted to install the interp package from the "spline" branch in the Gitlab repository at https://gitlab.aau.at/agebhard/interp .  When I select that branch on the web page, the URL changes to https://gitlab.aau.at/agebhard/interp/-/tree/spline .  However, using that URL in the obvious way gives an error:

remotes::install_gitlab("agebhard/interp",
                        subdir = "-/tree/spline",
                        host = "https://gitlab.aau.at")
#> Error: Failed to install 'unknown package' from GitLab:
#>   cannot open URL 'https://gitlab.aau.at/api/v4/projects/agebhard%2Finterp/repository/files/-%2Ftree%2Fspline%2FDESCRIPTION/raw?ref=HEAD'

Created on 2022-02-09 by the reprex package (v2.0.1.9000)

I ended up cloning the whole repository and then using git branch to select the branch, and installing locally.  But surely remotes::install_gitlab() would offer a way to install directly from a branch?  The install_github() function has ref to select a branch or tag, but I don't see an equivalent of that argument in install_gitlab().

Body:
Thanks to @danlooo's answer and some debuggging, I worked out the right way to use install_gitlab itself.  You just put the branch at the end of the name with an @ sign, e.g.

remotes::install_gitlab("agebhard/interp@spline",
                        host = "gitlab.aau.at")


问:
How to run different computer vision programmes with different media pipe versions on PyCharm?
I have several media pipe projects. However, some of them require different media pipe versions (older or newer). Is there a way to run all the projects in a single version? if not, how can we shift between the versions without uninstalling it and reinstall the required version? I am using PyCharm IDE.</p>

答: In case you still have this error, I have solved it by using two different IDEs and installing different media pipe versions on those IDEs separately</p>


问:
dataframe groupby or slice based on conditions
I have a dataframe like this:

```<code>df_test = pd.DataFrame({'ID1':['A','A','A','B','B','A','B','B','B','B','A','A','A','A'],
                       'ID2':[1,2,3,1,1,1,6,7,1,2,2,5,6,1]})
df_test
</code>```

The result dataframe would be like this ('ID1' was group/slice by the value, for example, if A was repeated at least 2 times, these 2 rows will be treated as a group and calculate the mean of ID2. it's similar to 'B', but only if 'B' repeat at least 3 times):

```<code>df_result = pd.DataFrame({'ID1':['A1','B1','A2'],
                       'mean_ID2':[2,4,3.5]})
df_result
</code>```

答:
you can use run length encoding to figure out the rows to keep based on number of elements in consecutive runs. in the next step, group by consecutive runs again and take mean.</p>
```<code>import pdrle
r = pdrle.encode(df_test.ID1)
r["chk"] = ((r.vals == "A") & (r.runs >=2)) | ((r.vals == "B") & (r.runs >= 3))
df2 = df_test[pdrle.decode(r.chk, r.runs)]
df2.groupby(pdrle.get_id(df2.ID1)).agg({"ID1": "first", "ID2": "mean"})
#     ID1     ID2
# ID1
# 0     A     2.0
# 1     B     4.0
# 2     A     3.5
</code>```

Body:
I have a dataframe like this:

df_test = pd.DataFrame({'ID1':['A','A','A','B','B','A','B','B','B','B','A','A','A','A'],
                       'ID2':[1,2,3,1,1,1,6,7,1,2,2,5,6,1]})
df_test

The result dataframe would be like this ('ID1' was group/slice by the value, for example, if A was repeated at least 2 times, these 2 rows will be treated as a group and calculate the mean of ID2. it's similar to 'B', but only if 'B' repeat at least 3 times):

df_result = pd.DataFrame({'ID1':['A1','B1','A2'],
                       'mean_ID2':[2,4,3.5]})
df_result

Body:
you can use run length encoding to figure out the rows to keep based on number of elements in consecutive runs. in the next step, group by consecutive runs again and take mean.

import pdrle
r = pdrle.encode(df_test.ID1)
r["chk"] = ((r.vals == "A") & (r.runs >=2)) | ((r.vals == "B") & (r.runs >= 3))
df2 = df_test[pdrle.decode(r.chk, r.runs)]
df2.groupby(pdrle.get_id(df2.ID1)).agg({"ID1": "first", "ID2": "mean"})
#     ID1     ID2
# ID1
# 0     A     2.0
# 1     B     4.0
# 2     A     3.5


问:
Replacing column values in a pandas DataFrame
I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.

I have tried the following:

```<code>w['female']['female']='1'
w['female']['male']='0'
</code>```

But receive the exact same copy of the previous results.

I would ideally like to get some output which resembles the following loop element-wise.

```<code>if w['female'] =='female':
    w['female'] = '1';
else:
    w['female'] = '0';
</code>```

I've looked through the gotchas documentation (http://pandas.pydata.org/pandas-docs/stable/gotchas.html) but cannot figure out why nothing happens.

Any help will be appreciated.

答:
To answer the question more generically so it applies to more use cases than just what the OP asked, consider this solution. I used jfs's solution solution to help me. Here, we create two functions that help feed each other and can be used whether you know the exact replacements or not.

import numpy as np
import pandas as pd

class Utility:

    @staticmethod
    def rename_values_in_column(column: pd.Series, name_changes: dict = None) -> pd.Series:
        """
        Renames the distinct names in a column. If no dictionary is provided for the exact name changes, it will default
        to <column_name>_count. Ex. female_1, female_2, etc.

        :param column: The column in your dataframe you would like to alter.
        :param name_changes: A dictionary of the old values to the new values you would like to change.
        Ex. {1234: "User A"} This would change all occurrences of 1234 to the string "User A" and leave the other values as they were.
        By default, this is an empty dictionary.
        :return: The same column with the replaced values
        """
        name_changes = name_changes if name_changes else {}
        new_column = column.replace(to_replace=name_changes)
        return new_column

    @staticmethod
    def create_unique_values_for_column(column: pd.Series, except_values: list = None) -> dict:
        """
        Creates a dictionary where the key is the existing column item and the value is the new item to replace it.
        The returned dictionary can then be passed the pandas rename function to rename all the distinct values in a
        column.
        Ex. column ["statement"]["I", "am", "old"] would return
        {"I": "statement_1", "am": "statement_2", "old": "statement_3"}

        If you would like a value to remain the same, enter the values you would like to stay in the except_values.
        Ex. except_values = ["I", "am"]
        column ["statement"]["I", "am", "old"] would return
        {"old", "statement_3"}

        :param column: A pandas Series for the column with the values to replace.
        :param except_values: A list of values you do not want to have changed.
        :return: A dictionary that maps the old values their respective new values.
        """
        except_values = except_values if except_values else []
        column_name = column.name
        distinct_values = np.unique(column)
        name_mappings = {}
        count = 1
        for value in distinct_values:
            if value not in except_values:
                name_mappings[value] = f"{column_name}_{count}"
                count += 1
        return name_mappings
```
<p>For the OP's use case, it is simple enough to just use</p>
```w["female"] = Utility.rename_values_in_column(w["female"], name_changes = {"female": 0, "male":1}
```
<p>However, it is not always so easy to know all of the different unique values within a data frame that you may want to rename. In my case, the string values for a column are hashed values so they hurt the readability. What I do instead is replace those hashed values with more readable strings thanks to the <code>create_unique_values_for_column</code> function.</p>
<pre class="lang-py prettyprint-override"><code>df["user"] = Utility.rename_values_in_column(
    df["user"],
    Utility.create_unique_values_for_column(df["user"])
)
</code>```

This will changed my user column values from ["1a2b3c", "a12b3c","1a2b3c"] to ["user_1", "user_2", "user_1]. Much easier to compare, right?

Body:
I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.

I have tried the following:

w['female']['female']='1'
w['female']['male']='0'

But receive the exact same copy of the previous results.

I would ideally like to get some output which resembles the following loop element-wise.

if w['female'] =='female':
    w['female'] = '1';
else:
    w['female'] = '0';

I've looked through the gotchas documentation (http://pandas.pydata.org/pandas-docs/stable/gotchas.html) but cannot figure out why nothing happens.

Any help will be appreciated.

Body:
To answer the question more generically so it applies to more use cases than just what the OP asked, consider this solution. I used jfs's solution solution to help me. Here, we create two functions that help feed each other and can be used whether you know the exact replacements or not.

import numpy as np
import pandas as pd

class Utility:

    @staticmethod
    def rename_values_in_column(column: pd.Series, name_changes: dict = None) -> pd.Series:
        """
        Renames the distinct names in a column. If no dictionary is provided for the exact name changes, it will default
        to <column_name>_count. Ex. female_1, female_2, etc.

        :param column: The column in your dataframe you would like to alter.
        :param name_changes: A dictionary of the old values to the new values you would like to change.
        Ex. {1234: "User A"} This would change all occurrences of 1234 to the string "User A" and leave the other values as they were.
        By default, this is an empty dictionary.
        :return: The same column with the replaced values
        """
        name_changes = name_changes if name_changes else {}
        new_column = column.replace(to_replace=name_changes)
        return new_column

    @staticmethod
    def create_unique_values_for_column(column: pd.Series, except_values: list = None) -> dict:
        """
        Creates a dictionary where the key is the existing column item and the value is the new item to replace it.
        The returned dictionary can then be passed the pandas rename function to rename all the distinct values in a
        column.
        Ex. column ["statement"]["I", "am", "old"] would return
        {"I": "statement_1", "am": "statement_2", "old": "statement_3"}

        If you would like a value to remain the same, enter the values you would like to stay in the except_values.
        Ex. except_values = ["I", "am"]
        column ["statement"]["I", "am", "old"] would return
        {"old", "statement_3"}

        :param column: A pandas Series for the column with the values to replace.
        :param except_values: A list of values you do not want to have changed.
        :return: A dictionary that maps the old values their respective new values.
        """
        except_values = except_values if except_values else []
        column_name = column.name
        distinct_values = np.unique(column)
        name_mappings = {}
        count = 1
        for value in distinct_values:
            if value not in except_values:
                name_mappings[value] = f"{column_name}_{count}"
                count += 1
        return name_mappings

For the OP's use case, it is simple enough to just use

w["female"] = Utility.rename_values_in_column(w["female"], name_changes = {"female": 0, "male":1}

However, it is not always so easy to know all of the different unique values within a data frame that you may want to rename. In my case, the string values for a column are hashed values so they hurt the readability. What I do instead is replace those hashed values with more readable strings thanks to the create_unique_values_for_column function.

df["user"] = Utility.rename_values_in_column(
    df["user"],
    Utility.create_unique_values_for_column(df["user"])
)

This will changed my user column values from ["1a2b3c", "a12b3c","1a2b3c"] to ["user_1", "user_2", "user_1]. Much easier to compare, right?


问:
Use IntersectionObserver To Trigger Event AFTER Element Completely Passes Threshold
I have a few IntersectionObserver's set up. observer toggles new boxes to be made as the user scrolls down the page. lastBoxObserver loads new boxes as this continuous scrolling happens.

What I would like to do is change the color of a box once it leaves the threshold set in the first observer (observer - whose threshold is set to 1). So, once box 12 enters the viewport, it passes through the observer, and once it has completely passed outside of the threshold for this observer and box 13 enters the observer, box 12's background changes from green to orange, perhaps.

Is there a way to make this happen? Maybe by adding an additional observer, or adding code to observer? Any help is greatly appreciated.

Codepen: https://codepen.io/jon424/pen/NWwReEJ

JavaScript

 const boxes = document.querySelectorAll(".box");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) observer.unobserve(entry.target);
        });
      },
      {
        threshold: 1,
      }
    );

    const lastBoxObserver = new IntersectionObserver((entries) => {
      const lastBox = entries[0];
      if (!lastBox.isIntersecting) return;
      loadNewBoxes();
      lastBoxObserver.unobserve(lastBox.target);
      lastBoxObserver.observe(document.querySelector(".box:last-child"));
    }, {});

    lastBoxObserver.observe(document.querySelector(".box:last-child"));

    boxes.forEach((box) => {
      observer.observe(box);
    });

    const boxContainer = document.querySelector(".container");

    function loadNewBoxes() {
      for (let i = 0; i < 1000; i++) {
        const box = document.createElement("div");
        box.textContent = `${i + 1}`;
        box.classList.add("box");
        observer.observe(box);
        boxContainer.appendChild(box);
      }
    }

```
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code>   <div class="container">
      <div class="box">0</div>
    </div>
</code>```

CSS

 .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .box {
      background: green;
      color: white;
      font-size: 4rem;
      text-align: center;
      margin: auto;
      height: 100px;
      width: 100px;
      border: 1px solid black;
      border-radius: 0.25rem;
      padding: 0.5rem;
      transform: translateX(100px);
      opacity: 0;
      transition: 150ms;
    }

    .box.show {
      transform: translateX(0);
      opacity: 1;
    }

    .box.show.more {
      background-color: orange;
    }
```

答:
You just need to add color change logic in your first observer.

I tested with the following changes to your code,

In css, change .box.show.more to -

```<code>.box.more {
      background-color: orange;
}
</code>```

In javascript -

```<code>const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) {
            observer.unobserve(entry.target);

            if(entry.target.textContent === '13')
                      entry.target.previousSibling.classList.toggle('more');
          }
        });
      },
      {
        threshold: 1,
      }
    );
</code>```

As you can see, the only change is that I added this part -

```<code>if(entry.target.textContent === '13')
    entry.target.previousSibling.classList.toggle('more');
</code>```

I also changed the number of new div to add from 1000 to 20 for easy test.

If you want to change box 12 color as soon as box 13 enters viewport, you can simply change "threshold" from 1 to 0.

Body:
I have a few IntersectionObserver's set up. observer toggles new boxes to be made as the user scrolls down the page. lastBoxObserver loads new boxes as this continuous scrolling happens.

What I would like to do is change the color of a box once it leaves the threshold set in the first observer (observer - whose threshold is set to 1). So, once box 12 enters the viewport, it passes through the observer, and once it has completely passed outside of the threshold for this observer and box 13 enters the observer, box 12's background changes from green to orange, perhaps.

Is there a way to make this happen? Maybe by adding an additional observer, or adding code to observer? Any help is greatly appreciated.

Codepen: https://codepen.io/jon424/pen/NWwReEJ

JavaScript

 const boxes = document.querySelectorAll(".box");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) observer.unobserve(entry.target);
        });
      },
      {
        threshold: 1,
      }
    );

    const lastBoxObserver = new IntersectionObserver((entries) => {
      const lastBox = entries[0];
      if (!lastBox.isIntersecting) return;
      loadNewBoxes();
      lastBoxObserver.unobserve(lastBox.target);
      lastBoxObserver.observe(document.querySelector(".box:last-child"));
    }, {});

    lastBoxObserver.observe(document.querySelector(".box:last-child"));

    boxes.forEach((box) => {
      observer.observe(box);
    });

    const boxContainer = document.querySelector(".container");

    function loadNewBoxes() {
      for (let i = 0; i < 1000; i++) {
        const box = document.createElement("div");
        box.textContent = `${i + 1}`;
        box.classList.add("box");
        observer.observe(box);
        boxContainer.appendChild(box);
      }
    }

HTML

0

CSS

 .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .box {
      background: green;
      color: white;
      font-size: 4rem;
      text-align: center;
      margin: auto;
      height: 100px;
      width: 100px;
      border: 1px solid black;
      border-radius: 0.25rem;
      padding: 0.5rem;
      transform: translateX(100px);
      opacity: 0;
      transition: 150ms;
    }

    .box.show {
      transform: translateX(0);
      opacity: 1;
    }

    .box.show.more {
      background-color: orange;
    }

Body:
You just need to add color change logic in your first observer.

I tested with the following changes to your code,

In css, change .box.show.more to -

.box.more {
      background-color: orange;
}

In javascript -

const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) {
            observer.unobserve(entry.target);

            if(entry.target.textContent === '13')
                      entry.target.previousSibling.classList.toggle('more');
          }
        });
      },
      {
        threshold: 1,
      }
    );

As you can see, the only change is that I added this part -

if(entry.target.textContent === '13')
    entry.target.previousSibling.classList.toggle('more');

I also changed the number of new div to add from 1000 to 20 for easy test.

If you want to change box 12 color as soon as box 13 enters viewport, you can simply change "threshold" from 1 to 0.


问:
How to make if/else chain with lists more efficient
I have a huge dataframe with ~100,000 rows. I have this code but it is taking way too long to execute. Is there any way to make this more efficient?</p>
```<code>df["Grade Band"] = ""
k5 = ["0","1","2","3","4","5"]
ms = ["6", "7" ,"8"]
hs = ["9","10","11","12"]

for x in df["Grade Roll"]:
    if x == "Other":
        df["Grade Band"] == "Undefined"
    elif x in k5:
        df["Grade Band"] == "K5"
    elif x in ms:
        df["Grade Band"] == "MS"
    elif x in hs:
            df["Grade Band"] == "HS"
</code>```

答:
This should be pretty fast:

```<code>df.loc[df["Grade Roll"] == "Other", "Grade Roll"] = "Undefined"
df.loc[df["Grade Roll"].isin(k5), "Grade Roll"] = "K5"
df.loc[df["Grade Roll"].isin(ms), "Grade Roll"] = "MS"
df.loc[df["Grade Roll"].isin(hs), "Grade Roll"] = "HS"
</code>```

If you wanted it to be less repetitive, you could store your arrays in a dict:

```<code>d = {
    "K5": ["0","1","2","3","4","5"],
    "MS": ["6", "7" ,"8"],
    "HS": ["9","10","11","12"],
    "Undefined": ["Other"]
}

for k, v in d.items():
    df.loc[df["Grade Roll"].isin(v), "Grade Roll"] = k
</code>```

Body:
I have a huge dataframe with ~100,000 rows. I have this code but it is taking way too long to execute. Is there any way to make this more efficient?

df["Grade Band"] = ""
k5 = ["0","1","2","3","4","5"]
ms = ["6", "7" ,"8"]
hs = ["9","10","11","12"]

for x in df["Grade Roll"]:
    if x == "Other":
        df["Grade Band"] == "Undefined"
    elif x in k5:
        df["Grade Band"] == "K5"
    elif x in ms:
        df["Grade Band"] == "MS"
    elif x in hs:
            df["Grade Band"] == "HS"

Body:
This should be pretty fast:

df.loc[df["Grade Roll"] == "Other", "Grade Roll"] = "Undefined"
df.loc[df["Grade Roll"].isin(k5), "Grade Roll"] = "K5"
df.loc[df["Grade Roll"].isin(ms), "Grade Roll"] = "MS"
df.loc[df["Grade Roll"].isin(hs), "Grade Roll"] = "HS"

If you wanted it to be less repetitive, you could store your arrays in a dict:

d = {
    "K5": ["0","1","2","3","4","5"],
    "MS": ["6", "7" ,"8"],
    "HS": ["9","10","11","12"],
    "Undefined": ["Other"]
}

for k, v in d.items():
    df.loc[df["Grade Roll"].isin(v), "Grade Roll"] = k


问:
A Java program that counts byte zero sequences
I have written code that is supposed to count sequential zeros. When you enter a number, for example 55  which in binary is 0011 0111, the Result is supposed to be 2 and 1, instead I only get 2 and the loop ends.

Can anyone help?

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

class Main {
  public static void main(String[] args) {
    System.out.print("input number:");

    Scanner sc = new Scanner(System.in);
    byte n = sc.nextByte();
    sc.close();

    byte mask = (byte)(128); // 1000 0000

    int result;
    int zeros = 0;
    System.out.print("result:");
    System.out.println("");
    for(int i=0; i<=8; i++) {
       result =(byte) (n & mask);
       if (result != 0) result = 1; else result = 0;

       if (result == 0) {
        zeros++;
       }
       if (result == 1) {
        if (zeros != 0) {
             System.out.print(zeros+" ");
             }
        zeros=0;

       }
       mask = (byte)(mask >> 1);

    }
  }
</code>```

}

答:
You haven't specified how this is to be done.  If bit manipulation only then you're on the right track.
 However, an alternative would be to use a String approach with regular expressions.

set a capture pattern to look for one or more 0 bits.

iterate over the data, applying the regex and capture the group.

a special check is done for all ones. A regex is used rather than equals to allow for arbitrary
 length strings if desired.

```<code>Pattern pat = Pattern.compile("(0+)");
String[] data =
        { "10101111", "11001000", "10011011", "00100010" "00000000","11111111"};

String[] data = { "10101111", "11001000", "10011011",
        "00100010", "00000000", "11111111" };

for (String octet : data) {
    System.out.print(
            octet + " - " + (octet.matches("1+") ? "0" : ""));
    Matcher m = pat.matcher(octet);
    while (m.find()) {
        System.out.print(m.group(1).length() + " ");
    }
    System.out.println();
}
</code>```

prints

```<code>10101111 - 1 1
11001000 - 2 3
10011011 - 2 1
00100010 - 2 3 1
00000000 - 8
11111111 - 0

</code>```

Body:
I have written code that is supposed to count sequential zeros. When you enter a number, for example 55  which in binary is 0011 0111, the Result is supposed to be 2 and 1, instead I only get 2 and the loop ends.

Can anyone help?

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    System.out.print("input number:");

    Scanner sc = new Scanner(System.in);
    byte n = sc.nextByte();
    sc.close();

    byte mask = (byte)(128); // 1000 0000

    int result;
    int zeros = 0;
    System.out.print("result:");
    System.out.println("");
    for(int i=0; i<=8; i++) {
       result =(byte) (n & mask);
       if (result != 0) result = 1; else result = 0;

       if (result == 0) {
        zeros++;
       }
       if (result == 1) {
        if (zeros != 0) {
             System.out.print(zeros+" ");
             }
        zeros=0;

       }
       mask = (byte)(mask >> 1);

    }
  }

}

Body:
You haven't specified how this is to be done.  If bit manipulation only then you're on the right track.
 However, an alternative would be to use a String approach with regular expressions.

set a capture pattern to look for one or more 0 bits.

iterate over the data, applying the regex and capture the group.

a special check is done for all ones. A regex is used rather than equals to allow for arbitrary
 length strings if desired.

Pattern pat = Pattern.compile("(0+)");
String[] data =
        { "10101111", "11001000", "10011011", "00100010" "00000000","11111111"};

String[] data = { "10101111", "11001000", "10011011",
        "00100010", "00000000", "11111111" };

for (String octet : data) {
    System.out.print(
            octet + " - " + (octet.matches("1+") ? "0" : ""));
    Matcher m = pat.matcher(octet);
    while (m.find()) {
        System.out.print(m.group(1).length() + " ");
    }
    System.out.println();
}

prints

10101111 - 1 1
11001000 - 2 3
10011011 - 2 1
00100010 - 2 3 1
00000000 - 8
11111111 - 0


问:
How can I identify the column, where two (or more) rows are different (same ID)?
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

```<code>ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)
</code>```
```<code>   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805
</code>```

My goal would be an additional column, which contains the changed column, i.e. desired output:

```<code>   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>
</code>```

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

答:
func <- function(X) {
  paste(names(
    Filter(function(z) length(z) > 1,
           lapply(X, unique))
  ), collapse = ";")
}

df %>%
  group_by(ID) %>%
  mutate(col_diff = func(cur_data())) %>%
  ungroup()
# # A tibble: 10 x 5
#       ID Info1 Info2 Info3 col_diff
#    <dbl> <dbl> <chr> <dbl> <chr>
#  1     1    10 A       999 ""
#  2     2    20 B       998 "Info2;Info3"
#  3     2    20 A       997 "Info2;Info3"
#  4     4    40 D       995 ""
#  5     5    50 E       995 "Info2"
#  6     5    50 E       995 "Info2"
#  7     5    50 F       995 "Info2"
#  8     6    65 Z       946 "Info1;Info2;Info3"
#  9     6    60 A       800 "Info1;Info2;Info3"
# 10     7    70 B       805 ""
```
<p>If you're planning on using the <code>col_diff</code> in a programmatic way later, it might be better to keep that as a <code>list-column</code>, so that you can test membership with <code>%in%</code>, etc.</p>
<pre class="lang-r prettyprint-override"><code>func2 <- function(X) {
  replicate(nrow(X), names(
    Filter(function(z) length(z) > 1,
           lapply(X, unique))
  ), simplify = FALSE)
}
out <- df %>%
  group_by(ID) %>%
  mutate(col_diff = func2(cur_data())) %>%
  ungroup()
out
# # A tibble: 10 x 5
#       ID Info1 Info2 Info3 col_diff
#    <dbl> <dbl> <chr> <dbl> <list>
#  1     1    10 A       999 <chr [0]>
#  2     2    20 B       998 <chr [2]>
#  3     2    20 A       997 <chr [2]>
#  4     4    40 D       995 <chr [0]>
#  5     5    50 E       995 <chr [1]>
#  6     5    50 E       995 <chr [1]>
#  7     5    50 F       995 <chr [1]>
#  8     6    65 Z       946 <chr [3]>
#  9     6    60 A       800 <chr [3]>
# 10     7    70 B       805 <chr [0]>
str(out$col_diff)
# List of 10
#  $ : chr(0)
#  $ : chr [1:2] "Info2" "Info3"
#  $ : chr [1:2] "Info2" "Info3"
#  $ : chr(0)
#  $ : chr "Info2"
#  $ : chr "Info2"
#  $ : chr "Info2"
#  $ : chr [1:3] "Info1" "Info2" "Info3"
#  $ : chr [1:3] "Info1" "Info2" "Info3"
#  $ : chr(0)
</code>```

Body:
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)

   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805

My goal would be an additional column, which contains the changed column, i.e. desired output:

   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

Body:
func <- function(X) {
  paste(names(
    Filter(function(z) length(z) > 1,
           lapply(X, unique))
  ), collapse = ";")
}

df %>%
  group_by(ID) %>%
  mutate(col_diff = func(cur_data())) %>%
  ungroup()
# # A tibble: 10 x 5
#       ID Info1 Info2 Info3 col_diff
#    <dbl> <dbl> <chr> <dbl> <chr>
#  1     1    10 A       999 ""
#  2     2    20 B       998 "Info2;Info3"
#  3     2    20 A       997 "Info2;Info3"
#  4     4    40 D       995 ""
#  5     5    50 E       995 "Info2"
#  6     5    50 E       995 "Info2"
#  7     5    50 F       995 "Info2"
#  8     6    65 Z       946 "Info1;Info2;Info3"
#  9     6    60 A       800 "Info1;Info2;Info3"
# 10     7    70 B       805 ""

If you're planning on using the col_diff in a programmatic way later, it might be better to keep that as a list-column, so that you can test membership with %in%, etc.

func2 <- function(X) {
  replicate(nrow(X), names(
    Filter(function(z) length(z) > 1,
           lapply(X, unique))
  ), simplify = FALSE)
}
out <- df %>%
  group_by(ID) %>%
  mutate(col_diff = func2(cur_data())) %>%
  ungroup()
out
# # A tibble: 10 x 5
#       ID Info1 Info2 Info3 col_diff
#    <dbl> <dbl> <chr> <dbl> <list>
#  1     1    10 A       999 <chr [0]>
#  2     2    20 B       998 <chr [2]>
#  3     2    20 A       997 <chr [2]>
#  4     4    40 D       995 <chr [0]>
#  5     5    50 E       995 <chr [1]>
#  6     5    50 E       995 <chr [1]>
#  7     5    50 F       995 <chr [1]>
#  8     6    65 Z       946 <chr [3]>
#  9     6    60 A       800 <chr [3]>
# 10     7    70 B       805 <chr [0]>
str(out$col_diff)
# List of 10
#  $ : chr(0)
#  $ : chr [1:2] "Info2" "Info3"
#  $ : chr [1:2] "Info2" "Info3"
#  $ : chr(0)
#  $ : chr "Info2"
#  $ : chr "Info2"
#  $ : chr "Info2"
#  $ : chr [1:3] "Info1" "Info2" "Info3"
#  $ : chr [1:3] "Info1" "Info2" "Info3"
#  $ : chr(0)


问:
How do you provide "context" in an "Object" or "Singleton" class in Android?
I have this warning:

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException

The thing is when I use what they want me to use like here with the warning:

```<code>  if (operation is Connect) {
            with(operation) {
                Timber.w("Connecting to ${device.name} | ${device.address}")
                device.connectGatt(context, false, gattCallback)
                isConnected.value = true
            }
            return
        }
</code>```

And after I select the "Add Permission Check":

```<code> if (operation is Connect) {
        with(operation) {
            Timber.w("Connecting to ${device.name} | ${device.address}")
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
            ) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return
            }
            device.connectGatt(context, false, gattCallback)
            isConnected.value = true
        }
        return
    }
</code>```

"this" is underlined in red as an error expecting context but found "Connect". What am I supposed to do in this situation?

EDIT: This one too

This error is in a few parts of the code, they started appearing after I updated Android Studio and Gradle. I'm not gonna lie, I'm not that experienced with Kotlin nor with singleton classes. But the class itself was based on a tutorial that used an "Object" class in the sense of it being instantiated only once, I believe that's what's called a singleton class though I am not sure if I am using it correctly.

答: You are passing this which is a reference to Connect not Context. Just pass context.

Body:
I have this warning:

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException

The thing is when I use what they want me to use like here with the warning:

  if (operation is Connect) {
            with(operation) {
                Timber.w("Connecting to ${device.name} | ${device.address}")
                device.connectGatt(context, false, gattCallback)
                isConnected.value = true
            }
            return
        }

And after I select the "Add Permission Check":

 if (operation is Connect) {
        with(operation) {
            Timber.w("Connecting to ${device.name} | ${device.address}")
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
            ) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return
            }
            device.connectGatt(context, false, gattCallback)
            isConnected.value = true
        }
        return
    }

"this" is underlined in red as an error expecting context but found "Connect". What am I supposed to do in this situation?

EDIT: This one too

This error is in a few parts of the code, they started appearing after I updated Android Studio and Gradle. I'm not gonna lie, I'm not that experienced with Kotlin nor with singleton classes. But the class itself was based on a tutorial that used an "Object" class in the sense of it being instantiated only once, I believe that's what's called a singleton class though I am not sure if I am using it correctly.


问:
How can I chain functions when i call it in Swift?
I am beginner in swift and I'm doing exercises to learn.

I have to filter any numbers that are even, sort the array, map them to string and print the result one item per line.

The problem is, when I call the function, I´m not able to chain the closures, and it only prints the third function.

```<code>import Foundation

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) -> [Int], third: ([Int]) -> [String]) {
    first(luckyNumbers)
    second(luckyNumbers)
    third(luckyNumbers)

    third(luckyNumbers).forEach {
        print($0)
    }
}

doImportantWorkChain { number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
} second: { number in
    return number.sorted {
        return $0 < $1
    }
} third: { number in
    return number.map {
       ("\($0) is the lucky number")
    }
}
</code>```

Output

```<code>7 is the lucky number
4 is the lucky number
38 is the lucky number
21 is the lucky number
16 is the lucky number
15 is the lucky number
12 is the lucky number
33 is the lucky number
31 is the lucky number
49 is the lucky number
</code>```

Output I have to get

```<code>4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number
</code>```

I know that I have to use: luckyNumbers.first { }.second { }

When I try to write like this Xcode give me error: value of type '(([Int]) -> [Int], ([Int]) -> [Int], ([Int]) -> [String]) -> ()' has no member 'first'

So I erase first and give me this errors:

Expected member name following '.'

Top-level statement cannot begin with a closure expression

Value of type '(_) -> _' has no member 'second'

```<code>doImportantWorkChain.first{ number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
}.second{ number in
    return number.sorted {
        return $0 < $1
    }
}.third{ number in
    return number.map {
       ("\($0) is the lucky number")
    }
}
</code>```

Also I try to chain it when when I call them inside the function but doesn't work either.

答:
As the first answer suggested, the issue is that the result of a closure should be used in the next closure.

The fastest way to get the output you are looking for

```<code>func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    third(second(first(luckyNumbers))).forEach {
        print($0)
    }
}
</code>```

However, this is not really chaining functions together and it is doing what the first answer with and just reduces your lines of code but there is no real upgrade in this.

The right way (IMO) to get the output you are looking for

Chaining would be something that I believe one of the commenters suggested is using the filter, sort and map functions directly on luckyNumbers to get your desired output:

```<code>luckyNumbers
    .filter { $0.isMultiple(of: 2) }
    .sorted() { return $0 < $1 }
    .map { ("\($0) is the lucky number") }
    .forEach { print($0) }
</code>```

A way that is chaining, will give you the desired output but I don't know why you would ever use this

If you think about what you need to do, to achieve some sort of chaining, you need to create your own higher order functions like filter, map etc with the same signatures as your closures and then executing the closures.

I did this by creating an extension for Int arrays

```<code>extension Array where Element == Int
{
    func apply(_ operation: ([Int]) -> [Int]) -> [Int]
    {
        return operation(self)
    }

    func apply(_ operation: ([Int]) -> [String]) -> [String]
    {
        return operation(self)
    }
}
</code>```

Then you can achieve chaining and get your desired result

```<code>func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    luckyNumbers
        .apply(first)
        .apply(second)
        .apply(third)
        .forEach { print($0) }
}
</code>```

Again, this might be a nice exercise to work your brain and explore the language and its capabilities but I don't think you will ever really use this.

All three of the above ways will give you this output:

```<code>4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number
</code>```

Body:
I am beginner in swift and I'm doing exercises to learn.

I have to filter any numbers that are even, sort the array, map them to string and print the result one item per line.

The problem is, when I call the function, I´m not able to chain the closures, and it only prints the third function.

import Foundation

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) -> [Int], third: ([Int]) -> [String]) {
    first(luckyNumbers)
    second(luckyNumbers)
    third(luckyNumbers)

    third(luckyNumbers).forEach {
        print($0)
    }
}

doImportantWorkChain { number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
} second: { number in
    return number.sorted {
        return $0 < $1
    }
} third: { number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Output

7 is the lucky number
4 is the lucky number
38 is the lucky number
21 is the lucky number
16 is the lucky number
15 is the lucky number
12 is the lucky number
33 is the lucky number
31 is the lucky number
49 is the lucky number

Output I have to get

4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number

I know that I have to use: luckyNumbers.first { }.second { }

When I try to write like this Xcode give me error: value of type '(([Int]) -> [Int], ([Int]) -> [Int], ([Int]) -> [String]) -> ()' has no member 'first'

So I erase first and give me this errors:

Expected member name following '.'

Top-level statement cannot begin with a closure expression

Value of type '(_) -> _' has no member 'second'

doImportantWorkChain.first{ number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
}.second{ number in
    return number.sorted {
        return $0 < $1
    }
}.third{ number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Also I try to chain it when when I call them inside the function but doesn't work either.

Body:
As the first answer suggested, the issue is that the result of a closure should be used in the next closure.

The fastest way to get the output you are looking for

func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    third(second(first(luckyNumbers))).forEach {
        print($0)
    }
}

However, this is not really chaining functions together and it is doing what the first answer with and just reduces your lines of code but there is no real upgrade in this.

The right way (IMO) to get the output you are looking for

Chaining would be something that I believe one of the commenters suggested is using the filter, sort and map functions directly on luckyNumbers to get your desired output:

luckyNumbers
    .filter { $0.isMultiple(of: 2) }
    .sorted() { return $0 < $1 }
    .map { ("\($0) is the lucky number") }
    .forEach { print($0) }

A way that is chaining, will give you the desired output but I don't know why you would ever use this

If you think about what you need to do, to achieve some sort of chaining, you need to create your own higher order functions like filter, map etc with the same signatures as your closures and then executing the closures.

I did this by creating an extension for Int arrays

extension Array where Element == Int
{
    func apply(_ operation: ([Int]) -> [Int]) -> [Int]
    {
        return operation(self)
    }

    func apply(_ operation: ([Int]) -> [String]) -> [String]
    {
        return operation(self)
    }
}

Then you can achieve chaining and get your desired result

func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    luckyNumbers
        .apply(first)
        .apply(second)
        .apply(third)
        .forEach { print($0) }
}

Again, this might be a nice exercise to work your brain and explore the language and its capabilities but I don't think you will ever really use this.

All three of the above ways will give you this output:

4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number


问:
jQuery UI droppable "out" event doesn't trigger
On "over"-ing I'm rebuilding the droppable elements by $(this).parent.empty().append(...)
(they basically consist of
 elements)

The problem is that the actual element, awaiting the "out" function to be triggered is deleted as well --> out cannot be fired

is there any solution for this kind of problem?

答:
Have you tried .live. This will add it back on if you create the elements after the DOM has been loaded already. So if you have some thing like $("#mylist li").live('handler', function(){}); Im not sure exactly what you are doing, but it would be something like this.

You can see some examples here:
http://api.jquery.com/live/

And in face you can do multiple handlers.

```<code>$("#mylist li").live("mouseover mouseout", function(event) {
  if ( event.type == "mouseover" ) {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});
</code>```

Delegate as Husky suggested:

```<code>$("#mylist").delegate("li", "mouseover mouseout", function(event) {
  if ( event.type == "mouseover" ) {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});
</code>```

Body:
Have you tried .live. This will add it back on if you create the elements after the DOM has been loaded already. So if you have some thing like $("#mylist li").live('handler', function(){}); Im not sure exactly what you are doing, but it would be something like this.

You can see some examples here:
http://api.jquery.com/live/

And in face you can do multiple handlers.

$("#mylist li").live("mouseover mouseout", function(event) {
  if ( event.type == "mouseover" ) {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

Delegate as Husky suggested:

$("#mylist").delegate("li", "mouseover mouseout", function(event) {
  if ( event.type == "mouseover" ) {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});