问:
How do I move an Azure DevOps project to a different organization?
I have got a project in an old org (from VSTS), that I want to move to my new one.

I can't see any options in Azure DevOps on migrating projects, or any information on the interwebs.

Anyone know how to do it?

答:
BTW, if you need to change the entire Devops Organization tied to your personal Tenant (E.g. VS Enterprise Subscription) and move it to new Tenant, you can change the AAD and point it to the new one e.g. your EA Tenant on Azure commercial cloud.

Before you switch your organization directory, make sure the following statements are true:

You're in the Project Collection Administrator group for the
organization.

You're a member or a guest in the source Azure AD and a
member in the destination Azure AD

You have 100 or fewer users in
your source organization. Otherwise you will have to open a support ticket.

You may have to add the users back in destination org if they do not exist becuase they will loose access the moment you switch the AAD.


来源: stackexchange

问:
Javascript parse html, modify anchor tags that contain images
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

```<code><a style="color:000;" href="images/image.jpg">
    <img width="100" height="20" src="images/image_thumb.jpg" />
</a>
</code>```

I would like to change it to be:

```<code><a style="color:000;" href="images/image.jpg" rel="lightbox" >
    <img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
</code>```

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

答:
Dumbest regexp</p>

```<code>var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
    text = '';

text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

I would like to change it to be:

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

Body:
Dumbest regexp

var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
    text = '';

text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');


问:
react filter array when user clicks elements with same values
I am trying to build simple puzzle application for my personal react project.

Basically, I have made an array with objects and map through this array to render puzzle lists.

```<code>const puzzleData = [
  { id: Math.random() * 5, value: '<main>', key: 'main' },
  { id: Math.random() * 5, value: '</main>', key: 'main' },
  { id: Math.random() * 5, value: '<section>', key: 'section' },
  { id: Math.random() * 5, value: '</section>', key: 'section' },
  { id: Math.random() * 5, value: '<nav>', key: 'nav' },
  { id: Math.random() * 5, value: '</nav>', key: 'nav' },
  { id: Math.random() * 5, value: '<footer>', key: 'footer' },
  { id: Math.random() * 5, value: '</footer>', key: 'footer' },
  { id: Math.random() * 5, value: '<aside>', key: 'aside' },
  { id: Math.random() * 5, value: '</aside>', key: 'aside' },
  { id: Math.random() * 5, value: '<h1>', key: 'h1' },
  { id: Math.random() * 5, value: '</h1>', key: 'h1' },
  { id: Math.random() * 5, value: '<p>', key: 'p' },
  { id: Math.random() * 5, value: '</p>', key: 'p' },
  { id: Math.random() * 5, value: '<span>', key: 'span' },
  { id: Math.random() * 5, value: '</span>', key: 'span' },
];

const [puzzle, setPuzzle] = useState([...puzzleData]);

<ul className={styles.puzzle}>
        {puzzle.map((item, i) => {
          return (
            <li
              key={item.id}
              onClick={() => {
                filterHandler(item.key, item.id);
              }}
              style={{ backgroundColor: color.id === item.id ? 'white' : null }}
            >
              {item.value}
            </li>
          );
        })}
      </ul>
