问:
How to calculate the average of a column where the row meets a certain condition in Pandas
Basically I have this Dataframe:

```<code>import pandas as pd
dict = {'number': [1,1,1,1,1,2,2,2,4,4,4,4,6,6], 'time':[34,33,41,36,43,22,24,32,29,28,33,32,55,51]}
df = pd.DataFrame(dict)
print(df)
</code>```

Output:

And I want to transform the df or create another one where instead of being several rows with the same 'number', there is a unique 'number' per row; and in the 'time' column, its average (of the records that had the same 'number'). Also, there should be a 3rd column called 'count' that shows the amount of records each 'number' had.

The output expected is:

Thanks.

答:
Simply use groupby + agg:

```<code>agg = df.groupby('number')['time'].agg(['count', 'mean']).reset_index()
</code>```

Output:

```<code>>>> agg
   number  count  mean
0       1      5  37.4
1       2      3  26.0
2       4      4  30.5
3       6      2  53.0
</code>```

Body:
Basically I have this Dataframe:

import pandas as pd
dict = {'number': [1,1,1,1,1,2,2,2,4,4,4,4,6,6], 'time':[34,33,41,36,43,22,24,32,29,28,33,32,55,51]}
df = pd.DataFrame(dict)
print(df)

Output:

And I want to transform the df or create another one where instead of being several rows with the same 'number', there is a unique 'number' per row; and in the 'time' column, its average (of the records that had the same 'number'). Also, there should be a 3rd column called 'count' that shows the amount of records each 'number' had.

The output expected is:

Thanks.

Body:
Simply use groupby + agg:

agg = df.groupby('number')['time'].agg(['count', 'mean']).reset_index()

Output:

>>> agg
   number  count  mean
0       1      5  37.4
1       2      3  26.0
2       4      4  30.5
3       6      2  53.0


来源: stackexchange

问:
Server won't run this part of Python code
We have a server for python scripts, where there is quite a lot of them running already, but for some reason one code won't run and it is because of this part:

```<code>def getData(ico):
    url = "https://www.mojedatovaschranka.cz/sds/ws/call"

    headers = {'Content-Type':'application/xml'}

    data = """
            <GetInfoRequest xmlns="http://seznam.gov.cz/ovm/ws/v1">
                <Ico>{}</Ico>
            </GetInfoRequest>
    """.format(ico)

    response = requests.post(url, headers=headers, data=data)

    #print(response.status_code)
    #print(response.text)

    data = xmltodict.parse(response.content)
    #print(data)
    return data
</code>```

for
It is offical api for some data off all legal subjects, not really important.
We cant figure out, what is wrong with this segment.

There are other codes with API calls, so there is not a problem, thant server can't send them.

Also we have newest python 7.3.1 installed.

All libs are installed and used by other scripts.

This is the only message we got: Task Scheduler successfully completed task "\Python\API_Databox" , instance "{0b448401-dedd-4cbc-9200-8addd409dfcf}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 2147942401.

Also it runs normally on my computers.

So my question is, does somebody know what might fix the issue or why server cant"t run this specific code? Other similar codes are running just fine.

答:
Maybe it's a long shot but I had that exact error message when trying to execute a simple .bat file with task scheduler as another user....

The script called an .exe with some options.

It started fine manually, but the task failed and failed. After playing around with the program, arguments, and start in fields in task scheduler I moved the .bat to the other documents folder of the user I was trying to run the task with. Tried to run it with a cmd launched as that account. Guess what, it couldn't find the exe...

In the end I realized that task scheduler and the other account had no idea where the .exe was located. Copied it over to where the script was and it finally ran correctly. Hope this helps ;)

ContentLicense: CC BY-SA 4.0

Body:
We have a server for python scripts, where there is quite a lot of them running already, but for some reason one code won't run and it is because of this part:

def getData(ico):
    url = "https://www.mojedatovaschranka.cz/sds/ws/call"

    headers = {'Content-Type':'application/xml'}

    data = """
            <GetInfoRequest xmlns="http://seznam.gov.cz/ovm/ws/v1">
                <Ico>{}</Ico>
            </GetInfoRequest>
    """.format(ico)

    response = requests.post(url, headers=headers, data=data)

    #print(response.status_code)
    #print(response.text)

    data = xmltodict.parse(response.content)
    #print(data)
    return data

for
It is offical api for some data off all legal subjects, not really important.
We cant figure out, what is wrong with this segment.

There are other codes with API calls, so there is not a problem, thant server can't send them.

Also we have newest python 7.3.1 installed.

All libs are installed and used by other scripts.

This is the only message we got: Task Scheduler successfully completed task "\Python\API_Databox" , instance "{0b448401-dedd-4cbc-9200-8addd409dfcf}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 2147942401.

Also it runs normally on my computers.

So my question is, does somebody know what might fix the issue or why server cant"t run this specific code? Other similar codes are running just fine.


问:
functional programming with coroutines python
I have async call, for example

```<code>from httpx import AsyncClient, Response

client = AsyncClient()
my_call = client.get(f"{HOST}/api/my_method")  # async call
</code>```

And I want to pass it to some retry logic like

```<code>async def retry_http(http_call):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

await retry_http(my_call)
</code>```

but I got

```<code>RuntimeError
cannot reuse already awaited coroutine
</code>```

Are there any method to make my_call an reusable coroutine ?

答:
can be fixed in next way</p>
```<code>async def retry_http(http_call, *args, **kwargs):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call(*args, **kwargs)
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

client = AsyncClient()
await retry_http(client.get, f"{HOST}/api/my_method")
</code>```

Body:
I have async call, for example

from httpx import AsyncClient, Response

client = AsyncClient()
my_call = client.get(f"{HOST}/api/my_method")  # async call

And I want to pass it to some retry logic like

async def retry_http(http_call):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

await retry_http(my_call)

but I got

RuntimeError
cannot reuse already awaited coroutine

Are there any method to make my_call an reusable coroutine ?

Body:
can be fixed in next way

async def retry_http(http_call, *args, **kwargs):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call(*args, **kwargs)
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

client = AsyncClient()
await retry_http(client.get, f"{HOST}/api/my_method")


问:
Behaviour of final static method
I have been playing around with modifiers with static method and came across a weird behaviour.

As we know, static methods cannot be overridden, as they are associated with class rather than instance.

So if I have the below snippet, it compiles fine

```<code>//Snippet 1 - Compiles fine
public class A {
    static void ts() {
    }
}

class B extends A {
    static void ts() {
    }
}
</code>```

But if I include final modifier to static method in class A, then compilation fails
ts() in B cannot override ts() in A; overridden method is static final.

Why is this happening when static method cannot be overridden at all?

答:
Static methods are "hidden" in inherited classes and cannot be overridden "non-statically" i.e. they cannot be overridden in a "polymorphism" sense. But they can be overridden "statically".

Static final methods are not allowed to be overridden even "statically".

The following example illustrates this -

App.java -

```<code>public class App {
    public static void main(String[] args) {
        Base.fun1();
        Base.fun2();
        Derived1.fun1();
        Derived1.fun2();
        Derived2.fun1();
        Derived2.fun2();
    }
}
</code>```

Base.java -

```<code>public abstract class Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Base");
    }

    protected static final void fun2() {
        System.out.println("Static final fun2() called in Base");
    }

}
</code>```

Derived1.java -

```<code>public class Derived1 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived1");
    }

    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived1");
    }
    */
}
</code>```

Derived2.java -

```<code>public class Derived2 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived2");
    }

    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived2");
    }
    */
}
</code>```

Output -

```<code>Static fun1() called in Base
Static final fun2() called in Base
Static fun1() called in Derived1
Static final fun2() called in Base
Static fun1() called in Derived2
Static final fun2() called in Base
</code>```

ContentLicense: CC BY-SA 3.0

Title: Behaviour of final static method

Body:
I have been playing around with modifiers with static method and came across a weird behaviour.

As we know, static methods cannot be overridden, as they are associated with class rather than instance.

So if I have the below snippet, it compiles fine

//Snippet 1 - Compiles fine
public class A {
    static void ts() {
    }
}

class B extends A {
    static void ts() {
    }
}