</code>```

I want my filterHandler function applied onClick to filter puzzle array when user clicks same li elements with same key value. For example, when user clicks main and /main in li elements, filter puzzle array to remove those two from the rendered elements. Below is my current filterHandler function.

```<code>const filterHandler = (key, id) => {
setPuzzle((prevState) => {
      const updated = prevState.filter(
        (item) => item.key !== key || item.id !== id
      );
      return updated;
    });
</code>```

Right now, it is filtering out li element that user clicks but I want to filtering out li element when user clicks two same elements with same key values (like real puzzle game). Is there a way to apply this logic with filter method? Thanks in advance!

答:
You will have to maintain a state variable in order to keep a track of which element the user has clicked before allowing the user to make the second click. In that way you will have the previously clicked element stored with you which you can compare with the user's second element click.

```<code>const [lastElementClick, setLastElementClick] = useState("")
</code>```

Now within your filterHandler() function, we can at any given time check if the last element clicked matches our current key. Also I removed the second condition inside your filter condition (this was needed to remove both the elements, otherwise only the last clicked element will be removed)

```<code>  const filterHandler = (key, id) => {
    if(lastElementClick === key) {
      setPuzzle((prevState) => {
        const updated = prevState.filter(
          (item) => item.key !== key
        );
        return updated;
      });
      setLastElementClick(key)
    } else {
      setLastElementClick(key)
    }
  };
</code>```

UPDATE: In order to prevent removal of block by clicking the same element twice, we should add another check in our if condition. We are already matching if lastElement matches our current key, now we can add a condition to make sure that lastElement's id does not match the current id (i.e, same element is not clicked)

For this reason I'm going to update the state variable to hold both the key and id of the last element clicked

```<code>const [lastElementClick, setLastElementClick] = useState({ id: "", key: "" });
</code>```

After that we can update the if condition by also checking for the id:

```<code>const filterHandler = (key, id) => {
    if (lastElementClick.key === key && lastElementClick.id !== id) {
      const updated = puzzle.filter((item) => item.key !== key);
      setPuzzle(updated);
      setLastElementClick({ key, id });
    } else {
      setLastElementClick({ key, id });
    }
  };
</code>```

I have also updated the code in the below link, you can try that out too,

Here's a link to the full working code: https://codesandbox.io/s/modest-williams-lun0f?file=/src/App.js:1223-1539

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build simple puzzle application for my personal react project.

Basically, I have made an array with objects and map through this array to render puzzle lists.

const puzzleData = [
  { id: Math.random() * 5, value: '', key: 'main' },
  { id: Math.random() * 5, value: '', key: 'main' },
  { id: Math.random() * 5, value: '
', key: 'section' },
  { id: Math.random() * 5, value: '
', key: 'section' },
  { id: Math.random() * 5, value: '', key: 'nav' },
  { id: Math.random() * 5, value: '', key: 'nav' },
  { id: Math.random() * 5, value: '', key: 'footer' },
  { id: Math.random() * 5, value: '', key: 'footer' },
  { id: Math.random() * 5, value: '', key: 'aside' },
  { id: Math.random() * 5, value: '', key: 'aside' },
  { id: Math.random() * 5, value: '
', key: 'h1' },
  { id: Math.random() * 5, value: '
', key: 'h1' },
  { id: Math.random() * 5, value: '
', key: 'p' },
  { id: Math.random() * 5, value: '
', key: 'p' },
  { id: Math.random() * 5, value: '', key: 'span' },
  { id: Math.random() * 5, value: '', key: 'span' },
];

const [puzzle, setPuzzle] = useState([...puzzleData]);

        {puzzle.map((item, i) => {
          return (

 {
                filterHandler(item.key, item.id);
              }}
              style={{ backgroundColor: color.id === item.id ? 'white' : null }}
            >
              {item.value}

          );
        })}

I want my filterHandler function applied onClick to filter puzzle array when user clicks same li elements with same key value. For example, when user clicks main and /main in li elements, filter puzzle array to remove those two from the rendered elements. Below is my current filterHandler function.

const filterHandler = (key, id) => {
setPuzzle((prevState) => {
      const updated = prevState.filter(
        (item) => item.key !== key || item.id !== id
      );
      return updated;
    });

Right now, it is filtering out li element that user clicks but I want to filtering out li element when user clicks two same elements with same key values (like real puzzle game). Is there a way to apply this logic with filter method? Thanks in advance!

Body:
You will have to maintain a state variable in order to keep a track of which element the user has clicked before allowing the user to make the second click. In that way you will have the previously clicked element stored with you which you can compare with the user's second element click.

const [lastElementClick, setLastElementClick] = useState("")

Now within your filterHandler() function, we can at any given time check if the last element clicked matches our current key. Also I removed the second condition inside your filter condition (this was needed to remove both the elements, otherwise only the last clicked element will be removed)

  const filterHandler = (key, id) => {
    if(lastElementClick === key) {
      setPuzzle((prevState) => {
        const updated = prevState.filter(
          (item) => item.key !== key
        );
        return updated;
      });
      setLastElementClick(key)
    } else {
      setLastElementClick(key)
    }
  };

UPDATE: In order to prevent removal of block by clicking the same element twice, we should add another check in our if condition. We are already matching if lastElement matches our current key, now we can add a condition to make sure that lastElement's id does not match the current id (i.e, same element is not clicked)

For this reason I'm going to update the state variable to hold both the key and id of the last element clicked

const [lastElementClick, setLastElementClick] = useState({ id: "", key: "" });

After that we can update the if condition by also checking for the id:

const filterHandler = (key, id) => {
    if (lastElementClick.key === key && lastElementClick.id !== id) {
      const updated = puzzle.filter((item) => item.key !== key);
      setPuzzle(updated);
      setLastElementClick({ key, id });
    } else {
      setLastElementClick({ key, id });
    }
  };

I have also updated the code in the below link, you can try that out too,

Here's a link to the full working code: https://codesandbox.io/s/modest-williams-lun0f?file=/src/App.js:1223-1539


问:
Different types of passing parameters to a recursive function
The below code worked perfectly fine.

```<code>        def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                cur.append(i)
                perm(cur)
                cur.pop()

        perm([])
        return res
</code>```

However, the below one returned error

```<code>         def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                perm(cur.append(i))
                cur.pop()

        perm([])
        return res
</code>```
```<code>TypeError: argument of type 'NoneType' is not iterable
    avail = [i for i in nums if not i in cur]
Line 5 in <listcomp> (Solution.py)
    avail = [i for i in nums if not i in cur]
Line 5 in perm (Solution.py)
    perm(cur.append(i))
Line 12 in perm (Solution.py)
    perm([])
Line 15 in permute (Solution.py)
    ret = Solution().permute(param_1)
Line 38 in _driver (Solution.py)
    _driver()
Line 49 in <module> (Solution.py)
</code>```

I'm trying to understand the logic behind this.

I'm not sure of the difference between both ways of parameter passing.

答:
Function cur.append(i) doesn't return anything. It only appends i to cur list.

Then when you call perm with it as an argument, you basically calling perm(None), which is not iterable. Therefore [i for i in nums if not i in cur] fails.

Body:
The below code worked perfectly fine.

        def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                cur.append(i)
                perm(cur)
                cur.pop()

        perm([])
        return res

However, the below one returned error

         def perm(cur):
            avail = [i for i in nums if not i in cur]
            if len(avail) == 0:
                res.append(cur.copy())
                return

            for i in avail:
                perm(cur.append(i))
                cur.pop()

        perm([])
        return res

TypeError: argument of type 'NoneType' is not iterable
    avail = [i for i in nums if not i in cur]
Line 5 in <listcomp> (Solution.py)
    avail = [i for i in nums if not i in cur]
Line 5 in perm (Solution.py)
    perm(cur.append(i))
Line 12 in perm (Solution.py)
    perm([])
Line 15 in permute (Solution.py)
    ret = Solution().permute(param_1)
Line 38 in _driver (Solution.py)
    _driver()
Line 49 in <module> (Solution.py)

I'm trying to understand the logic behind this.

I'm not sure of the difference between both ways of parameter passing.


问:
Creating on/off button in react
I am making a button that is going to say "disable" when its on and "enable" when its off. how do I do that in react?? I have tried to make it but I have no idea where to even start, is there some syntax im missing?</p>

答:
The code below does the job of displaying the button text based on a state.
Inside the useState() hook you can specify the initial state.
On the button's click event the state will be reversed to toggle between true and false

```<code>const customButton = () => {
 const [enabled, setEnabled] = useState(false);

 return (
  <button
    onClick={() => setEnabled(!enabled)}>
    {enabled ? "disable" : "enable"}
  </button>
 );
}

</code>```

Title: Creating on/off button in react

Body:
The code below does the job of displaying the button text based on a state.
Inside the useState() hook you can specify the initial state.
On the button's click event the state will be reversed to toggle between true and false

const customButton = () => {
 const [enabled, setEnabled] = useState(false);

 return (
  <button
    onClick={() => setEnabled(!enabled)}>
    {enabled ? "disable" : "enable"}
  </button>
 );
}


问:
forEach and assign to variable
This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don't know why it works that way.

```<code>const numbers = [1, 2, 3];

let exampleId: number;

numbers.forEach(function(number) {
  exampleId = number;
});

console.log(exampleId);
</code>```

Why do I get the error "Variable 'exampleId' is used before being assigned." in the line from console.log?

答:
The way to select the value of the last element from an array is

```<code>function lastElementOfArray(arr = []) {
  return arr.length > 0
    ? arr[ arr.length - 1 ]
    : undefined
    ;
}
</code>```

The reason you get Variable 'exampleId' is used before being assigned. is because there's no guarantee that the Array.forEach() callback that assigns a value to exampleId will ever be invoked (e.g., when the array numbers has a length of 0).

And so, you get that message on the line

```<code>console.log(exampleId)
</code>```

Title: forEach and assign to variable

Body:
This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don't know why it works that way.

const numbers = [1, 2, 3];

let exampleId: number;

numbers.forEach(function(number) {
  exampleId = number;
});

console.log(exampleId);

Why do I get the error "Variable 'exampleId' is used before being assigned." in the line from console.log?

Body:
The way to select the value of the last element from an array is

function lastElementOfArray(arr = []) {
  return arr.length > 0
    ? arr[ arr.length - 1 ]
    : undefined
    ;
}

The reason you get Variable 'exampleId' is used before being assigned. is because there's no guarantee that the Array.forEach() callback that assigns a value to exampleId will ever be invoked (e.g., when the array numbers has a length of 0).

And so, you get that message on the line

console.log(exampleId)


问:
How to set that data whole area in gridview?
Hello, I am using the dataGridview control to display some data, but my problem is I have one or two columns of data, the columns  will appear in  a small part in gridview instead of filling all available space. I want the data to take up all available area in the datagrid. How can I do This? thank you!</p>

答:
You have to set the Column Fill mode.

http://msdn.microsoft.com/en-us/library/ms171605.aspx


问:
My sticky positioned element isn't acting like it should
Usually, I don't have any issues with the sticky position property.
However, I can't figure out why my div isn't behaving so.

See the issue here : my link

The reservation part .practitionerRight #reservation on the right is wrapped within a higher div .practitionerRight.

It should stick to top: 80px but it doesn't. I read the Stack Overflow topics about sticky positioning but couldn't find the solution there.

Here is the actual css code :

```<code>position: -webkit-sticky;
position: sticky;
top: 80px;
</code>```

Thanks to those who will try to help me.

答:
You're div with the id of main has overflow-x: hidden. That div is the parent of the child that you want sticky and overflow hidden doesn't play well with position: sticky. Remove the overflow-x: hidden css and it works (line #118 in your style.css):

```<code>#main{
min-height:100%;
width: 100%;
/* overflow-x: hidden; */ //remove this
}
</code>```

There's nothing overflowing, anyhow.

Body:
Usually, I don't have any issues with the sticky position property.
However, I can't figure out why my div isn't behaving so.

See the issue here : my link

The reservation part .practitionerRight #reservation on the right is wrapped within a higher div .practitionerRight.

It should stick to top: 80px but it doesn't. I read the Stack Overflow topics about sticky positioning but couldn't find the solution there.

Here is the actual css code :

position: -webkit-sticky;
position: sticky;
top: 80px;

Thanks to those who will try to help me.

Body:
You're div with the id of main has overflow-x: hidden. That div is the parent of the child that you want sticky and overflow hidden doesn't play well with position: sticky. Remove the overflow-x: hidden css and it works (line #118 in your style.css):

#main{
min-height:100%;
width: 100%;
/* overflow-x: hidden; */ //remove this
}

There's nothing overflowing, anyhow.


问:
A value is trying to be set on a copy of a slice from a DataFrame. - pandas
I'm new to pandas, and, given a data frame, I was trying to drop some columns that don't accomplish an specific requirement. Researching how to do it, I got to this structure:

```<code>df = df.loc[df['DS_FAMILIA_PROD'].isin(['CARTOES', 'CARTÕES'])]
</code>```

However, when processing the frame, I get this error:

```<code>A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self[name] = value
</code>```

I'm not sure about what to do because I'm already using the .loc function.
What am I missing?

```<code>f = ['ID_manifest', 'issue_date', 'channel', 'product', 'ID_client', 'desc_manifest']

df = pd.DataFrame(columns=f)
for chunk in df2017_chunks:
    aux = preProcess(chunk, f)
    df = pd.concat([df, aux])

def preProcess(df, f):
    stops = list(stopwords.words("portuguese"))
    stops.extend(['reclama', 'cliente', 'santander', 'cartao', 'cartão'])

    df = df.loc[df['DS_FAMILIA_PROD'].isin(['CARTOES', 'CARTÕES'])]

    df.columns = f
    df.desc_manifest = df.desc_manifest.str.lower() # All lower case
    df.desc_manifest = df.desc_manifest.apply(lambda x: re.sub('[^A-zÀ-ÿ]', ' ', str(x))) # Just letters
    df.replace(['NaN', 'nan'], np.nan, inplace = True) # Remone nan
    df.dropna(subset=['desc_manifest'], inplace=True)
    df.desc_manifest = df.desc_manifest.apply(lambda x: [word for word in str(x).split() if word not in stops]) # Remove stop words

    return df