But if I include final modifier to static method in class A, then compilation fails
ts() in B cannot override ts() in A; overridden method is static final.

Why is this happening when static method cannot be overridden at all?

Body:
Static methods are "hidden" in inherited classes and cannot be overridden "non-statically" i.e. they cannot be overridden in a "polymorphism" sense. But they can be overridden "statically".

Static final methods are not allowed to be overridden even "statically".

The following example illustrates this -

App.java -

public class App {
    public static void main(String[] args) {
        Base.fun1();
        Base.fun2();
        Derived1.fun1();
        Derived1.fun2();
        Derived2.fun1();
        Derived2.fun2();
    }
}

Base.java -

public abstract class Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Base");
    }

    protected static final void fun2() {
        System.out.println("Static final fun2() called in Base");
    }

}

Derived1.java -

public class Derived1 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived1");
    }

    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived1");
    }
    */
}

Derived2.java -

public class Derived2 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived2");
    }

    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived2");
    }
    */
}

Output -

Static fun1() called in Base
Static final fun2() called in Base
Static fun1() called in Derived1
Static final fun2() called in Base
Static fun1() called in Derived2
Static final fun2() called in Base


问:
Error "Database operation expected to affect 1 row(s) but actually affected 0 row(s)" when adding a related entity
I've been searching for a solution to write a "generic" update method in EF Core which updates all changed properties of an entity including a related collection. The reason for this is that I store translations for the name of an entity in a different table.
I found this solution which seemed to work just fine at the beginning but then I noticed that I get an error "Database operation expected to affect 1 row(s) but actually affected 0 row(s)" when the only thing I changed in the entity was adding a new name translation in the related table TblProjectTranslations. Here is my code:

```<code>public async Task UpdateProjectAsync(TblProject updatedEntity)
{
    TblProject dbEntity = Context.TblProjects
        .Include(dbEntity => dbEntity.TblProjectTranslations)
        .SingleOrDefault(dbEntity => dbEntity.ProjectId == updatedEntity.ProjectId);

    if (dbEntity != null)
    {
        Context.Entry(dbEntity).CurrentValues.SetValues(updatedEntity);

        foreach (TblProjectTranslation dbTranslation in dbEntity.TblProjectTranslations.ToList())
        {
            if (!updatedEntity.TblProjectTranslations
                .Any(translation => translation.ProjectId == dbTranslation.ProjectId && translation.Language == dbTranslation.Language))
            {
                Context.TblProjectTranslations.Remove(dbTranslation);
            }
        }

        foreach (TblProjectTranslation newTranslation in updatedEntity.TblProjectTranslations)
        {
            TblProjectTranslation dbTranslation = dbEntity.TblProjectTranslations
                .SingleOrDefault(dbTranslation => dbTranslation.ProjectId == newTranslation.ProjectId && dbTranslation.Language == newTranslation.Language);

            if (dbTranslation != null)
            {
                Context.Entry(dbTranslation).CurrentValues.SetValues(newTranslation);
            }
            else
            {
                dbEntity.TblProjectTranslations.Add(newTranslation);
            }
        }

        await Context.SaveChangesAsync();
    }
}
</code>```

Here are the reverse engineered EF Core classes:

```<code>public partial class TblProject
{
    public TblProject()
    {
        TblProjectTranslations = new HashSet<TblProjectTranslation>();
    }

    public int ProjectId { get; set; }

    public virtual ICollection<TblProjectTranslation> TblProjectTranslations { get; set; }
}

public partial class TblProjectTranslation
{
    public int ProjectId { get; set; }
    public string Language { get; set; }
    public string ProjectName { get; set; }

    public virtual TblProject Project { get; set; }
}
</code>```

Here is how they are defined in OnModelCreating:

```<code>modelBuilder.Entity<TblProject>(entity =>
{
    entity.HasKey(e => e.ProjectId);

    entity.ToTable("TBL_project");

    entity.Property(e => e.ProjectId).HasColumnName("project_ID");
});

modelBuilder.Entity<TblProjectTranslation>(entity =>
{
    entity.HasKey(e => new { e.ProjectId, e.Language });

    entity.ToTable("TBL_project_translation");

    entity.HasIndex(e => e.ProjectId, "IX_TBL_project_translation_project_ID");

    entity.Property(e => e.ProjectId).HasColumnName("project_ID");

    entity.Property(e => e.Language)
        .HasMaxLength(5)
        .HasColumnName("language")
        .HasDefaultValueSql("('-')");

    entity.Property(e => e.ProjectName)
        .IsRequired()
        .HasMaxLength(50)
        .HasColumnName("project_name")
        .HasDefaultValueSql("('-')");

    entity.HasOne(d => d.Project)
        .WithMany(p => p.TblProjectTranslations)
        .HasForeignKey(d => d.ProjectId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("TBL_project_translation_TBL_project");
});
</code>```

What I do not understand is that dbEntity.TblProjectTranslations.Add(newTranslation) seems to be the problem. When I replace this line with await Context.TblProjectTranslations.AddAsync(newTranslation), the error "magically" disappears, but aren't both ways supposed to do basically the same thing? Here is an example for an updatedEntity and a dbEntity which I captured while debugging the function right before the problem occurred:

```<code>updatedEntity:
ProjectId: 41
TblProjectTranslations: 1 Entry with:
    Language: "en"
    Project: null
    ProjectId: 41
    ProjectName: "TestNameEN"

dbEntity:
ProjectId: 41
TblProjectTranslations: No entries
</code>```

What is going on here? I do not even have any triggers in the database in both of those tables which seemed to be the cause of this error for some other people.

答:
After playing a bit with the sample model, code and explanations, I finally was able to reproduce it. The culprit seems to be the composite key and the default value for the string part of it:

entity.HasKey(e => new { e.ProjectId, e.Language }); // (1)

entity.Property(e => e.Language)
    .HasMaxLength(5)
    .HasColumnName("language")
    .HasDefaultValueSql("('-')"); // (2)
```
<p>Same happens if you use</p>
<pre class="lang-cs prettyprint-override"><code>.HasDefaultValue("-")
</code>```

This combination somehow is causing the EF to consider the item added to the parent collection navigation property

dbEntity.TblProjectTranslations.Add(newTranslation);
```
<p>as <code>Modified</code> instead of <code>Added</code>, which later leads to the error in questtion.</p>
<p>Since I can't find such behavior explanation in the EF Core documentation, and in general it looks wrong, I would suggest to go and report it to the EF Core GitHub issue tracker.</p>
<p>Meanwhile, the possible workarounds I see are</p>
<ul>
<li><p>Remove <code>.HasDefaultValueSql</code> / <code>.HasDefaultValue</code> for the key column</p>
</li>
<li><p>Instead of adding the child to the parent collection, add it directly to the context or the corresponding <code>DbSet</code> (optionally set the reference navigation property in advance "just in case"):</p>
</li>
</ul>
<pre class="lang-cs prettyprint-override"><code>newTranslation.Project = dbEntity;
Context.Add(newTranslation);
</code>```

Body:
I've been searching for a solution to write a "generic" update method in EF Core which updates all changed properties of an entity including a related collection. The reason for this is that I store translations for the name of an entity in a different table.
I found this solution which seemed to work just fine at the beginning but then I noticed that I get an error "Database operation expected to affect 1 row(s) but actually affected 0 row(s)" when the only thing I changed in the entity was adding a new name translation in the related table TblProjectTranslations. Here is my code:

public async Task UpdateProjectAsync(TblProject updatedEntity)
{
    TblProject dbEntity = Context.TblProjects
        .Include(dbEntity => dbEntity.TblProjectTranslations)
        .SingleOrDefault(dbEntity => dbEntity.ProjectId == updatedEntity.ProjectId);

    if (dbEntity != null)
    {
        Context.Entry(dbEntity).CurrentValues.SetValues(updatedEntity);

        foreach (TblProjectTranslation dbTranslation in dbEntity.TblProjectTranslations.ToList())
        {
            if (!updatedEntity.TblProjectTranslations
                .Any(translation => translation.ProjectId == dbTranslation.ProjectId && translation.Language == dbTranslation.Language))
            {
                Context.TblProjectTranslations.Remove(dbTranslation);
            }
        }

        foreach (TblProjectTranslation newTranslation in updatedEntity.TblProjectTranslations)
        {
            TblProjectTranslation dbTranslation = dbEntity.TblProjectTranslations
                .SingleOrDefault(dbTranslation => dbTranslation.ProjectId == newTranslation.ProjectId && dbTranslation.Language == newTranslation.Language);

            if (dbTranslation != null)
            {
                Context.Entry(dbTranslation).CurrentValues.SetValues(newTranslation);
            }
            else
            {
                dbEntity.TblProjectTranslations.Add(newTranslation);
            }
        }

        await Context.SaveChangesAsync();
    }
}

Here are the reverse engineered EF Core classes:

public partial class TblProject
{
    public TblProject()
    {
        TblProjectTranslations = new HashSet<TblProjectTranslation>();
    }

    public int ProjectId { get; set; }

    public virtual ICollection<TblProjectTranslation> TblProjectTranslations { get; set; }
}

public partial class TblProjectTranslation
{
    public int ProjectId { get; set; }
    public string Language { get; set; }
    public string ProjectName { get; set; }

    public virtual TblProject Project { get; set; }
}

Here is how they are defined in OnModelCreating:

modelBuilder.Entity<TblProject>(entity =>
{
    entity.HasKey(e => e.ProjectId);

    entity.ToTable("TBL_project");

    entity.Property(e => e.ProjectId).HasColumnName("project_ID");
});

modelBuilder.Entity<TblProjectTranslation>(entity =>
{
    entity.HasKey(e => new { e.ProjectId, e.Language });

    entity.ToTable("TBL_project_translation");

    entity.HasIndex(e => e.ProjectId, "IX_TBL_project_translation_project_ID");

    entity.Property(e => e.ProjectId).HasColumnName("project_ID");

    entity.Property(e => e.Language)
        .HasMaxLength(5)
        .HasColumnName("language")
        .HasDefaultValueSql("('-')");

    entity.Property(e => e.ProjectName)
        .IsRequired()
        .HasMaxLength(50)
        .HasColumnName("project_name")
        .HasDefaultValueSql("('-')");

    entity.HasOne(d => d.Project)
        .WithMany(p => p.TblProjectTranslations)
        .HasForeignKey(d => d.ProjectId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("TBL_project_translation_TBL_project");
});

What I do not understand is that dbEntity.TblProjectTranslations.Add(newTranslation) seems to be the problem. When I replace this line with await Context.TblProjectTranslations.AddAsync(newTranslation), the error "magically" disappears, but aren't both ways supposed to do basically the same thing? Here is an example for an updatedEntity and a dbEntity which I captured while debugging the function right before the problem occurred:

updatedEntity:
ProjectId: 41
TblProjectTranslations: 1 Entry with:
    Language: "en"
    Project: null
    ProjectId: 41
    ProjectName: "TestNameEN"

dbEntity:
ProjectId: 41
TblProjectTranslations: No entries

What is going on here? I do not even have any triggers in the database in both of those tables which seemed to be the cause of this error for some other people.

Body:
After playing a bit with the sample model, code and explanations, I finally was able to reproduce it. The culprit seems to be the composite key and the default value for the string part of it:

entity.HasKey(e => new { e.ProjectId, e.Language }); // (1)

entity.Property(e => e.Language)
    .HasMaxLength(5)
    .HasColumnName("language")
    .HasDefaultValueSql("('-')"); // (2)

Same happens if you use

.HasDefaultValue("-")

This combination somehow is causing the EF to consider the item added to the parent collection navigation property

dbEntity.TblProjectTranslations.Add(newTranslation);

as Modified instead of Added, which later leads to the error in questtion.

Since I can't find such behavior explanation in the EF Core documentation, and in general it looks wrong, I would suggest to go and report it to the EF Core GitHub issue tracker.

Meanwhile, the possible workarounds I see are

Remove .HasDefaultValueSql / .HasDefaultValue for the key column

Instead of adding the child to the parent collection, add it directly to the context or the corresponding DbSet (optionally set the reference navigation property in advance "just in case"):

newTranslation.Project = dbEntity;
Context.Add(newTranslation);


问:
Convert factor to numeric in the same order of the factor from 0 to length of the unique values
I am able to convert the new_target column into numerical form. But as the factor form is already numerical, I am left with a bunch of numbers. I want them ordered and reassigned to their equivalent from 0 to the length of the factor. I have a numerical target at first, then I quantize it to 20 bins. As a result, I obtain new_target column which consists of the unique values (0,1,3,14,16,18,19). Instead of these unique values I need values ordered from 0 to length of the unique values in new_target. Which are c(0,1,2,3,4,5,6). The expected output is given in new_target_expected column. How can I create new_target_expected column without manually creating it? I have a bigger dataframe I am dealing with and it is not possible to do this manually.

require(stringr)
require(data.table)

cat_var <- c("rock", "indie", "rock", "rock", "pop", "indie", "pop", "rock", "pop")
cat_var_2 <- c("blue", "green", "red", "red", "blue", "red", "green", "blue", "green")
target_var <- c(30, 10, 27, 14, 29, 25, 27, 12, 10)
df <- data.table("categorical_variable" = cat_var, "categorical_variable_2" = cat_var_2, "target_variable" =  target_var)

targetVariable <- "target_variable"

number_of_buckets = 20
# Each bucket should contain equal number of objects
a <- cut(df[[targetVariable]] , breaks = number_of_buckets, labels = 0:(number_of_buckets - 1))

df[["new_target"]] <- a
df[["new_target"]] <- as.numeric(as.character(df[["new_target"]]))
df[["new_target_expected"]] <- c(6, 0, 4, 2, 5, 3, 4, 1, 0)

```

答:
We could remove the unused levels with droplevels and coerce the factor to integer.  Indexing in R starts from 1, so subtract 1 to make the values start from 0.

```<code>library(data.table)
df[, (targetVariable) := as.integer(droplevels(a))-1]
</code>```

-output

```<code>> df
   categorical_variable categorical_variable_2 target_variable
1:                 rock                   blue               6
2:                indie                  green               0
3:                 rock                    red               4
4:                 rock                    red               2
5:                  pop                   blue               5
6:                indie                    red               3
7:                  pop                  green               4
8:                 rock                   blue               1
9:                  pop                  green               0
</code>```

Body:
We could remove the unused levels with droplevels and coerce the factor to integer.  Indexing in R starts from 1, so subtract 1 to make the values start from 0.

library(data.table)
df[, (targetVariable) := as.integer(droplevels(a))-1]

-output

> df
   categorical_variable categorical_variable_2 target_variable
1:                 rock                   blue               6
2:                indie                  green               0
3:                 rock                    red               4
4:                 rock                    red               2
5:                  pop                   blue               5
6:                indie                    red               3
7:                  pop                  green               4
8:                 rock                   blue               1
9:                  pop                  green               0


问:
Add leading zeros to integer section of filename
I have folders of images with names like HolidaySnapsJune-1.tif , HolidaySnapsMay-12.tif and HolidaySnaps2018-005.tif

I want to add one leading 0 to the integer section of the filename if it is 2 digits long, and I want to add two leading 00s if it is just one digit long.

I have tried variations of

```<code>find . -name '*\_[0-9][0-9].tif' -exec sh -c '
for fpath do
  echo mv "$fpath" "${fpath%/*}/${fpath##*/}"
done' _ {} +
</code>```

But these put the leading zeros in front of the full file name instead of in front of the integer section.

I would love to do this is a bash script which would recursively work on folders so it's important that the difference in names preceeding the '-' is ignored or worked-around.

I'm on Windows and just have access to whatever is built into git-bashso bash, sed, awk etc.

答:
If you don't want to use non-standard commands and write a small script, this would be one way to do it.

while read -r line; do
    num=$(sed 's/\..*//' <<<${line/*-})
    printf -v new_name '%s-%03d.%s' "${line/-*}" "${num}" "${line/*\.}"
    mv -v "${line}” "${new_name}"
done < <(printf '%s\n' HolidaySnapsJune-1.tif HolidaySnapsMay-12.tif)
```

Using HolidaySnapsJune-1.tif for explanation below:

${line/*-} removes everything before the dash -= 1.tif

${line/*\.} removes everything besides the extension.

sed 's/\..*//' <<<${line/*-} also removes everything after the first period ., so now we have simply 1

'%s-%03d.%s' the %03d part of that tells printf to print digits with leading zeroes up to 3 digits.

Used while read as it is easy to mockup with. You probably want to either use a find command or something such for the input to the loop.

Body:
I have folders of images with names like HolidaySnapsJune-1.tif , HolidaySnapsMay-12.tif and HolidaySnaps2018-005.tif

I want to add one leading 0 to the integer section of the filename if it is 2 digits long, and I want to add two leading 00s if it is just one digit long.

I have tried variations of

find . -name '*\_[0-9][0-9].tif' -exec sh -c '
for fpath do
  echo mv "$fpath" "${fpath%/*}/${fpath##*/}"
done' _ {} +

But these put the leading zeros in front of the full file name instead of in front of the integer section.

I would love to do this is a bash script which would recursively work on folders so it's important that the difference in names preceeding the '-' is ignored or worked-around.

I'm on Windows and just have access to whatever is built into git-bashso bash, sed, awk etc.

Body:
If you don't want to use non-standard commands and write a small script, this would be one way to do it.

while read -r line; do
    num=$(sed 's/\..*//' <<<${line/*-})
    printf -v new_name '%s-%03d.%s' "${line/-*}" "${num}" "${line/*\.}"
    mv -v "${line}” "${new_name}"
done < <(printf '%s\n' HolidaySnapsJune-1.tif HolidaySnapsMay-12.tif)

Using HolidaySnapsJune-1.tif for explanation below:

${line/*-} removes everything before the dash -= 1.tif

${line/*\.} removes everything besides the extension.

sed 's/\..*//' <<<${line/*-} also removes everything after the first period ., so now we have simply 1

'%s-%03d.%s' the %03d part of that tells printf to print digits with leading zeroes up to 3 digits.

Used while read as it is easy to mockup with. You probably want to either use a find command or something such for the input to the loop.


问:
How can i "sleep" in flutter and wait to run something
I'm coding my first app in flutter, so i want to show a WelcomeDialog at the first 5 seconds when user has loged in.
How can i do that?

i've implemented this code inside class _HomeScreenState extends State<HomeScreen> , but it doesnt shows nothing at the 5 seconds of loged in.

```<code>  //at 5 seconds to loged in, welcome dialog appear on the screen
  Future<void> startDialogWelcome() async {
    await Future.delayed(const Duration(seconds: 5), () {
      _showDialogWelcome(context);
    });
  }
</code>```

答:
I've created an example for you. You can use initState method with override. You can simply use the showDialog API to show a dialog on the screen also You can use the AlertDialog widget inside the dialog body.

If you want test: https://dartpad.dev/684308e16c95834e35f1e22d5e75e05e

class HomeScreen extends StatefulWidget {
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  @override
  void initState() {
    startDialogWelcome();
    super.initState();
  }

  Future<void> startDialogWelcome() async {
    await Future.delayed(const Duration(seconds: 5), () {
      _showDialogWelcome();
    });
  }

  void _showDialogWelcome() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Welcome!'),
            content: Text('Hey! Welcome to my app!')
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          'Hello, World!',
          style: Theme.of(context).textTheme.headline4,
        ),
      ),
    );
  }
}
```

Body:
I'm coding my first app in flutter, so i want to show a WelcomeDialog at the first 5 seconds when user has loged in.
How can i do that?

i've implemented this code inside class _HomeScreenState extends State<HomeScreen> , but it doesnt shows nothing at the 5 seconds of loged in.

  //at 5 seconds to loged in, welcome dialog appear on the screen
  Future<void> startDialogWelcome() async {
    await Future.delayed(const Duration(seconds: 5), () {
      _showDialogWelcome(context);
    });
  }


问:
Spark createDataFrame is getting stuck (during spark-submit)
I am trying to create a spark dataframe from a list. The list has 1 or 2 elements So far I tried the 4 methods below, but strangely my application is getting stuck at spark.createDataFrame(). Can someone please point out what I am doing wrong?

Update: These methods are working when tried in pyspark shell, but getting stuck during spark-submit

Method 1

```<code>schema = StructType([
StructField('TABLE_NAME', StringType(), True)
])
rdd = spark.sparkContext.parallelize(table_name_list)
df = spark.createDataFrame(rdd,schema)
df.show(truncate=False)
</code>```

Method2

```<code>column = ["TABLE_NAME"]
df = spark.createDataFrame(data=table_name_list, schema = column)
df.show(truncate=False)
</code>```

Method3

```<code>df = spark.createDataFrame([table_name_list], StringType())
df.show(truncate=False)
</code>```

Method 4

```<code>pd_df_tb_nm=pd.DataFrame({'TABLE_NAME':table_name_list})
print(pd_df_tb_nm) #printing pd df data
df_tb_nm=spark.createDataFrame(pd_df_tb_nm)
df.show(truncate=False)
</code>```

答: This issue is coming only when I set master as YARN using config("spark.master", "yarn"). In local mode all of the above methods and the one suggested here  are working seamlessly)**</p>

Body:
I am trying to create a spark dataframe from a list. The list has 1 or 2 elements So far I tried the 4 methods below, but strangely my application is getting stuck at spark.createDataFrame(). Can someone please point out what I am doing wrong?

Update: These methods are working when tried in pyspark shell, but getting stuck during spark-submit

Method 1

schema = StructType([
StructField('TABLE_NAME', StringType(), True)
])
rdd = spark.sparkContext.parallelize(table_name_list)
df = spark.createDataFrame(rdd,schema)
df.show(truncate=False)

Method2

column = ["TABLE_NAME"]
df = spark.createDataFrame(data=table_name_list, schema = column)
df.show(truncate=False)

Method3

df = spark.createDataFrame([table_name_list], StringType())
df.show(truncate=False)

Method 4

pd_df_tb_nm=pd.DataFrame({'TABLE_NAME':table_name_list})
print(pd_df_tb_nm) #printing pd df data
df_tb_nm=spark.createDataFrame(pd_df_tb_nm)
df.show(truncate=False)


问:
PHP - Adding prefix to String array during an explode
Ok, am trying to figure out the best way to do this.  I have code as follows:

```<code>$context['dp_module_headers'] = array();
</code>```

Than later on down within the function within a while loop I iterate through all foldernames and apply the path to this array.  But the paths are relative to the folder names, so I need to include the folder names within the values of the exploded array.

```<code>$context['dp_module_headers'] += explode('+', $row[$type . '_header_files']);
</code>```

This can return an array like so:

```<code>$context['dp_module_headers'][0] = 'source/script.js';
$context['dp_module_headers'][1] = 'source/script.css';
$context['dp_module_headers'][2] = 'source/script.js';
$context['dp_module_headers'][3] = 'mydir/style.css';
</code>```

I need to pre-pend the folder name before all values within the array.  I only have access to the folder name that it is in when within the function that does the explode.  So within the other function of a different file, I don't have access to the folder name that these paths link to.

So, when doing the explode, I need to pre-pend the folders name before each path within the value of each array.

So, basically, this array needs to return the following instead:

```<code>$context['dp_module_headers'][0] = 'sitenews/source/script.js';
$context['dp_module_headers'][1] = 'sitenews/source/script.css';
$context['dp_module_headers'][2] = 'userpanel/source/script.js';
$context['dp_module_headers'][3] = 'userpanel/mydir/style.css';
</code>```

I have a variable called $folder that gets changed per explode, but how can I add the $folder name string variable to the beginning of each value while exploding it?  Or is there a better way to do this?

Thanks guys :)

答:
With PHP 5.3+, you can use something like this:

```<code>$context['dp_module_headers'] += array_map(
    function ($path) use ($folder) { return $folder . $path; },
    explode('+', $row[$type . '_header_files'])
);
</code>```

That's a little more awkward to with with 5.2-, there you should save your exploded paths in a variable, loop over that array, prepend the $folder value to each value, then add the result to your $context array.

Body:
Ok, am trying to figure out the best way to do this.  I have code as follows:

$context['dp_module_headers'] = array();

Than later on down within the function within a while loop I iterate through all foldernames and apply the path to this array.  But the paths are relative to the folder names, so I need to include the folder names within the values of the exploded array.

$context['dp_module_headers'] += explode('+', $row[$type . '_header_files']);

This can return an array like so:

$context['dp_module_headers'][0] = 'source/script.js';
$context['dp_module_headers'][1] = 'source/script.css';
$context['dp_module_headers'][2] = 'source/script.js';
$context['dp_module_headers'][3] = 'mydir/style.css';

I need to pre-pend the folder name before all values within the array.  I only have access to the folder name that it is in when within the function that does the explode.  So within the other function of a different file, I don't have access to the folder name that these paths link to.

So, when doing the explode, I need to pre-pend the folders name before each path within the value of each array.

So, basically, this array needs to return the following instead:

$context['dp_module_headers'][0] = 'sitenews/source/script.js';
$context['dp_module_headers'][1] = 'sitenews/source/script.css';
$context['dp_module_headers'][2] = 'userpanel/source/script.js';
$context['dp_module_headers'][3] = 'userpanel/mydir/style.css';

I have a variable called $folder that gets changed per explode, but how can I add the $folder name string variable to the beginning of each value while exploding it?  Or is there a better way to do this?

Thanks guys :)

Body:
With PHP 5.3+, you can use something like this:

$context['dp_module_headers'] += array_map(
    function ($path) use ($folder) { return $folder . $path; },
    explode('+', $row[$type . '_header_files'])
);

That's a little more awkward to with with 5.2-, there you should save your exploded paths in a variable, loop over that array, prepend the $folder value to each value, then add the result to your $context array.


问:
Add dynamic data in a demo chart.js file of a django template
I'm using the "start bootstrap4" template for my Django project. I want to edit my own data in the sample chart. I need to change it in the chart-pie-demo.js file

I already created the list of data that I want t add into the chart. The data is defined in my views.py:

```<code>def chart(request):
    sheet2022 = client.open('sheet 2022')
    instance = sheet2022.get_worksheet(0)
    mysheet = instance.get_all_records()

    rpending2022 = list(filter(lambda datapending2022:

    Mi=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Mike'))
    Lu=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Lucy'))
    Ja=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Jack'))

    mydata = [Mi, Lu, Ja]
    context = {'mydata': mydata}
    return render(request,'charts.html', context)
</code>```

My chart-pie-demo.js file:

```<code>var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: [55, 30, 15],
      backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
      hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
      hoverBorderColor: "rgba(234, 236, 244, 1)",
    }],
  },
  options: {
    maintainAspectRatio: false,
    tooltips: {
      backgroundColor: "rgb(255,255,255)",
      bodyFontColor: "#858796",
      borderColor: '#dddfeb',
      borderWidth: 1,
      xPadding: 15,
      yPadding: 15,
      displayColors: false,
      caretPadding: 10,
    },
    legend: {
      display: false
    },
    cutoutPercentage: 80,
  },
});
</code>```

I want to replace the sample data: [55, 30, 15] with my own mydata. When I change it in my chart-pie-demo.js file, the chart doesn't show up. Do I need to link the data location in the chart-pie-demo.js file?

答:
You already mentioned use of pandas; that's why assume you can aggregate the names already.
For the django part:
You will need a view looking something like this:

def your_view(request):
  data = "[10, 20, 30]" # however your aggreated output will look.
  # for simplicity of this example I assume it as a string like that

  # you can pass variables to djangos frontend using context

  context = {'my_data': data}
  return render(request, 'index.html', context)
```
<p>So basically you can put your data just in an ordinary django context.
If your js is that short and you want a quick and easy answer, it would be best to remove the js file and put the code directly into a script tag in your html (I assumed "index.html" for example here).</p>
<p>Then you can just go into your script tag and:</p>
<pre class="lang-js prettyprint-override"><code>var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: {{ data }} ,
...
</code>```

Overall the basic idea in django is: you create a view. You create an url pointing to the view. The view renders a HTML file (or well, "file" in general; word files and other files work as well). "Renders" basically means performing templating functions and putting whatever values you gave it in context into the according variable names written in double curly brackets.

After that the file is served. Which means whatever you do in template runs before the javascript runs because the server creates the file using template tags and just after that it is sent to the browser which then executes javascript. For your example you could image django context and template tags just as a basic "use whatever I put in this variable to replace it in my html/css/js/whatever file".

That means you could also do:

def your_view(request):

  context = {
    'data_one': 10
    'data_two': 20
    'data_three': 30
  }
  return render(request, 'index.html', context)
```
<p>and accordingly:</p>
<pre class="lang-js prettyprint-override"><code>var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: [{{ data_one }}, {{ data_two }}, {{ data_three }}],
...
</code>```

Body:
I'm using the "start bootstrap4" template for my Django project. I want to edit my own data in the sample chart. I need to change it in the chart-pie-demo.js file

I already created the list of data that I want t add into the chart. The data is defined in my views.py:

def chart(request):
    sheet2022 = client.open('sheet 2022')
    instance = sheet2022.get_worksheet(0)
    mysheet = instance.get_all_records()

    rpending2022 = list(filter(lambda datapending2022:

    Mi=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Mike'))
    Lu=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Lucy'))
    Ja=len(tuple(d for d in rpending2022  if d['Receiver'] == 'Jack'))

    mydata = [Mi, Lu, Ja]
    context = {'mydata': mydata}
    return render(request,'charts.html', context)

My chart-pie-demo.js file:

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: [55, 30, 15],
      backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
      hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
      hoverBorderColor: "rgba(234, 236, 244, 1)",
    }],
  },
  options: {
    maintainAspectRatio: false,
    tooltips: {
      backgroundColor: "rgb(255,255,255)",
      bodyFontColor: "#858796",
      borderColor: '#dddfeb',
      borderWidth: 1,
      xPadding: 15,
      yPadding: 15,
      displayColors: false,
      caretPadding: 10,
    },
    legend: {
      display: false
    },
    cutoutPercentage: 80,
  },
});

I want to replace the sample data: [55, 30, 15] with my own mydata. When I change it in my chart-pie-demo.js file, the chart doesn't show up. Do I need to link the data location in the chart-pie-demo.js file?

Body:
You already mentioned use of pandas; that's why assume you can aggregate the names already.
For the django part:
You will need a view looking something like this:

def your_view(request):
  data = "[10, 20, 30]" # however your aggreated output will look.
  # for simplicity of this example I assume it as a string like that

  # you can pass variables to djangos frontend using context

  context = {'my_data': data}
  return render(request, 'index.html', context)

So basically you can put your data just in an ordinary django context.
If your js is that short and you want a quick and easy answer, it would be best to remove the js file and put the code directly into a script tag in your html (I assumed "index.html" for example here).

Then you can just go into your script tag and:

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: {{ data }} ,
...

Overall the basic idea in django is: you create a view. You create an url pointing to the view. The view renders a HTML file (or well, "file" in general; word files and other files work as well). "Renders" basically means performing templating functions and putting whatever values you gave it in context into the according variable names written in double curly brackets.

After that the file is served. Which means whatever you do in template runs before the javascript runs because the server creates the file using template tags and just after that it is sent to the browser which then executes javascript. For your example you could image django context and template tags just as a basic "use whatever I put in this variable to replace it in my html/css/js/whatever file".

That means you could also do:

def your_view(request):

  context = {
    'data_one': 10
    'data_two': 20
    'data_three': 30
  }
  return render(request, 'index.html', context)

and accordingly:

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: [{{ data_one }}, {{ data_two }}, {{ data_three }}],
...


问:
Complex conditional Regex grouping
I have the following text:

```<code> 1. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see
    para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2,
    FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs.