</code>```

答:
If your program intends to take a copy of the df on purpose, you can stop the warning with this:</p>
```<code>pd.set_option('mode.chained_assignment', None)
</code>```

Body:
I'm new to pandas, and, given a data frame, I was trying to drop some columns that don't accomplish an specific requirement. Researching how to do it, I got to this structure:

df = df.loc[df['DS_FAMILIA_PROD'].isin(['CARTOES', 'CARTÕES'])]

However, when processing the frame, I get this error:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self[name] = value

I'm not sure about what to do because I'm already using the .loc function.
What am I missing?

f = ['ID_manifest', 'issue_date', 'channel', 'product', 'ID_client', 'desc_manifest']

df = pd.DataFrame(columns=f)
for chunk in df2017_chunks:
    aux = preProcess(chunk, f)
    df = pd.concat([df, aux])

def preProcess(df, f):
    stops = list(stopwords.words("portuguese"))
    stops.extend(['reclama', 'cliente', 'santander', 'cartao', 'cartão'])

    df = df.loc[df['DS_FAMILIA_PROD'].isin(['CARTOES', 'CARTÕES'])]

    df.columns = f
    df.desc_manifest = df.desc_manifest.str.lower() # All lower case
    df.desc_manifest = df.desc_manifest.apply(lambda x: re.sub('[^A-zÀ-ÿ]', ' ', str(x))) # Just letters
    df.replace(['NaN', 'nan'], np.nan, inplace = True) # Remone nan
    df.dropna(subset=['desc_manifest'], inplace=True)
    df.desc_manifest = df.desc_manifest.apply(lambda x: [word for word in str(x).split() if word not in stops]) # Remove stop words

    return df

Body:
If your program intends to take a copy of the df on purpose, you can stop the warning with this:

pd.set_option('mode.chained_assignment', None)


问:
Why can't my .NET 6 Minimal API deserialize POST body?
I've build a very simple, vanilla minimal API with .NET 6. All I'm trying to do for now is prove that I can receive HTTP POST requests and log them. Hopefully if I can get this working I'll start doing something more interesting, but even this vanilla out of the box functionality isn't working.

Some things I've tried:

Changing my logMessage to a record

Adding a default constructor to the logMessage

My full code is posted below, can anyone see what is wrong with this? Or how to fix it?

My minimal API:

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// NOTE: tried the below but it made no difference. Commented back out.
// builder.Services.Configure<JsonOptions>(options =>
// {
//     options.SerializerOptions.IncludeFields = true;
// });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.MapPost("/", (logMessage message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received message:");
    Console.WriteLine(message.LogMessage);
    return Results.Accepted;
});

app.Run("http://localhost:5025");

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class logMessage
{
    public string? LogMessage {get;set;}
}
```
<p>My post message (testing from Postman, but also tried sending from various other places):</p>
<pre class="lang-json prettyprint-override"><code>{
    "LogMessage":"test"
}
</code>```

The result:

```<code>System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported. Path: $.Method.ReturnParameter.Member.DeclaringType.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported.
   at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.HttpResponseJsonExtensions.WriteAsJsonAsyncSlow[TValue](Stream body, TValue value, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

Same result if I try from the Swagger page.

答:
Results.Accepted is a method so you need to invoke it:

app.MapPost("/", (logMessage message) =>
{
    ...
    return Results.Accepted();
});
```

Otherwise it is converted to delegate (Func<string, object, IResult> in this case) which can not be serialized (so you see the exception in question).

Body:
I've build a very simple, vanilla minimal API with .NET 6. All I'm trying to do for now is prove that I can receive HTTP POST requests and log them. Hopefully if I can get this working I'll start doing something more interesting, but even this vanilla out of the box functionality isn't working.

Some things I've tried:

Changing my logMessage to a record

Adding a default constructor to the logMessage

My full code is posted below, can anyone see what is wrong with this? Or how to fix it?

My minimal API:

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// NOTE: tried the below but it made no difference. Commented back out.
// builder.Services.Configure<JsonOptions>(options =>
// {
//     options.SerializerOptions.IncludeFields = true;
// });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.MapPost("/", (logMessage message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received message:");
    Console.WriteLine(message.LogMessage);
    return Results.Accepted;
});

app.Run("http://localhost:5025");

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class logMessage
{
    public string? LogMessage {get;set;}
}

My post message (testing from Postman, but also tried sending from various other places):

{
    "LogMessage":"test"
}

The result:

System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported. Path: $.Method.ReturnParameter.Member.DeclaringType.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported.
   at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.HttpResponseJsonExtensions.WriteAsJsonAsyncSlow[TValue](Stream body, TValue value, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Same result if I try from the Swagger page.

Body:
Results.Accepted is a method so you need to invoke it:

app.MapPost("/", (logMessage message) =>
{
    ...
    return Results.Accepted();
});

Otherwise it is converted to delegate (Func<string, object, IResult> in this case) which can not be serialized (so you see the exception in question).


问:
Do rolling on all dataframe rows
I would like to find in dataframe of prices all all-time highs in that were in history.

timestamp
close
ath

x
1234
0

x
2000
1

x
1956
0

x
1884
0

x
2234
1

So for specific row I would like to find a maximum for all previous rows and check if value in current row is greater than this maximum. I cannot do it without indexing for all rows and I know that it is inefficient.

答:
FWIW, here is an alternative:</p>
```<code>df['ath'] = (df['close'] > df['close'].expanding().max().shift()).astype(int)
</code>```

Title: Do rolling on all dataframe rows

Body:
FWIW, here is an alternative:

df['ath'] = (df['close'] > df['close'].expanding().max().shift()).astype(int)


问:
Compare list column to a second list and return item in third list
Have a dataframe with a list column like and two reference lists:

```<code>d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)

ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']

    col1    col2
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]
3   4   [a, b, d]
4   5   [a, b, e]
</code>```

And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b

```<code>col1    col2    check
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]   option1
3   4   [a, b, d]   option2
4   5   [a, b, e]   option3
</code>```

I've tried something like this:

```<code>for index, row in df.iterrows():
    for (a, b) in zip(ref_a, ref_b):
        if a in row['col2']:
            df.loc[index, 'check'] = b
            print('true', b)
        else:
            df.loc[index, 'check'] = ''
</code>```

And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.

答:
Here's another approach if you think it's more elegant:

def get_option(xs):
    for x in xs:
        if x in ref_a:
            return ref_b[ref_a.index(x)]
    return 'no option' # or None or np.nan?

df['check'] = df['col2'].apply(get_option)

print(df)
```

Body:
Have a dataframe with a list column like and two reference lists:

d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)

ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']

    col1    col2
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]
3   4   [a, b, d]
4   5   [a, b, e]

And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b

col1    col2    check
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]   option1
3   4   [a, b, d]   option2
4   5   [a, b, e]   option3

I've tried something like this:

for index, row in df.iterrows():
    for (a, b) in zip(ref_a, ref_b):
        if a in row['col2']:
            df.loc[index, 'check'] = b
            print('true', b)
        else:
            df.loc[index, 'check'] = ''

And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.


问:
Why "Branch" test coverage in Jest shows 0% coverage?
One of my test coverage is as below:

branch 0%

function 75%

lines 81.25%

I see total 3 lines: 16, 27 and 38 under uncovered lines. I confirm that by looking at coverage/Icov-report/index.html (WIP for improving unit test).

Would missing 3 lines of coverage cause branch coverage to be 0%? I would expect something rather than 0% but I am learning Jest so not sure.

Repository info: TypeScript, Node, Jest

Code Coverage:

Index.html report

service.ts

```<code>import { injectable } from 'inversify';
import { createLogger, format, Logger } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import fs from 'fs';

const logDir = 'logs';

@injectable()
export default class LoggerService {
  private readonly winstonLogger: Logger;

  private static loggerService: LoggerService;

  constructor() {
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir);
    }

    const dailyRotateFileTransport = new DailyRotateFile({
      filename: `${logDir}/%DATE%-results.log`,
      datePattern: 'YYYY-MM-DD',
    });

    this.winstonLogger = createLogger({
      format: format.combine(
        format.timestamp(),
        format.printf((info) => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message)}`),
      ),
      transports: [
        dailyRotateFileTransport,
      ],
      exitOnError: false,
    });
  }

  static get Instance() {
    if (this.loggerService) {
      return this.loggerService;
    }
    this.loggerService = new LoggerService();
    return this.loggerService;
  }

  public get logger() {
    return this.winstonLogger;
  }
}

</code>```

service.spec.ts

```<code>const logger = {
  debug: jest.fn(),
  log: jest.fn(),
};

// trying to mock createLogger to return a specific logger instance
jest.mock('winston', () => ({
  format: {
    combine: jest.fn(),
    timestamp: jest.fn(),
    printf: jest.fn(),
  },
  createLogger: jest.fn().mockReturnValue(logger),
  transports: {
    File: jest.fn(),
  },
}));

import 'reflect-metadata';
import * as winston from 'winston';
import LoggerService from '../logger.service';