</code>```

I'm interested in extracting names of Documents that follow the pattern: (FCCC\/(?:SBSTA|SBI|CP|KP\/CMP|PA\/CMA)\/[0-9]{4}\/(?:INF\.|L\.|MISC\.)?[0-9]+(?:\/Add\.[0-9])?(?:\/Rev\.[0-9]+)?) this is, FCCC/Document_type(SBSTA or SBI, etc.)/Year/Number and they may or may not have adds, corrections and revisions.

There are two ways to refer to adds or revisions:

Add them at the end of the name: adding /Rev or /Add + number

or and Rev|Add|Corr .num

Then from the text I'm interested into build the names that are referenced with the second option.  For example, map: FCCC/CP/2011/7 and Corr.1 and Add.1 and 2 to ["FCCC/CP/2011/7", "FCCC/CP/2011/7/Corr.1", "FCCC/CP/2011/7/Add.1", "FCCC/CP/2011/7/Add.2"].

This is my current approach:

def _find_documents(par: str) -> Union[list, None]:
    """
    Finds referenced documents
    :param par:
    :return:
    """
    found_list = []
    pattern = r"(FCCC\/(?:SBSTA|SBI|CP|KP\/CMP|PA\/CMA)\/[0-9]{4}\/(?:INF\.|L\.|MISC\.)?[0-9]+(?:\/Add\.[0-9])?(?:\/Rev\.[0-9]+)?)"
    found = re.findall(pattern, par)

    # Now, we look for corrections and Revisions
    for doc in found:
        found_list.append(doc)
        doc = doc.replace(r"/", r"\/")
        pattern = doc + r"(?: and ((:?Corr\.|Add\.)?[0-9]))?(?: and ((:?Corr\.|Add\.)[0-9]))*(:? and ([0-9])+)?"
        res = re.search(pattern, par).groups()
        for pat in res:
            if pat is not None:
                found_list.append(doc + "/" + pat)

    return found_list if found_list is not None else None

    st = r"""
    50. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2, FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs.
    """

    _find_documents(st)
    """ [OUT]:
    ['FCCC/CP/2011/7',
     'FCCC\\/CP\\/2011\\/7/Corr.1',
    'FCCC\\/CP\\/2011\\/7/Corr.',  EXTRA
    'FCCC\\/CP\\/2011\\/7/Add.1',
    'FCCC\\/CP\\/2011\\/7/Add.',  EXTRA
    'FCCC\\/CP\\/2011\\/7/ and 2',  EXTRA
    'FCCC\\/CP\\/2011\\/7/2', WRONG Should be FCCC/CP/2011/7/Add.2
    'FCCC/SBI/2010/17',
    'FCCC/SBI/2010/26',
    'FCCC/SBI/2010/MISC.9']"""

```

As you can see I have several problems that I don't know how to solve.

The group capture extra matches ["Add.", "Corr.", "and 2"]

When I try to append Corrs, Apps, the / is somehow escaped.

Not sure how to map submatch and 2 into /Add.2 or /Corr.2 depending on the previous

Any ideas?

Thanks,

答:
You can use

import re
text = "50. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2, FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs."
rx_main = re.compile(r'(FCCC/(?:SBSTA|SBI|CP|KP/CMP|PA/CMA)/\d{4}/(?:INF\.|L\.|MISC\.)?\d+)((?:(?:/|\s+and\s+|\s*,\s*)(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*)*)')
rx_rev = re.compile(r'(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*')
rx_split = re.compile(r'\s*,\s*|\s+and\s+')
matches = rx_main.finditer(text)
results = []
for m in matches:
    results.append(m.group(1))
    chunks = [rx_split.split(x) for x in rx_rev.findall(m.group(2))]
    for ch in chunks:
        if len(ch) == 1: # it is simple, just add first item to Group 1
            results.append(f"{m.group(1)}/{ch[0]}")
        else:
            name = ch[0].split('.')[0] # Rev, Corr or Add
            for c in ch:
                if '.' in c: # if there is a dot, append whole string to Group 1
                    results.append(f"{m.group(1)}/{c}")
                else:
                    results.append(f"{m.group(1)}/{name}.{c}") # Append the new number to Corr/Add/Rev