describe('loggerService', () => {
  let loggerMock: winston.Logger;

  afterAll(() => {
    jest.resetModules();
    jest.resetAllMocks();
  });

  it('logger function called', () => {
    const mockCreateLogger = jest.spyOn(winston, 'createLogger');
    const loggingService: LoggerService = LoggerService.Instance;
    loggerMock = mockCreateLogger.mock.instances[0];
    expect(loggingService).toBeInstanceOf(LoggerService);
    expect(loggingService).toBeDefined();
    expect(mockCreateLogger).toHaveBeenCalled();

    logger.log('debug', 'test log debug');
    expect(logger.log).toHaveBeenCalled();

    loggingService.logger.debug('debug message');
    expect(logger.debug).toHaveBeenCalledTimes(1);
  });
});

</code>```

答:
Looks like 0% means you missed testing all ifs that are definitely goes to the category Branch.

Try to add tests for one of ifs and see if % Branch will become something like 50%

Body:
One of my test coverage is as below:

branch 0%

function 75%

lines 81.25%

I see total 3 lines: 16, 27 and 38 under uncovered lines. I confirm that by looking at coverage/Icov-report/index.html (WIP for improving unit test).

Would missing 3 lines of coverage cause branch coverage to be 0%? I would expect something rather than 0% but I am learning Jest so not sure.

Repository info: TypeScript, Node, Jest

Code Coverage:

Index.html report

service.ts

import { injectable } from 'inversify';
import { createLogger, format, Logger } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import fs from 'fs';

const logDir = 'logs';

@injectable()
export default class LoggerService {
  private readonly winstonLogger: Logger;

  private static loggerService: LoggerService;

  constructor() {
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir);
    }

    const dailyRotateFileTransport = new DailyRotateFile({
      filename: `${logDir}/%DATE%-results.log`,
      datePattern: 'YYYY-MM-DD',
    });

    this.winstonLogger = createLogger({
      format: format.combine(
        format.timestamp(),
        format.printf((info) => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message)}`),
      ),
      transports: [
        dailyRotateFileTransport,
      ],
      exitOnError: false,
    });
  }

  static get Instance() {
    if (this.loggerService) {
      return this.loggerService;
    }
    this.loggerService = new LoggerService();
    return this.loggerService;
  }

  public get logger() {
    return this.winstonLogger;
  }
}

service.spec.ts

const logger = {
  debug: jest.fn(),
  log: jest.fn(),
};

// trying to mock createLogger to return a specific logger instance
jest.mock('winston', () => ({
  format: {
    combine: jest.fn(),
    timestamp: jest.fn(),
    printf: jest.fn(),
  },
  createLogger: jest.fn().mockReturnValue(logger),
  transports: {
    File: jest.fn(),
  },
}));

import 'reflect-metadata';
import * as winston from 'winston';
import LoggerService from '../logger.service';

describe('loggerService', () => {
  let loggerMock: winston.Logger;

  afterAll(() => {
    jest.resetModules();
    jest.resetAllMocks();
  });

  it('logger function called', () => {
    const mockCreateLogger = jest.spyOn(winston, 'createLogger');
    const loggingService: LoggerService = LoggerService.Instance;
    loggerMock = mockCreateLogger.mock.instances[0];
    expect(loggingService).toBeInstanceOf(LoggerService);
    expect(loggingService).toBeDefined();
    expect(mockCreateLogger).toHaveBeenCalled();

    logger.log('debug', 'test log debug');
    expect(logger.log).toHaveBeenCalled();

    loggingService.logger.debug('debug message');
    expect(logger.debug).toHaveBeenCalledTimes(1);
  });
});


问:
Could managed code (specifically .NET) ever become 'unmanaged'?
Recently I was talking with a friend of mine who had started a C++ class a couple months ago (his first exposure to programming). We got onto the topic of C# and .NET generally, and he made the point to me that he felt it was 'doomed' for all of the commonly-cited issues (low speed, breakable bytecode, etc). I agreed with him on all those issues, but I held back in saying it was doomed, only because I felt that, in time, languages like C# could instead become native code (if Microsoft so chose to change the implementation of .NET from a bytecode, JIT runtime environemnent to one which compiles directly to native code like your C++ program does).

My question is, am I out to lunch here? I mean, it may take a lot of work (and may break too many things), but there isn't some type of magical barrier which prevents C# code from being compiled natively (if one wanted to do it), right? There was a time where C++ was considered a very high-level language (which it still is, but not as much as in the past) yet now it's the bedrock (along with C) for Microsoft's native APIs. The idea that .NET could one day be on the same level as C++ in that respect seems only to be a matter of time and effort to me, not some fundamental flaw in the design of the language.

EDIT: I should add that if native compilation of .NET is possible, why does Microsoft choose not to go that route? Why have they chosen the JIT bytecode path?

答: C# could be natively compiled but it is unlikely the base class library will ever go there. On the flip side, I really don't see much advantage to moving beyond JIT.</p>

OwnerDisplayName: GRB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Andrew Robinson


问:
Database Design For Developing 'Quiz' Web Application using PHP and MySQL
So, I'm trying to learn PHP and MySQL (I have a basic understanding of both; I've read the first half of both Head First SQL and Head First PHP & MySQL) and I figure the best way to solidify my knowledge is by building something rather than reading.

With that in mind, I would like to create a basic webpage that connects to a MySQL database on a server.  I will build a basic HTML form and allow users to input basic information, such as: last_name, first_name, email, birthday, gender.

My problem is I don't know how to design a database that will record the results of a basic quiz - I want just 5 multiple-choice problems.  Eventually, I would like to display the results of the user versus the previous users' results.

If you could help me understand how to design table(s) for a 5-question Quiz I'd appreciate it.  Thanks!

答:
I would start with 4 simple tables:

Users

```<code>- user_id        auto integer
- regtime        datetime
- username       varchar
- useremail      varchar
- userpass       varchar
</code>```

Questions

```<code>- question_id    auto integer
- question       varchar
- is_active      enum(0,1)
</code>```

Question_choices

```<code>- choice_id        auto integer
- question_id      Questions.question_id
- is_right_choice  enum(0,1)
- choice           varchar
</code>```

User_question_answers

```<code>- user_id        Users.user_id
- question_id    Questions.question_id
- choice_id      Question_choices.choice.id
- is_right       enum(0,1)
- answer_time    datetime
</code>```

My thought on this table design is:

table Users is for storing registered user.

table Questions is for storing all your questions.

It has is_active so that you can selectively display only active questions (using WHERE is_active = '1')

table question_choices is for storing all available options. It has is_right_choice which defines what choice is the right answer for particular question.

Table User_question_answers is for storing answer from your user.

It has is_right for faster lookup, to see whether that particular question and answer choice is right (based on is_right_choice previously defined).

It also has answer_time just to note when that particular user answer the question.

Body:
I would start with 4 simple tables:

Users

- user_id        auto integer
- regtime        datetime
- username       varchar
- useremail      varchar
- userpass       varchar

Questions

- question_id    auto integer
- question       varchar
- is_active      enum(0,1)

Question_choices

- choice_id        auto integer
- question_id      Questions.question_id
- is_right_choice  enum(0,1)
- choice           varchar

User_question_answers

- user_id        Users.user_id
- question_id    Questions.question_id
- choice_id      Question_choices.choice.id
- is_right       enum(0,1)
- answer_time    datetime

My thought on this table design is:

table Users is for storing registered user.

table Questions is for storing all your questions.

It has is_active so that you can selectively display only active questions (using WHERE is_active = '1')

table question_choices is for storing all available options. It has is_right_choice which defines what choice is the right answer for particular question.

Table User_question_answers is for storing answer from your user.

It has is_right for faster lookup, to see whether that particular question and answer choice is right (based on is_right_choice previously defined).

It also has answer_time just to note when that particular user answer the question.


问:
Logical NAND of two variables in Python
I'm making a function that makes 50 random trees in a 1000 by 1000 area.

I need to make sure that Tree 2's x and y both are not the same as Tree 1's x and y. This takes a NAND Gate. I'm okay with one of them being the same, I'm okay with neither being the same, but not with both being the same. I can't seem to find anything about making NAND Gates in python. I'm fine with defining a function to make a NAND.

答:
This will provide all six logic gate functions (including nand) in a dictionary:

```<code>from operator import and_, or_, xor

gates = {g.__name__.rstrip('_'): g for g in (and_, or_, xor)}
gates = {**gates, **{f'n{k}': lambda a, b, _f=v: _f(a, b) ^ True for k, v in gates.items()}}
</code>```

x ^ y means xor(x, y). x ^ True means xor(x, True) which means not x.

Usage