print(results)
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>['FCCC/CP/2011/7', 'FCCC/CP/2011/7/Corr.1', 'FCCC/CP/2011/7/Add.1', 'FCCC/CP/2011/7/Add.2', 'FCCC/SBI/2010/17', 'FCCC/SBI/2010/26', 'FCCC/SBI/2010/MISC.9']
</code>```

See this Python demo.

The new regex is

(FCCC/(?:SBSTA|SBI|CP|KP/CMP|PA/CMA)/\d{4}/(?:INF\.|L\.|MISC\.)?\d+)((?:(?:/|\s+and\s+|\s*,\s*)(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*)*)
```

See the regex demo.

Title: Complex conditional Regex grouping

Body:
I have the following text:

 1. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see
    para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2,
    FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs.

I'm interested in extracting names of Documents that follow the pattern: (FCCC\/(?:SBSTA|SBI|CP|KP\/CMP|PA\/CMA)\/[0-9]{4}\/(?:INF\.|L\.|MISC\.)?[0-9]+(?:\/Add\.[0-9])?(?:\/Rev\.[0-9]+)?) this is, FCCC/Document_type(SBSTA or SBI, etc.)/Year/Number and they may or may not have adds, corrections and revisions.

There are two ways to refer to adds or revisions:

Add them at the end of the name: adding /Rev or /Add + number

or and Rev|Add|Corr .num

Then from the text I'm interested into build the names that are referenced with the second option.  For example, map: FCCC/CP/2011/7 and Corr.1 and Add.1 and 2 to ["FCCC/CP/2011/7", "FCCC/CP/2011/7/Corr.1", "FCCC/CP/2011/7/Add.1", "FCCC/CP/2011/7/Add.2"].

This is my current approach:

def _find_documents(par: str) -> Union[list, None]:
    """
    Finds referenced documents
    :param par:
    :return:
    """
    found_list = []
    pattern = r"(FCCC\/(?:SBSTA|SBI|CP|KP\/CMP|PA\/CMA)\/[0-9]{4}\/(?:INF\.|L\.|MISC\.)?[0-9]+(?:\/Add\.[0-9])?(?:\/Rev\.[0-9]+)?)"
    found = re.findall(pattern, par)

    # Now, we look for corrections and Revisions
    for doc in found:
        found_list.append(doc)
        doc = doc.replace(r"/", r"\/")
        pattern = doc + r"(?: and ((:?Corr\.|Add\.)?[0-9]))?(?: and ((:?Corr\.|Add\.)[0-9]))*(:? and ([0-9])+)?"
        res = re.search(pattern, par).groups()
        for pat in res:
            if pat is not None:
                found_list.append(doc + "/" + pat)

    return found_list if found_list is not None else None

    st = r"""
    50. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2, FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs.
    """

    _find_documents(st)
    """ [OUT]:
    ['FCCC/CP/2011/7',
     'FCCC\\/CP\\/2011\\/7/Corr.1',
    'FCCC\\/CP\\/2011\\/7/Corr.',  EXTRA
    'FCCC\\/CP\\/2011\\/7/Add.1',
    'FCCC\\/CP\\/2011\\/7/Add.',  EXTRA
    'FCCC\\/CP\\/2011\\/7/ and 2',  EXTRA
    'FCCC\\/CP\\/2011\\/7/2', WRONG Should be FCCC/CP/2011/7/Add.2
    'FCCC/SBI/2010/17',
    'FCCC/SBI/2010/26',
    'FCCC/SBI/2010/MISC.9']"""

As you can see I have several problems that I don't know how to solve.

The group capture extra matches ["Add.", "Corr.", "and 2"]

When I try to append Corrs, Apps, the / is somehow escaped.

Not sure how to map submatch and 2 into /Add.2 or /Corr.2 depending on the previous

Any ideas?

Thanks,

Body:
You can use

import re
text = "50. The SBI considered this sub-item at its resumed 1^st^ meeting and at its 2^nd^ meeting (see para. 46 above). It had before it documents FCCC/CP/2011/7 and Corr.1 and Add.1 and 2, FCCC/SBI/2010/17, FCCC/SBI/2010/26 and FCCC/SBI/2010/MISC.9. A statement was made on behalf of the LDCs."
rx_main = re.compile(r'(FCCC/(?:SBSTA|SBI|CP|KP/CMP|PA/CMA)/\d{4}/(?:INF\.|L\.|MISC\.)?\d+)((?:(?:/|\s+and\s+|\s*,\s*)(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*)*)')
rx_rev = re.compile(r'(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*')
rx_split = re.compile(r'\s*,\s*|\s+and\s+')
matches = rx_main.finditer(text)
results = []
for m in matches:
    results.append(m.group(1))
    chunks = [rx_split.split(x) for x in rx_rev.findall(m.group(2))]
    for ch in chunks:
        if len(ch) == 1: # it is simple, just add first item to Group 1
            results.append(f"{m.group(1)}/{ch[0]}")
        else:
            name = ch[0].split('.')[0] # Rev, Corr or Add
            for c in ch:
                if '.' in c: # if there is a dot, append whole string to Group 1
                    results.append(f"{m.group(1)}/{c}")
                else:
                    results.append(f"{m.group(1)}/{name}.{c}") # Append the new number to Corr/Add/Rev

print(results)

Output:

['FCCC/CP/2011/7', 'FCCC/CP/2011/7/Corr.1', 'FCCC/CP/2011/7/Add.1', 'FCCC/CP/2011/7/Add.2', 'FCCC/SBI/2010/17', 'FCCC/SBI/2010/26', 'FCCC/SBI/2010/MISC.9']

See this Python demo.

The new regex is

(FCCC/(?:SBSTA|SBI|CP|KP/CMP|PA/CMA)/\d{4}/(?:INF\.|L\.|MISC\.)?\d+)((?:(?:/|\s+and\s+|\s*,\s*)(?:Add|Rev|Corr)\.\d+(?:(?:\s*,\s*|\s+and\s+)\d+)*)*)

See the regex demo.


问:
Set scroll position from a different view in scrollview
How can I click the button from a different view and set the scroll position in a different view? the following code throws an error. I'm using environmentalObject. What I'm expecting is, when I click the buttons in ButtonView the scroll position of ScrollView1 should set to the 3rd object or 1st object in the scrollview. It works well in the same view, but does not know how to do it when it's different views.

Error: Type '()' cannot conform to 'View'

```<code>import SwiftUI

@EnvironmentObject private var environmentVariables: miscellaneousEnvironmentalVariable

struct ScrollView1: View {
var body: some View {

    ScrollView {

        ScrollViewReader { value in

            if (environmentVariables.CurrentIndexforPosts >= 0) {
                withAnimation {
                    value.scrollTo((environmentVariables.CurrentIndexforPosts), anchor: .top)}
            }

            LazyVStack {
                Text ("TEXT 1")
                Text ("TEXT 2")
                Text ("TEXT 3")
                Text ("TEXT 4")
            }

}

struct ButtonView: View {
            var body: some View {

                Button("Go to next") {
                    environmentVariables.CurrentIndexforPosts = 3
                                }
                            }
                            .padding()

                  Button("Go to previous") {
                      environmentVariables.CurrentIndexforPosts = 1
                                  }
                              }
                              .padding()
            }

        }
</code>```

答:
What a horrible MRE!! This is what you could mean and how it works:

One. you have to put .id()s on your ScrollView, otherwise scollTo doesn't know where to go.

Two. There have to be enough entries in the ScrollView. If all are visible, the scrollTo won't do anything.

```<code>class EnvironmentVariables: ObservableObject {
    @Published var currentIndexforPosts: Int = 0
}

struct ContentView: View {

    @StateObject  var environmentVariables = EnvironmentVariables()

    var body: some View {
        VStack {
            ButtonView()
            ScrollView1()
        }
        .environmentObject(environmentVariables)
    }
}

struct ScrollView1: View {

    @EnvironmentObject var environmentVariables: EnvironmentVariables

    var body: some View {

        ScrollView {
            ScrollViewReader { value in
                LazyVStack {
                    ForEach(0..<100) { i in
                        Text ("Text \(i)").id(i)
                            .font(.title)
                    }
                }

              .onChange(of: environmentVariables.currentIndexforPosts) { _ in
                    if environmentVariables.currentIndexforPosts >= 0 {
                        withAnimation {
                            value.scrollTo(environmentVariables.currentIndexforPosts, anchor: .top)
                        }
                    }
                }
            }
        }
    }
}

struct ButtonView: View {

    @EnvironmentObject var environmentVariables: EnvironmentVariables

    var body: some View {

        Button("Go to next") {
            environmentVariables.currentIndexforPosts += 10
        }
        .padding()

        Button("Go to previous") {
            environmentVariables.currentIndexforPosts -= 10
        }
    }
}
</code>```

Body:
How can I click the button from a different view and set the scroll position in a different view? the following code throws an error. I'm using environmentalObject. What I'm expecting is, when I click the buttons in ButtonView the scroll position of ScrollView1 should set to the 3rd object or 1st object in the scrollview. It works well in the same view, but does not know how to do it when it's different views.

Error: Type '()' cannot conform to 'View'

import SwiftUI

@EnvironmentObject private var environmentVariables: miscellaneousEnvironmentalVariable

struct ScrollView1: View {
var body: some View {

    ScrollView {

        ScrollViewReader { value in

            if (environmentVariables.CurrentIndexforPosts >= 0) {
                withAnimation {
                    value.scrollTo((environmentVariables.CurrentIndexforPosts), anchor: .top)}
            }

            LazyVStack {
                Text ("TEXT 1")
                Text ("TEXT 2")
                Text ("TEXT 3")
                Text ("TEXT 4")
            }

}

struct ButtonView: View {
            var body: some View {

                Button("Go to next") {
                    environmentVariables.CurrentIndexforPosts = 3
                                }
                            }
                            .padding()

                  Button("Go to previous") {
                      environmentVariables.CurrentIndexforPosts = 1
                                  }
                              }
                              .padding()
            }

        }

Body:
What a horrible MRE!! This is what you could mean and how it works:

One. you have to put .id()s on your ScrollView, otherwise scollTo doesn't know where to go.

Two. There have to be enough entries in the ScrollView. If all are visible, the scrollTo won't do anything.

class EnvironmentVariables: ObservableObject {
    @Published var currentIndexforPosts: Int = 0
}

struct ContentView: View {

    @StateObject  var environmentVariables = EnvironmentVariables()

    var body: some View {
        VStack {
            ButtonView()
            ScrollView1()
        }
        .environmentObject(environmentVariables)
    }
}

struct ScrollView1: View {

    @EnvironmentObject var environmentVariables: EnvironmentVariables

    var body: some View {

        ScrollView {
            ScrollViewReader { value in
                LazyVStack {
                    ForEach(0..<100) { i in
                        Text ("Text \(i)").id(i)
                            .font(.title)
                    }
                }

              .onChange(of: environmentVariables.currentIndexforPosts) { _ in
                    if environmentVariables.currentIndexforPosts >= 0 {
                        withAnimation {
                            value.scrollTo(environmentVariables.currentIndexforPosts, anchor: .top)
                        }
                    }
                }
            }
        }
    }
}

struct ButtonView: View {

    @EnvironmentObject var environmentVariables: EnvironmentVariables