```<code>>>> gates
{'and': <function _operator.and_(a, b, /)>,
 'or': <function _operator.or_(a, b, /)>,
 'xor': <function _operator.xor(a, b, /)>,
 'nand': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function and_>)>,
 'nor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function or_>)>,
 'nxor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function xor>)>}

>>> gates['and'](True, True)
True

>>> gates['and'](1, 1)
1

>>> gates['nand'](True, True)
False

>>> gates['nand'](1, 1)
0
</code>```

Title: Logical NAND of two variables in Python

Body:
This will provide all six logic gate functions (including nand) in a dictionary:

from operator import and_, or_, xor

gates = {g.__name__.rstrip('_'): g for g in (and_, or_, xor)}
gates = {**gates, **{f'n{k}': lambda a, b, _f=v: _f(a, b) ^ True for k, v in gates.items()}}

x ^ y means xor(x, y). x ^ True means xor(x, True) which means not x.

Usage

>>> gates
{'and': <function _operator.and_(a, b, /)>,
 'or': <function _operator.or_(a, b, /)>,
 'xor': <function _operator.xor(a, b, /)>,
 'nand': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function and_>)>,
 'nor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function or_>)>,
 'nxor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function xor>)>}

>>> gates['and'](True, True)
True

>>> gates['and'](1, 1)
1

>>> gates['nand'](True, True)
False

>>> gates['nand'](1, 1)
0


答:
Use cummax to keep the highest seen value then shift rows and compare to the current row:

```<code>df['ath'] = df['close'].gt(df['close'].cummax().shift()).astype(int)
print(df)

# Output
  timestamp  close  ath
0         x   1234    0
1         x   2000    1
2         x   1956    0
3         x   1884    0
4         x   2234    1
</code>```

Title: Do rolling on all dataframe rows

Body:
I would like to find in dataframe of prices all all-time highs in that were in history.

timestamp
close
ath

x
1234
0

x
2000
1

x
1956
0

x
1884
0

x
2234
1

So for specific row I would like to find a maximum for all previous rows and check if value in current row is greater than this maximum. I cannot do it without indexing for all rows and I know that it is inefficient.

Body:
Use cummax to keep the highest seen value then shift rows and compare to the current row:

df['ath'] = df['close'].gt(df['close'].cummax().shift()).astype(int)
print(df)

# Output
  timestamp  close  ath
0         x   1234    0
1         x   2000    1
2         x   1956    0
3         x   1884    0
4         x   2234    1


问:
Z3,C++ API, How to convert bool sort to int sort
I am using Z3 in C++, and I have some bool-sort exprs.

What I want to do is to count the number of true-value exprs.

A very simple way is to convert those expr into int-sort and then add them up.

However I don't know how to convert bool to int.

Thanks!

SOLUTION:

As the cpp example file shows(function ite_example2()):

```<code>expr b = c.bool_const("x");
expr x = c.int_val(1);
expr y = c.int_val(0);
expr conj = ite(b,x,y);
</code>```

答:
There are built-in functions in Z3 for counting "k amongst N" and other variants.

They should usually be preferred as they offer better performance due to dedicated strategies.

```<code>((_ at-most k) x y z)
</code>```

this means at most k of the Booleans x, y, z... are true.

See this other question for more details, and the comment by Nikolaj Bjorner on the answer for the SMT syntax of the variants.

K-out-of-N constraint in Z3Py

Body:
I am using Z3 in C++, and I have some bool-sort exprs.

What I want to do is to count the number of true-value exprs.

A very simple way is to convert those expr into int-sort and then add them up.

However I don't know how to convert bool to int.

Thanks!

SOLUTION:

As the cpp example file shows(function ite_example2()):

expr b = c.bool_const("x");
expr x = c.int_val(1);
expr y = c.int_val(0);
expr conj = ite(b,x,y);

Body:
There are built-in functions in Z3 for counting "k amongst N" and other variants.

They should usually be preferred as they offer better performance due to dedicated strategies.

((_ at-most k) x y z)

this means at most k of the Booleans x, y, z... are true.

See this other question for more details, and the comment by Nikolaj Bjorner on the answer for the SMT syntax of the variants.

K-out-of-N constraint in Z3Py


问:
Nest.js raw bodyParser doesn't fire json function
I need to get raw body request for generating signature.
and when i found solution i faced with issue that json function not working
example below :</p>
```<code>import { Injectable, NestMiddleware } from '@nestjs/common';
import { json } from 'body-parser';
import { IncomingMessage } from 'http';

@Injectable()
export class RawBodyMiddlewareMiddleware implements NestMiddleware {
  public use(req: IncomingMessage, res, next: () => any): any {
    json({ //json function not fired
      verify: (req, res, buffer) => {
        console.log(buffer);
        if (Buffer.isBuffer(buffer)) {
          const rawBody = Buffer.from(buffer);
          req['parsedRawBody'] = rawBody;
        }
        return true;
      },
    })(req, res as any, next);
  }
}
</code>```

答:
After investigation i understand that for some reason i need to mark bodyParser as false.</p>
```<code>const app = await NestFactory.create(AppModule, {
    bodyParser: false,
  });

</code>```

Body:
I need to get raw body request for generating signature.
and when i found solution i faced with issue that json function not working
example below :

import { Injectable, NestMiddleware } from '@nestjs/common';
import { json } from 'body-parser';
import { IncomingMessage } from 'http';

@Injectable()
export class RawBodyMiddlewareMiddleware implements NestMiddleware {
  public use(req: IncomingMessage, res, next: () => any): any {
    json({ //json function not fired
      verify: (req, res, buffer) => {
        console.log(buffer);
        if (Buffer.isBuffer(buffer)) {
          const rawBody = Buffer.from(buffer);
          req['parsedRawBody'] = rawBody;
        }
        return true;
      },
    })(req, res as any, next);
  }
}

Body:
After investigation i understand that for some reason i need to mark bodyParser as false.

const app = await NestFactory.create(AppModule, {
    bodyParser: false,
  });


问:
Alternately fill numpy array between non-zero values
I have a binary numpy array, mostly zero-valued, and I want to fill the gaps bewteen non-zero values with a given value, but in an alternate way.
For example:

```<code>[0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0]
</code>```

should result in either

```<code>[0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]
</code>```

or

```<code>[1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1]
</code>```

The idea is: while scanning the array left to right, fill 0 values with 1 up the next 1, if you didn't do it up to the previous 1.
I can do this iteratively and in this way

A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
ones_index = np.where(A == 1)[0]
begins = ones_index[::2] # beginnings of filling section
ends = ones_index[1::2]  # ends of filling sections

from itertools import zip_longest

# fill those sections
for begin, end in zip_longest(begins, ends, fillvalue=len(A)):
    A[begin:end] = 1
```

but I'm looking for a more efficent solution, maybe with numpy broadcasting. Any ideas?

Body:
I have a binary numpy array, mostly zero-valued, and I want to fill the gaps bewteen non-zero values with a given value, but in an alternate way.
For example:

[0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0]

should result in either

[0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]

or

[1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1]

The idea is: while scanning the array left to right, fill 0 values with 1 up the next 1, if you didn't do it up to the previous 1.
I can do this iteratively and in this way

A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
ones_index = np.where(A == 1)[0]
begins = ones_index[::2] # beginnings of filling section
ends = ones_index[1::2]  # ends of filling sections

from itertools import zip_longest

# fill those sections
for begin, end in zip_longest(begins, ends, fillvalue=len(A)):
    A[begin:end] = 1

but I'm looking for a more efficent solution, maybe with numpy broadcasting. Any ideas?

Body:
np.where(arr.cumsum() % 2 == 1, 1, arr)
# array([0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0,
#        0, 0, 1, 1, 1, 1, 0, 0])


问:
How can I delete a data on db automatically after 24 hours in django?
I want to make an instagram clone with django. I'm trying to make stories of instagram on Django Models.As you know, instagrams stories are deleted after 24 hours. How can i delete data from database?</p>

答:
Just filter these out. You can make a model that looks like:

```<code>class MyModel(models.Model):
    # …
    timestamp = models.DateTimeField(<strong>auto_now_add=True</strong>, db_index=True)</code>```

then you can retrieve only MyModel objects that are at most 24 hours old with:

```<code>from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(<strong>timestamp__gte=Now()-timespan(days=1)</strong>)</code>```

you can occasionally run a management command that removes the old MyModels with:

```<code>from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(<strong>timestamp__lt=Now()-timespan(days=1)</strong>)<b>.delete()</b></code>```

Body:
Just filter these out. You can make a model that looks like:

class MyModel(models.Model):
    # …
    timestamp = models.DateTimeField(auto_now_add=True, db_index=True)

then you can retrieve only MyModel objects that are at most 24 hours old with:

from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(timestamp__gte=Now()-timespan(days=1))

you can occasionally run a management command that removes the old MyModels with:

from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(timestamp__lt=Now()-timespan(days=1)).delete()


问:
What is the built-in `#[main]` attribute?
I have been using the #[tokio::main] macro in one of my programs. After importing main and using it unqualified, I encountered an unexpected error.

use tokio::main;

#[main]
async fn main() {}
```
```error[E0659]: `main` is ambiguous
 --> src/main.rs:3:3
  |
3 | #[main]
  |   ^^^^ ambiguous name
  |
  = note: ambiguous because of a name conflict with a builtin attribute
  = note: `main` could refer to a built-in attribute
```
<p>I've been scouring the documentation but I haven't been able to find this built-in <code>#[main]</code> attribute described anywhere. The Rust Reference contains an index of built-in attributes. The index doesn't include <code>#[main]</code>, though it does include an attribute named <code>#[no_main]</code>.</p>
<p>I did a search of the <code>rustlang/rust</code> repository, and found some code that seems related, but it seems to use a pair of macros named <code>#[start]</code> and <code>#[rustc_main]</code>, with no mention of <code>#[main]</code> itself. (Neither of those macros appears to be usable on stable, with <code>#[start]</code> emitting an error that it's unstable, and <code>#[rustc_main]</code> emitting an error that it's only meant for internal use by the compiler.)</p>
<p>My guess from the name would have been that it's meant to mark a different function as an entry-point instead of <code>main</code>, but it also doesn't seem to do that:</p>
<pre class="lang-rust prettyprint-override"><code>#[main]
fn something_else() {
    println!("this does not run");
}

fn main() {
    println!("this runs");
}
</code>```

Rust Analyzer didn't have much to offer:

What does the built-in #[main] attribute do, aside from conflicting with my imports?

答:
#[main] is an old, unstable attribute that was mostly removed from the language in 1.53.0. However, the removal missed one line, with the result you see: the attribute had no effect, but it could be used on stable Rust without an error, and conflicted with imported attributes named main. This was a bug, not intended behaviour. It has been fixed as of nightly-2022-02-10 and 1.59.0-beta.8. Your example with use tokio::main; and #[main] can now run without error.

Before it was removed, the unstable #[main] was used to specify the entry point of a program. Alex Crichton described the behaviour of it and related attributes in a 2016 comment on GitHub:

Ah yes, we've got three entry points. I.. think this is how they work:

First, #[start], the receiver of int argc and char **argv. This is literally the symbol main (or what is called by that symbol generated in the compiler).

Next, there's #[lang = "start"]. If no #[start] exists in the crate graph then the compiler generates a main function that calls this. This functions receives argc/argv along with a third argument that is a function pointer to the #[main] function (defined below). Importantly, #[lang = "start"] can be located in a library. For example it's located in the standard library (libstd).

Finally, #[main], the main function for an executable. This is passed no arguments and is called by #[lang = "start"] (if it decides to). The standard library uses this to initialize itself and then call the Rust program. This, if not specified, defaults to fn main at the top.

So to answer your question, this isn't the same as #[start]. To answer your other (possibly not yet asked) question, yes we have too many entry points.

Body:
I have been using the #[tokio::main] macro in one of my programs. After importing main and using it unqualified, I encountered an unexpected error.

use tokio::main;

#[main]
async fn main() {}

error[E0659]: `main` is ambiguous
 --> src/main.rs:3:3
  |
3 | #[main]
  |   ^^^^ ambiguous name
  |
  = note: ambiguous because of a name conflict with a builtin attribute
  = note: `main` could refer to a built-in attribute

I've been scouring the documentation but I haven't been able to find this built-in #[main] attribute described anywhere. The Rust Reference contains an index of built-in attributes. The index doesn't include #[main], though it does include an attribute named #[no_main].

I did a search of the rustlang/rust repository, and found some code that seems related, but it seems to use a pair of macros named #[start] and #[rustc_main], with no mention of #[main] itself. (Neither of those macros appears to be usable on stable, with #[start] emitting an error that it's unstable, and #[rustc_main] emitting an error that it's only meant for internal use by the compiler.)

My guess from the name would have been that it's meant to mark a different function as an entry-point instead of main, but it also doesn't seem to do that:

#[main]
fn something_else() {
    println!("this does not run");
}

fn main() {
    println!("this runs");
}

Rust Analyzer didn't have much to offer:

What does the built-in #[main] attribute do, aside from conflicting with my imports?


答:
Another way;, split the columns on , to form arrays. Zip the arrays and leverage pysparks' inline function to achieve what you want

```<code>df.withColumn('Subject', split(col("Subject"),",")).withColumn('Marks', split(col("Marks"),",")).selectExpr('ID','inline(arrays_zip(Subject,Marks))')

+---+---------+-----+
| ID|  Subject|Marks|
+---+---------+-----+
|  1|    maths|   80|
|  1|  physics|   90|
|  2| Computer|   73|
|  3|    music|   76|
|  3|   sports|   89|
|  3|chemistry|   85|
+---+---------+-----+
</code>```

Title: Pyspark: Is there a function to split dataframe column values on the basis of comma

Body:
input

+--------------+-----------------------+-----------------------+
|ID            |Subject                |Marks                  |
+--------------+-----------------------+-----------------------+
|1             |maths,physics          |80,90                  |
|2             |Computer               |73                     |
|3             |music,sports,chemistry |76,89,85               |
+--------------+-----------+-----------+-----------------------+

Expected output

+--------------+-----------------------+-----------------------+
|ID            |Subject                |Marks                  |
+--------------+-----------------------+-----------------------+
|1             |maths                  |80                     |
|1             |physics                |90                     |
|2             |Computer               |73                     |
|3             |music                  |76                     |
|3             |sports                 |89                     |
|3             |chemistry              |85                     |
+--------------+-----------+-----------+-----------------------+

need help in getting this expected output
,have already tried explode function but that only works on single column

Body:
Another way;, split the columns on , to form arrays. Zip the arrays and leverage pysparks' inline function to achieve what you want

df.withColumn('Subject', split(col("Subject"),",")).withColumn('Marks', split(col("Marks"),",")).selectExpr('ID','inline(arrays_zip(Subject,Marks))')

+---+---------+-----+
| ID|  Subject|Marks|
+---+---------+-----+
|  1|    maths|   80|
|  1|  physics|   90|
|  2| Computer|   73|
|  3|    music|   76|
|  3|   sports|   89|
|  3|chemistry|   85|
+---+---------+-----+


问:
Timer run every 5th minute
How can I run some function every 5th minute? Example: I want run sendRequest() only at time 14:00, 14:05, 14:10 etc.

I would like to do it programmatically, in C#. The application is a Windows service.

答:
You better give you own Thread that executes the method a condition</p>

```<code>While(programStatus == ProgramStatus.Working)
{
   While (true)
   {
      // Do your stuff
   }
   Thread.Sleep(TheTimeYouWantTheThreadToWaitTillTheNextOperation);
}
</code>```

Title: Timer run every 5th minute

Body:
You better give you own Thread that executes the method a condition

While(programStatus == ProgramStatus.Working)
{
   While (true)
   {
      // Do your stuff
   }
   Thread.Sleep(TheTimeYouWantTheThreadToWaitTillTheNextOperation);
}


问:
Tensorflow JS - converting tensor to JSON and back to tensor
I a training a model in batches and am therefore saving its weights into JSON to store/send.

I need to now load those back into tensors - is there a proper way to do this?

```<code>tensor.data().then(d => JSON.stringify(d));

// returns
{"0":0.000016666666851961054,"1":-0.00019999999494757503,"2":-0.000183333337190561}
</code>```

I can iterate over this an convert back to an array manually - but feel there maybe something in the API which would do this cleaner?

答:
This below can solve the issue, because you can export the Weights 'showWeights' in text format to save it in the database, text file ou browser storage for example and after you can apply in your model again with 'setWeightsFromString'.</p>
```<code>showWeights() {

    tf.tidy(() => {

        const weights = this.model.getWeights();
        let pesos = '';
        let shapes = '';

        for (let i = 0; i < weights.length; i++) {

            let tensor = weights[i];
            let shape = weights[i].shape;
            let values = tensor.dataSync().slice();

            if (pesos) pesos += ';';
            if (shapes) shapes += ';';

            pesos += values;
            shapes += shape;

        }

        console.log(pesos);  // sValues for setWeightsFromString
        console.log(shapes); // sShapes for setWeightsFromString

    });

}

setWeightsFromString(sValues,sShapes) {

   tf.tidy(() => {

        const aValues = sValues.split(';');
        const aShapes = sShapes.split(';');
        const loadedWeights = [];

        for (let i = 0 ; i < aValues.length ; i++) {

            const anValues = aValues[i].split(',').map((e) => {return Number(e)});
            const newValues = new Float32Array(anValues);
            const newShapes = aShapes[i].split(',').map((e) => {return Number(e)});

            loadedWeights[i] = tf.tensor(newValues, newShapes);

        }

        this.model.setWeights(loadedWeights);

    });
}
</code>```