    var body: some View {

        Button("Go to next") {
            environmentVariables.currentIndexforPosts += 10
        }
        .padding()

        Button("Go to previous") {
            environmentVariables.currentIndexforPosts -= 10
        }
    }
}


问:
How to scale down page content to fit window.print()
I have a problem with window.print function. I have a page that should fit A4 landscape page, but it doesn't. It looks like A4 page is not wide enough, so it pushes some of the content to the next page (I have 5 cards in a row, one of them is pushed to the second row). Is there any way to scale down the content without changing the width etc. of every object?</p>

答:
Of course!

You can use the print media query like this:

```<code>@media print {
    print-area *{ /* can be whatever CSS selector you need */
        transform: scale(x)
    }
}
</code>```

where x is the size you want to scale down.

Body:
Of course!

You can use the print media query like this:

@media print {
    print-area *{ /* can be whatever CSS selector you need */
        transform: scale(x)
    }
}

where x is the size you want to scale down.


问:
Can I use std::next on user defined class
If I have a user-defined class :

```<code>class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;
</code>```

Can I use std::next on objects of MyColl
If yes, then what needs to be done

答:
Can I use std::next on user defined class

You can use std::next with any class that is an iterator.

Can I use std::next on objects of MyColl

No, because MyColl is not an iterator.

You also cannot use it with MyColl::Itr, because that isn't an iterator either.

I am missing something because I am getting following error error: no type named ‘difference_type’ in ‘struct std::iterator_traits<MyColl::Itr>

The error message tells you what you're missing. You're missing std::iterator_traits<MyColl::Itr>::difference_type. Without it, MyColl::Itr is not an iterator. More generally, the class must satisfy all requirements of the iterator concept.

Body:
If I have a user-defined class :

class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;

Can I use std::next on objects of MyColl
If yes, then what needs to be done


问:
Django Rest Framework: how to route a uuid to an associated object?
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album.

I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method:

```<code>### views/album.py

class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(detail=False, methods=['get'])
    def shared(self, request):

        # How do you get the uuid from the supplied URL?
        uuid = ???
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])
</code>```

Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far:

```<code>### myapp/urls.py

router = routers.DefaultRouter()
router.register(r'albums', AlbumViewSet)
...

urlpatterns = [
    # ...
    path('', include(router.urls)),
]

format_suffix_patterns(urlpatterns)
</code>```

Thanks!

答:
Here you need to some changes in url-pattern and your action-decorater:

First Change :

/albums/shared/[uuid]  to /albums/[uuid]/shared/  According to Docs.

Second Change :

```<code>class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

                   ⬇⬇⬇⬇
    @action(detail=True, methods=['get'])
    def shared(self,request,pk=None): ⬅⬅⬅⬅
        uuid = pk
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])
</code>```

Pass UUID in url and fetch it in view... For ex.  /albums/45/shared/

Body:
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album.

I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method:

### views/album.py

class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(detail=False, methods=['get'])
    def shared(self, request):

        # How do you get the uuid from the supplied URL?
        uuid = ???
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])

Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far:

### myapp/urls.py

router = routers.DefaultRouter()
router.register(r'albums', AlbumViewSet)
...

urlpatterns = [
    # ...
    path('', include(router.urls)),
]

format_suffix_patterns(urlpatterns)

Thanks!

Body:
Here you need to some changes in url-pattern and your action-decorater:

First Change :

/albums/shared/[uuid]  to /albums/[uuid]/shared/  According to Docs.

Second Change :

class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

                   ⬇⬇⬇⬇
    @action(detail=True, methods=['get'])
    def shared(self,request,pk=None): ⬅⬅⬅⬅
        uuid = pk
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])

Pass UUID in url and fetch it in view... For ex.  /albums/45/shared/


问:
Getting an error while trying to map a list of objects
I'm trying to map below list :

```<code>mappedCustomers = customers.stream().map(e ->e.setLastName("e")).collect(Collectors.toList());
</code>```

Customer Class

```<code>@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue
Long id;

String firstName;

String lastName;

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}
</code>```

}

But I'm getting this error:

no instance(s) of type variable(s) R exist so that void conforms to R

答:
map() returns a new stream, so you can chain another operation if you need. Then, collect() returns a new list. But since you only call a setter, you end up with two lists containing the same objects. In this case, forEach() would be simpler.

customers.stream().forEach(e -> e.setLastName("e"));
```

Body:
I'm trying to map below list :

mappedCustomers = customers.stream().map(e ->e.setLastName("e")).collect(Collectors.toList());

Customer Class

@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue
Long id;

String firstName;

String lastName;

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

}

But I'm getting this error:

no instance(s) of type variable(s) R exist so that void conforms to R


问:
How to implement the startsWith function of a trie in python
I have the following implementation of a trie in python.

I want to implement the startsWith function that will return a list of all words that start with the prefix.

Currently it return tue or false. Im not sure how to get a list of words in my implementation. I believe I need some sort of dfs, but not sure how to implement it

```<code>class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in cur.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def search(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return False
            current = current.children[char]
        return current.end_of_word

    def startsWith(self, prefix):
        current = self.root
        for char in prefix:
            if char not in current.children:
                return False
            current = current.children[char]
        return True

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False

# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
obj.insert('applegate')
obj.insert('apply')
obj.insert('application')

print(obj.search('applegate'))
obj.remove('applegate')
print(obj.search('applegate'))

print(obj.startsWith('app')) -> should return a list of all words that start with 'app'

</code>```

答:
As you have logic in search and startsWith that is common, I would put that common logic in a separate method (I'll call it locate). Then on the TreeNode class you could define a recursive method that finds (yields) all words rooted at that node.

Code:

```<code>class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

    def allWords(self):
        if self.end_of_word:
            yield ""
        for char, child in self.children.items():
            for word in child.allWords():
                yield char + word

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def locate(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return
            current = current.children[char]
        return current

    def search(self, word):
        current = self.locate(word)
        return current and current.end_of_word

    def startsWith(self, prefix):
        current = self.locate(prefix)
        if not current:
            return []
        return [prefix + word for word in current.allWords()]

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False
</code>```

Body:
I have the following implementation of a trie in python.

I want to implement the startsWith function that will return a list of all words that start with the prefix.

Currently it return tue or false. Im not sure how to get a list of words in my implementation. I believe I need some sort of dfs, but not sure how to implement it

class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in cur.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def search(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return False
            current = current.children[char]
        return current.end_of_word

    def startsWith(self, prefix):
        current = self.root
        for char in prefix:
            if char not in current.children:
                return False
            current = current.children[char]
        return True

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False

# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
obj.insert('applegate')
obj.insert('apply')
obj.insert('application')

print(obj.search('applegate'))
obj.remove('applegate')
print(obj.search('applegate'))

print(obj.startsWith('app')) -> should return a list of all words that start with 'app'

Body:
As you have logic in search and startsWith that is common, I would put that common logic in a separate method (I'll call it locate). Then on the TreeNode class you could define a recursive method that finds (yields) all words rooted at that node.

Code:

class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

    def allWords(self):
        if self.end_of_word:
            yield ""
        for char, child in self.children.items():
            for word in child.allWords():
                yield char + word

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def locate(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return
            current = current.children[char]
        return current

    def search(self, word):
        current = self.locate(word)
        return current and current.end_of_word

    def startsWith(self, prefix):
        current = self.locate(prefix)
        if not current:
            return []
        return [prefix + word for word in current.allWords()]

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False


问:
Why isn't this perl prog printing about the translated text?
I am new to perl and programming in general, and I just found out about regular expressions and the substitution operator.

```<code>#!/usr/bin/perl

open(LEET, "leet.txt") or die "Can't open leet.txt: $!\n";
while($line = <LEET>) {
    $line =~ s/4/a/gi, s/3/e/gi;
}
print $line;
</code>```

Why doesn't his print anything? I want to make a leet speak translator that opens up a text file and prints out the translated text.

答:
Here's one way to do it (leet to english). You can add more keys as needed. To translate english to leet, just use a reversed hash: %english = reverse %leet;

A perhaps simpler solution is to use tr/// for the substitution. E.g. tr/43/ae/.

Code:

```<code>use strict;
use warnings;

my %leet = ( '4' => 'a', '3' => 'e' );
my $rx = join '|', keys %leet;
while (<>) {
    s/($b)/$l{$1}/eg;
    print;
}
</code>```

Usage: script.pl file.txt > output.txt

Body:
I am new to perl and programming in general, and I just found out about regular expressions and the substitution operator.

#!/usr/bin/perl

open(LEET, "leet.txt") or die "Can't open leet.txt: $!\n";
while($line = <LEET>) {
    $line =~ s/4/a/gi, s/3/e/gi;
}
print $line;

Why doesn't his print anything? I want to make a leet speak translator that opens up a text file and prints out the translated text.

Body:
Here's one way to do it (leet to english). You can add more keys as needed. To translate english to leet, just use a reversed hash: %english = reverse %leet;

A perhaps simpler solution is to use tr/// for the substitution. E.g. tr/43/ae/.

Code:

use strict;
use warnings;

my %leet = ( '4' => 'a', '3' => 'e' );
my $rx = join '|', keys %leet;
while (<>) {
    s/($b)/$l{$1}/eg;
    print;
}

Usage: script.pl file.txt > output.txt