Body:
I a training a model in batches and am therefore saving its weights into JSON to store/send.

I need to now load those back into tensors - is there a proper way to do this?

tensor.data().then(d => JSON.stringify(d));

// returns
{"0":0.000016666666851961054,"1":-0.00019999999494757503,"2":-0.000183333337190561}

I can iterate over this an convert back to an array manually - but feel there maybe something in the API which would do this cleaner?

Body:
This below can solve the issue, because you can export the Weights 'showWeights' in text format to save it in the database, text file ou browser storage for example and after you can apply in your model again with 'setWeightsFromString'.

showWeights() {

    tf.tidy(() => {

        const weights = this.model.getWeights();
        let pesos = '';
        let shapes = '';

        for (let i = 0; i < weights.length; i++) {

            let tensor = weights[i];
            let shape = weights[i].shape;
            let values = tensor.dataSync().slice();

            if (pesos) pesos += ';';
            if (shapes) shapes += ';';

            pesos += values;
            shapes += shape;

        }

        console.log(pesos);  // sValues for setWeightsFromString
        console.log(shapes); // sShapes for setWeightsFromString

    });

}

setWeightsFromString(sValues,sShapes) {

   tf.tidy(() => {

        const aValues = sValues.split(';');
        const aShapes = sShapes.split(';');
        const loadedWeights = [];

        for (let i = 0 ; i < aValues.length ; i++) {

            const anValues = aValues[i].split(',').map((e) => {return Number(e)});
            const newValues = new Float32Array(anValues);
            const newShapes = aShapes[i].split(',').map((e) => {return Number(e)});

            loadedWeights[i] = tf.tensor(newValues, newShapes);

        }

        this.model.setWeights(loadedWeights);

    });
}


问:
Mongoose global plugins not working (ES6)
I'm running into an issue with mongoose.plugin() and none of global plugin changes seem to be affecting the schemas.

Other than importing, I've tried directly writing the plugin in the same index.js file, and removing pointer functions. The global plugins just don't seem to be taking effect. I'm just trying to apply toJSON: { virtuals: true } to all models.

```<code>"mongoose": "^6.0.12"
</code>```
```<code>import test from './plugins/test.js'
...

// Plugins
mongoose.plugin(test)
...

// Models
import './user.js'
...
</code>```

test.js content:

```<code>export default (schema) => {
  schema.set('toJSON', { ...schema.get('toJSON'), virtuals: true })

  return schema
}
</code>```

When I directly apply { toJSON: { virtuals: true } } to the user schema it works as intended, but I want to apply this and potentially other plugins to all the models.

Any help or information is appreciated!

答:
I got it working by up splitting plugins and models into separate files and created an index.js for importing all the plugins.

Within the app.js now I import plugins first followed by the models:

```<code>...
import mongoose from 'mongoose'
import './models/plugins'
import './models
...
</code>```

Body:
I'm running into an issue with mongoose.plugin() and none of global plugin changes seem to be affecting the schemas.

Other than importing, I've tried directly writing the plugin in the same index.js file, and removing pointer functions. The global plugins just don't seem to be taking effect. I'm just trying to apply toJSON: { virtuals: true } to all models.

"mongoose": "^6.0.12"

import test from './plugins/test.js'
...

// Plugins
mongoose.plugin(test)
...

// Models
import './user.js'
...

test.js content:

export default (schema) => {
  schema.set('toJSON', { ...schema.get('toJSON'), virtuals: true })

  return schema
}

When I directly apply { toJSON: { virtuals: true } } to the user schema it works as intended, but I want to apply this and potentially other plugins to all the models.

Any help or information is appreciated!

Body:
I got it working by up splitting plugins and models into separate files and created an index.js for importing all the plugins.

Within the app.js now I import plugins first followed by the models:

...
import mongoose from 'mongoose'
import './models/plugins'
import './models
...


问:
Assignment of Code Inputs and Partial Outputs
I need help with this coding assignment I have.

Assignment:

¨User will input two words

The longer word will output in reverse starting with the last letter until the middle letter

The shorter word will output in order starting at the middle until the end; then output at the beginning until (but not including) the middle

```<code>-in the scenario of same length, the shorter word will be designated with the first input
</code>```

Example

"radio" and "computer" should produce

"radio" would be "diora"

"computer" would be "retu"¨

^thats the assignment.

the thing I'm trying to figure is what exactly to put in the if and else statements.

my code:

```<code>System.out.println("Input word #1:  ");
String w1 = scan.nextLine();

System.out.println("Input word #2:  ");
String w2 = scan.nextLine();

int len1 = w1.length();
int len2 = w2.length();

int location1 =  w1.indexOf( w1 );
int half1 = len1/ 2;

int location2 =  w2.indexOf( w2 );
int half2 = len2/ 2;

if(len1 > len2){
    System.out.println(len1);
}
else{
}
</code>```

Please help me.

答:
First determine what you need: the longer and shorter word.
This already simplifies the problem:

```<code>    System.out.println("Input word #1:");
    String w1 = scan.nextLine();
    System.out.println("Input word #2:");
    String w2 = scan.nextLine();

    String longerWord;
    String shorterWord;
    if (w1.length() <= w2.length()) { // < or <= ?
       shorterWord = w1;
       longerWord = w2;
    } else {
       shorterWord = w2;
       longerWord = w1;
    }
</code>```

For the longer word you must pick the letters in the reverse order:

```<code>    int longerMiddle = longerWord.length() / 2; // Also the middle letter.
    ...
    for (int i = longerWord.length() - 1; i >= longerMiddle; --i) {
        ... letter ...
</code>```

It would spoil the fun helping you more.

Body:
I need help with this coding assignment I have.

Assignment:

¨User will input two words

The longer word will output in reverse starting with the last letter until the middle letter

The shorter word will output in order starting at the middle until the end; then output at the beginning until (but not including) the middle

-in the scenario of same length, the shorter word will be designated with the first input

Example

"radio" and "computer" should produce

"radio" would be "diora"

"computer" would be "retu"¨

^thats the assignment.

the thing I'm trying to figure is what exactly to put in the if and else statements.

my code:

System.out.println("Input word #1:  ");
String w1 = scan.nextLine();

System.out.println("Input word #2:  ");
String w2 = scan.nextLine();

int len1 = w1.length();
int len2 = w2.length();

int location1 =  w1.indexOf( w1 );
int half1 = len1/ 2;

int location2 =  w2.indexOf( w2 );
int half2 = len2/ 2;

if(len1 > len2){
    System.out.println(len1);
}
else{
}

Please help me.

Body:
First determine what you need: the longer and shorter word.
This already simplifies the problem:

    System.out.println("Input word #1:");
    String w1 = scan.nextLine();
    System.out.println("Input word #2:");
    String w2 = scan.nextLine();

    String longerWord;
    String shorterWord;
    if (w1.length() <= w2.length()) { // < or <= ?
       shorterWord = w1;
       longerWord = w2;
    } else {
       shorterWord = w2;
       longerWord = w1;
    }

For the longer word you must pick the letters in the reverse order:

    int longerMiddle = longerWord.length() / 2; // Also the middle letter.
    ...
    for (int i = longerWord.length() - 1; i >= longerMiddle; --i) {
        ... letter ...

It would spoil the fun helping you more.


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
Update. Content can be both higher and wider than container

The "intermediate flexbox" solution provides automatic switching between center and edge alignment of content, but only in one direction - either horizontally or vertically. Therefore, I propose to choose which centering to keep and which to sacrifice.

For example, in this solution, the narrow content is centered and the wide content starts from the left edge of the container. In this case, the content will start from the top edge, regardless of its height. For clarity, I have included four examples with different content sizes in the code.

(The "vertical centered" solution is below in the first version of the answer.)

https://jsfiddle.net/glebkema/8yqxcm9e/

.container {
  border: 2px solid red;
  display: flex;
  height: 250px;
  overflow: auto;
}

.intermediate {
  display: flex;
  flex-grow: 1;
  justify-content: center;
}

.content {
  border: 2px solid blue;
  height: 150px;
  margin: 12px;
  width: 150px;
}

.content.high {
  height: 600px;
}

.content.wide {
  width: 900px;
}

@media (min-width: 500px) {
  .grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
  }
}

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="container">
    <div class="intermediate">
      <div class="content">Narrow content is centered horizontally</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content wide">Narrow content is centered horizontally</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content high">Wide content starts from the left edge</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content wide high">Wide content starts from the left edge</div>
    </div>
  </div>
</div></code>```

1st answer. Content can be higher but not wider than container

I've understood the desired behavior like this:

If the child box is small, it should be centered on the parent.

If the child box is large, then it should not be cut off at the top, but start from the top edge of the parent.

At the same time, the sizes of the blocks are not known in advance and their behavior must be adjusted to the sizes of each other.

Problem:

If we just use the justify-content: center; property, and the height of the child block is greater than the height of the parent, then the top part of the child block is cut off and not available for vertical scrolling.

Solution:

Use a hierarchy of three nested blocks too.
But make the outer container a flex block with a column direction, and give it the overflow-y: scroll; property.
And the intermediate block remains a flex block with the justify-content: center; and flex-grow: 1; properties.

.container.scroll {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}
.intermediate {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  justify-content: center;
}
```
<p>So if the child block is smaller than the parent block, it is centered.
And if its height is greater than the parent's height, it starts from the parent's top edge.</p>
<p><strong>Notice:</strong></p>
<p>In the source code, the <code>.app</code> and <code>.header</code> blocks have a height in pixels, and <code>.container</code> has a height of <code>100%</code>. Thus, it goes beyond the <code>.app</code> block.</p>
<p>To prevent this, I've used flex-boxes for the entire layout too. I also changed the header's <code>height</code> property to <code>min-height</code> to prevent it from shrinking as the container grows.</p>
<p><strong>And here are demos for similar tasks:</strong></p>
<ul>
<li>vertical scroll</li>
<li>horizontal scroll</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.app {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.header {
  min-height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  flex-grow: 1;
}

.container.scroll {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}

.intermediate {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}

.content.small {
  height: 250px;
}

.app + .app {
  margin-top: 50px;
}</code>```

Large content starts from the container's top edge

Small content is centered

```

Body:
Update. Content can be both higher and wider than container

The "intermediate flexbox" solution provides automatic switching between center and edge alignment of content, but only in one direction - either horizontally or vertically. Therefore, I propose to choose which centering to keep and which to sacrifice.

For example, in this solution, the narrow content is centered and the wide content starts from the left edge of the container. In this case, the content will start from the top edge, regardless of its height. For clarity, I have included four examples with different content sizes in the code.

(The "vertical centered" solution is below in the first version of the answer.)

https://jsfiddle.net/glebkema/8yqxcm9e/

.container {
  border: 2px solid red;
  display: flex;
  height: 250px;
  overflow: auto;
}

.intermediate {
  display: flex;
  flex-grow: 1;
  justify-content: center;
}

.content {
  border: 2px solid blue;
  height: 150px;
  margin: 12px;
  width: 150px;
}

.content.high {
  height: 600px;
}

.content.wide {
  width: 900px;
}

@media (min-width: 500px) {
  .grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
  }
}

body {
  margin: 0;
}

<div class="grid">
  <div class="container">
    <div class="intermediate">
      <div class="content">Narrow content is centered horizontally</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content wide">Narrow content is centered horizontally</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content high">Wide content starts from the left edge</div>
    </div>
  </div>

  <div class="container">
    <div class="intermediate">
      <div class="content wide high">Wide content starts from the left edge</div>
    </div>
  </div>
</div>

1st answer. Content can be higher but not wider than container

I've understood the desired behavior like this:

If the child box is small, it should be centered on the parent.

If the child box is large, then it should not be cut off at the top, but start from the top edge of the parent.

At the same time, the sizes of the blocks are not known in advance and their behavior must be adjusted to the sizes of each other.

Problem:

If we just use the justify-content: center; property, and the height of the child block is greater than the height of the parent, then the top part of the child block is cut off and not available for vertical scrolling.

Solution:

Use a hierarchy of three nested blocks too.
But make the outer container a flex block with a column direction, and give it the overflow-y: scroll; property.
And the intermediate block remains a flex block with the justify-content: center; and flex-grow: 1; properties.

.container.scroll {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}
.intermediate {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  justify-content: center;
}

So if the child block is smaller than the parent block, it is centered.
And if its height is greater than the parent's height, it starts from the parent's top edge.

Notice:

In the source code, the .app and .header blocks have a height in pixels, and .container has a height of 100%. Thus, it goes beyond the .app block.

To prevent this, I've used flex-boxes for the entire layout too. I also changed the header's height property to min-height to prevent it from shrinking as the container grows.

And here are demos for similar tasks:

vertical scroll

horizontal scroll

.app {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.header {
  min-height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  flex-grow: 1;
}

.container.scroll {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}

.intermediate {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}

.content.small {
  height: 250px;
}

.app + .app {
  margin-top: 50px;
}

<div class="app">
  <div class="header"></div>
  <div class="container scroll">
    <div class="intermediate">
      <div class="content">Large content starts from the container's top edge</div>
    </div>
  </div>
</div>

<div class="app">
  <div class="header"></div>
  <div class="container scroll">
    <div class="intermediate">
      <div class="content small">Small content is centered</div>
    </div>
  </div>
</div>


答:
You could use a combination of explode, map, and groupby + first for a nice (and probably pretty fast) pandas-esque one-liner:

```<code>df['check'] = df['col2'].explode().map(dict(zip(ref_a, ref_b))).groupby(level=0).first().fillna('')
</code>```

Output:

```<code>>>> df
   col1       col2    check
0     1     [a, b]
1     2     [a, b]
2     3  [a, b, c]  option1
3     4  [a, b, d]  option2
4     5  [a, b, e]  option3
</code>```

Title: Compare list column to a second list and return item in third list

Body:
Have a dataframe with a list column like and two reference lists:

d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)

ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']

    col1    col2
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]
3   4   [a, b, d]
4   5   [a, b, e]

And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b

col1    col2    check
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]   option1
3   4   [a, b, d]   option2
4   5   [a, b, e]   option3

I've tried something like this:

for index, row in df.iterrows():
    for (a, b) in zip(ref_a, ref_b):
        if a in row['col2']:
            df.loc[index, 'check'] = b
            print('true', b)
        else:
            df.loc[index, 'check'] = ''

And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.

Body:
You could use a combination of explode, map, and groupby + first for a nice (and probably pretty fast) pandas-esque one-liner:

df['check'] = df['col2'].explode().map(dict(zip(ref_a, ref_b))).groupby(level=0).first().fillna('')

Output:

>>> df
   col1       col2    check
0     1     [a, b]
1     2     [a, b]
2     3  [a, b, c]  option1
3     4  [a, b, d]  option2
4     5  [a, b, e]  option3


问:
React delete an item from an array of objects
I'm fetching some data from a JSON file. I'm using the map method to display it and it's stored in a state. I need to be able to delete an item when the delete button is clicked. I'm using the filter method to filter out that specific item but I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'filter')

```<code>export default function Customers() {

const { appData, setAppData } = useContext(AppContext);
const { customers, packages } = appData;

function handleDeleteCustomer(id) {

    console.log(id)
    setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)
}

return (
    <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="simple table">
            <TableHead>
                <TableRow>

                    <TableCell >id</TableCell>
                    <TableCell >Name</TableCell>
                    <TableCell />
                    <TableCell />

                </TableRow>
            </TableHead>
            <TableBody>
                {appData.customers.map((row) => {
                    return (
                        <TableRow sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
                            <TableCell component="th" scope="row">{row.id}</TableCell>
                            <TableCell >{row.name}</TableCell>
                            <TableCell ><Button variant="contained">Create Invoice</Button></TableCell>
                            <TableCell ><Button variant="contained" onClick={() => handleDeleteCustomer(row.id)}>Delete</Button></TableCell>
                        </TableRow>
                    )
                })}
            </TableBody>
        </Table>
    </TableContainer>
)
</code>```

}

答:
There is a bug in your code:

```<code>setAppData(appData.customers.filter(customer => customer.id !== id), appData.packages)
</code>```

not

```<code>setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)
</code>```

Body:
I'm fetching some data from a JSON file. I'm using the map method to display it and it's stored in a state. I need to be able to delete an item when the delete button is clicked. I'm using the filter method to filter out that specific item but I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'filter')

export default function Customers() {

const { appData, setAppData } = useContext(AppContext);
const { customers, packages } = appData;

function handleDeleteCustomer(id) {

    console.log(id)
    setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)
}

return (
    <TableContainer component={Paper}>

            <TableHead>
                <TableRow>

                    <TableCell >id</TableCell>
                    <TableCell >Name</TableCell>
                    <TableCell />
                    <TableCell />

                </TableRow>
            </TableHead>
            <TableBody>
                {appData.customers.map((row) => {
                    return (
                        <TableRow sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
                            <TableCell component="th" scope="row">{row.id}</TableCell>
                            <TableCell >{row.name}</TableCell>
                            <TableCell ><Button variant="contained">Create Invoice</Button></TableCell>
                            <TableCell ><Button variant="contained" onClick={() => handleDeleteCustomer(row.id)}>Delete</Button></TableCell>
                        </TableRow>
                    )
                })}
            </TableBody>

    </TableContainer>
)

}

Body:
There is a bug in your code:

setAppData(appData.customers.filter(customer => customer.id !== id), appData.packages)

not

setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)