问:
How can i use loop to show the data distribution in a dataset
I am a beginner

How can i use for loop to print all them

```<code>['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities',
   'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2',
   'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st',
   'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation',
   'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',
   'Heating', 'HeatingQC', 'CentralAir', 'Electrical', 'KitchenQual',
   'Functional', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond',
   'PavedDrive', 'SaleType', 'SaleCondition']
</code>```

Like I did in it

pd.concat([df['MSZoning'].value_counts()/df.shape[0] * 100,
           df3['MSZoning'].value_counts()/df3.shape[0] * 100], axis=1,
          keys=['MSZoning_org','MSZoning_clean'])
```

output:-

![output][https://i.stack.imgur.com/trH9m.jpg]

答:
```<code>xs = ['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities',
   'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2',
   'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st',
   'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation',
   'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',
   'Heating', 'HeatingQC', 'CentralAir', 'Electrical', 'KitchenQual',
   'Functional', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond',
   'PavedDrive', 'SaleType', 'SaleCondition']

def cat_var_dist(var):
    return pd.concat([
        df[var].value_counts()/df.shape[0] * 100,
        df3[var].value_counts()/df3.shape[0] * 100,
        ],
        axis=1,
        keys=[f'{var}_org',f'{var}_clean'],
    )

for x in xs:
    print(cat_var_dist(x))
</code>```

Body:
I am a beginner

How can i use for loop to print all them

['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities',
   'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2',
   'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st',
   'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation',
   'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',
   'Heating', 'HeatingQC', 'CentralAir', 'Electrical', 'KitchenQual',
   'Functional', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond',
   'PavedDrive', 'SaleType', 'SaleCondition']

Like I did in it

pd.concat([df['MSZoning'].value_counts()/df.shape[0] * 100,
           df3['MSZoning'].value_counts()/df3.shape[0] * 100], axis=1,
          keys=['MSZoning_org','MSZoning_clean'])

output:-

![output][https://i.stack.imgur.com/trH9m.jpg]


来源: stackexchange

问:
Android Studio can't install android 12 when run with Installation Options - APK from app bundle
I use installation Options - Deploy - APK from app bundle becasuse of PAD(Play Asset Delivery).

Android 10, 11 build & run works well, but in android 12, install failed.

(But Build SUCCESSFUL)

and  install failed message

```<code>Installation failed due to: 'Failed to commit install session 223924615 with command cmd package install-commit 223924615.
Error: INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION:
Failed parse during installPackageLI: /data/app/vmdl223924615.tmp/split_config.xxhdpi.apk (at Binary XML file line #0):
/data/app/vmdl223924615.tmp/split_config.arm64_v8a.apk (at Binary XML file line #0): Failed to read manifest from /data/app/vmdl223924615.tmp/split_assetPack.apk'
</code>```

(My assets pack name is assetPack)

version info

android studio :

target SDK : 30

min SDK : 26

gradle version : 4.0.2

build tools version : 30.0.2

kotlin version : 1.4.10

答:
```<code> implementation 'androidx.work:work-runtime-ktx:2.7.0-alpha05'
</code>```

Put this line in build.gradle and sync...

work for me....

ContentLicense: CC BY-SA 4.0

Body:
I use installation Options - Deploy - APK from app bundle becasuse of PAD(Play Asset Delivery).

Android 10, 11 build & run works well, but in android 12, install failed.

(But Build SUCCESSFUL)

and  install failed message

Installation failed due to: 'Failed to commit install session 223924615 with command cmd package install-commit 223924615.
Error: INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION:
Failed parse during installPackageLI: /data/app/vmdl223924615.tmp/split_config.xxhdpi.apk (at Binary XML file line #0):
/data/app/vmdl223924615.tmp/split_config.arm64_v8a.apk (at Binary XML file line #0): Failed to read manifest from /data/app/vmdl223924615.tmp/split_assetPack.apk'

(My assets pack name is assetPack)

version info

android studio :

target SDK : 30

min SDK : 26

gradle version : 4.0.2

build tools version : 30.0.2

kotlin version : 1.4.10

Body:
 implementation 'androidx.work:work-runtime-ktx:2.7.0-alpha05'

Put this line in build.gradle and sync...

work for me....


问:
how to know the full path of new created file?
see i have make one program which create one new file just using

```<code>fopen()
</code>```

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?

答:
You already have a file name, so the question is more how to detect whether it's already an absolute path or a relative path and turn the latter into an absolute path.

If it's an absolute path already, then the string will start with a /.  If it's not an absolute path, then you know it's relative to your current working directory.  Given that, you can determine the current working directory of your process and append the file path to that.

If you also want to resolve it to a real path (resolve symlinks, remove . and .. portions) you can use the realpath function.

ContentLicense: CC BY-SA 3.0

Body:
see i have make one program which create one new file just using

fopen()

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?


问:
How to deploy code from Visual Studio Code to Azure Function App in private endpoint and VNet?
I have Azure Function Premium (Python) with private network and Vnet in Azure.

I cannot currently deploy to Azure with Visual Studio Code from workstation.

```<code>11.09.57 func-App-2-171221: Starting deployment...
11.09.57 func-App-2-171221: Creating zip package...
11.09.57 func-App-2-171221: Zip package size: 10 kB
11.09.58: Error:  Error 403 - Forbidden
The web app you have attempted to reach has blocked your access.
</code>```

What is easiest way to build access to network access from my laptop to Function app?

答:
Create a zip of your function app which must contain all the files.
For example in python the zip file should contain

host.json

local.settings.json

requirements.txt

your api folder

.python_packages

Upload this zip file to storage account's container of which your function app is using.

Create a SAS token for this blob. (make sure the blob is private)

Copy the blob URL.

Go to Function app -> configuration and add new application settings.

key is WEBSITE_RUN_FROM_PACKAGE and value is <blob SAS URL you copied>.

Save and restart your function app.

Body:
I have Azure Function Premium (Python) with private network and Vnet in Azure.

I cannot currently deploy to Azure with Visual Studio Code from workstation.

11.09.57 func-App-2-171221: Starting deployment...
11.09.57 func-App-2-171221: Creating zip package...
11.09.57 func-App-2-171221: Zip package size: 10 kB
11.09.58: Error:  Error 403 - Forbidden
The web app you have attempted to reach has blocked your access.

What is easiest way to build access to network access from my laptop to Function app?


问:
Unable to create parquet column scanner
I am trying to load the parquet data from S3 into redshift and I am running following command:

```<code>COPY sample_table
FROM 's3://sample_s3/parquet_data/'
IAM_ROLE '<arn>'
FORMAT AS PARQUET;
</code>```

but as soon as I run this command, I am getting this error:

```<code>DETAIL:
  -----------------------------------------------
  error:  Spectrum Scan Error
  code:      15001
  context:   Unable to create parquet column scanner
  query:     21099
  location:  dory_util.cpp:1141
  process:   worker_thread [pid=6570]
  -----------------------------------------------
</code>```

and FYI, this is happening only for few tables and not for all the tables. I have 7 tables out of which I am getting this for only 2 tables and not able to figure out the issue.
Any help or anyone have ever received this issue?

答:
I was having this issue and it turned out to be how decimal values were encoded. According to the parquet-cli, a decimal value was being encoded as binary (STRING). What Redshift wanted was fixed_len_byte_array(5) (DECIMAL(10,4)).

To fix the issue, I converted the string values to decimal with the following Python code (which uses Pandas and PyArrow):

```<code>import pyarrow as pa
new_values = pa.chunked_array(pa.Array.from_pandas(table.column('score').to_pandas().astype(float)).cast(pa.decimal128(10, 4)))
table = table.set_column(position, 'score', new_values)
</code>```

I would also like to point out that the pa.chunked_array is necessary. Using only a PyArrow Array is not enough to get the proper type.

Just in case it may help with similar problems: I found this by first exporting some data from Redshift with the UNLOAD command and working backwards from there.

Title: Unable to create parquet column scanner

Body:
I am trying to load the parquet data from S3 into redshift and I am running following command:

COPY sample_table
FROM 's3://sample_s3/parquet_data/'
IAM_ROLE '<arn>'
FORMAT AS PARQUET;

but as soon as I run this command, I am getting this error:

DETAIL:
  -----------------------------------------------
  error:  Spectrum Scan Error
  code:      15001
  context:   Unable to create parquet column scanner
  query:     21099
  location:  dory_util.cpp:1141
  process:   worker_thread [pid=6570]
  -----------------------------------------------

and FYI, this is happening only for few tables and not for all the tables. I have 7 tables out of which I am getting this for only 2 tables and not able to figure out the issue.
Any help or anyone have ever received this issue?

Body:
I was having this issue and it turned out to be how decimal values were encoded. According to the parquet-cli, a decimal value was being encoded as binary (STRING). What Redshift wanted was fixed_len_byte_array(5) (DECIMAL(10,4)).

To fix the issue, I converted the string values to decimal with the following Python code (which uses Pandas and PyArrow):

import pyarrow as pa
new_values = pa.chunked_array(pa.Array.from_pandas(table.column('score').to_pandas().astype(float)).cast(pa.decimal128(10, 4)))
table = table.set_column(position, 'score', new_values)

I would also like to point out that the pa.chunked_array is necessary. Using only a PyArrow Array is not enough to get the proper type.

Just in case it may help with similar problems: I found this by first exporting some data from Redshift with the UNLOAD command and working backwards from there.


问:
How to render HTML stored inside an object?
I am using nextjs. I need to render custom landing pages according to their specific url. I am able to render all the details from the database of that particular URL except for the object which contains the details for the page. The pages has been built with the help of grapesjs.
Following is the data in db:

Following is code for rendering the list of the pages:
index.js

```<code>import Link from "next/link"
export const getStaticProps = async () => {
  const res = await fetch("http://localhost:5000/api/webpage/");
  const data = await res.json();
  return {
    props: {
      data,
    }
  };
};

const blog = ({ data }) => {
  return (
    <div>
      {data?.map((currentElement) => {
        return (
          <div key={currentElement.id} className="ssr-styles">
            <h3>
              {/* {currentElement._id} */}
              <Link href={`/blog/${currentElement.url}`}>
                {currentElement.name}
              </Link>
            </h3>
          </div>
        );
      })}
    </div>
  );
};
export default blog;
</code>```

Following is the code where the page is actually rendering:
[pageno].js=>

```<code>export const getStaticPaths = async () => {
  const res = await fetch("http://localhost:5000/api/webpage/");
  const data = await res.json();
  const paths = data.map((currentElement) => {
    return {
      params: { pageno: currentElement.url.toString() }
    };
  });
  return {
    paths,
    fallback: false
  };
};
export const getStaticProps = async (context) => {
  const url = context.params.pageno;
  const res = await fetch(`http://localhost:5000/api/webpage/url/${url}`);
  const data = await res.json();
  return {
    props: {
      data
    }
  };
};

export const Details = ({ data }) => {
  return (
    <>
      <div key={data.url} className="ssr-styles">
        {data._id}
        <h3>{data.name}</h3>
      </div>
    </>
  );
};

export default Details;
</code>```

how do I render the html inside the object content so as to get a proper webpage?

答: you can try using html-react-parser library. it converts an HTML string to React elements.</p>

Body:
I am using nextjs. I need to render custom landing pages according to their specific url. I am able to render all the details from the database of that particular URL except for the object which contains the details for the page. The pages has been built with the help of grapesjs.
Following is the data in db:

Following is code for rendering the list of the pages:
index.js

import Link from "next/link"
export const getStaticProps = async () => {
  const res = await fetch("http://localhost:5000/api/webpage/");
  const data = await res.json();
  return {
    props: {
      data,
    }
  };
};

const blog = ({ data }) => {
  return (

      {data?.map((currentElement) => {
        return (

              {/* {currentElement._id} */}
              <Link href={`/blog/${currentElement.url}`}>
                {currentElement.name}
              </Link>

        );
      })}

  );
};
export default blog;

Following is the code where the page is actually rendering:
[pageno].js=>

export const getStaticPaths = async () => {
  const res = await fetch("http://localhost:5000/api/webpage/");
  const data = await res.json();
  const paths = data.map((currentElement) => {
    return {
      params: { pageno: currentElement.url.toString() }
    };
  });
  return {
    paths,
    fallback: false
  };
};
export const getStaticProps = async (context) => {
  const url = context.params.pageno;
  const res = await fetch(`http://localhost:5000/api/webpage/url/${url}`);
  const data = await res.json();
  return {
    props: {
      data
    }
  };
};

export const Details = ({ data }) => {
  return (
    <>

        {data._id}

{data.name}

    </>
  );
};

export default Details;

how do I render the html inside the object content so as to get a proper webpage?


问:
Passing a C# Dictionary as a function parameter to allocate its memory does not work
I have  below code

```<code>using System;
using System.Collections.Generic;
class Program {
    static void add(Dictionary<string,string> hello){
      hello = new Dictionary<string,string>();
      hello["hello"] = "hello";
    }
    static void Main(string[] args) {
      Employee employee = new Employee(); // Employee class

      add(employee.hello);     //  employee.hello is property like public Dictionary<string,string> hello {get;set;}
        Console.WriteLine(hello["hello"]);
    }
}
</code>```

I have also tried using ref but i'm getting A property or indexer may not be passed as ref

When I intialize hello this program  works fine but when i try to intialize it in function it is giving me null reference error. So is there any way to initialize dictionary by passing through a function like that ?

答:
You need to chose if you are passing in a created dictionary or creating one in the add method.

Here's option 1:

```<code>class Program
{
    static void add(Dictionary<string, string> hello)
    {
        hello["hello"] = "hello";
    }

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        add(employee.hello);
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = new Dictionary<string, string>();
}
</code>```

Here's option 2:

```<code>class Program
{
    static Dictionary<string, string> add() =>
        new Dictionary<string, string>()
        {
            { "hello", "hello" },
        };

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        employee.hello = add();
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = null;
}
</code>```

And, option 3, also works.

```<code>class Program
{
    static void add(ref Dictionary<string, string> hello)
    {
        if (hello == null)
        {
            hello = new Dictionary<string, string>();
        }
        hello["hello"] = "hello";
    }

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        add(ref employee.hello);
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = null;
}
</code>```

All three of those print hello to the console.

It's a little unclear what you're trying to do. But if it is the last one then you're mixing up the responsibilities of your classes and methods.

The class Employee should be responsible for setting up its own fields.

Finally, it would be useful for you to use the C# variable and method naming standards.

Body:
I have  below code

using System;
using System.Collections.Generic;
class Program {
    static void add(Dictionary<string,string> hello){
      hello = new Dictionary<string,string>();
      hello["hello"] = "hello";
    }
    static void Main(string[] args) {
      Employee employee = new Employee(); // Employee class

      add(employee.hello);     //  employee.hello is property like public Dictionary<string,string> hello {get;set;}
        Console.WriteLine(hello["hello"]);
    }
}

I have also tried using ref but i'm getting A property or indexer may not be passed as ref

When I intialize hello this program  works fine but when i try to intialize it in function it is giving me null reference error. So is there any way to initialize dictionary by passing through a function like that ?

Body:
You need to chose if you are passing in a created dictionary or creating one in the add method.

Here's option 1:

class Program
{
    static void add(Dictionary<string, string> hello)
    {
        hello["hello"] = "hello";
    }

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        add(employee.hello);
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = new Dictionary<string, string>();
}

Here's option 2:

class Program
{
    static Dictionary<string, string> add() =>
        new Dictionary<string, string>()
        {
            { "hello", "hello" },
        };

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        employee.hello = add();
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = null;
}

And, option 3, also works.

class Program
{
    static void add(ref Dictionary<string, string> hello)
    {
        if (hello == null)
        {
            hello = new Dictionary<string, string>();
        }
        hello["hello"] = "hello";
    }

    static void Main(string[] args)
    {
        Employee employee = new Employee();
        add(ref employee.hello);
        Console.WriteLine(employee.hello["hello"]);
    }
}

public class Employee
{
    public Dictionary<string, string> hello = null;
}

All three of those print hello to the console.

It's a little unclear what you're trying to do. But if it is the last one then you're mixing up the responsibilities of your classes and methods.

The class Employee should be responsible for setting up its own fields.

Finally, it would be useful for you to use the C# variable and method naming standards.


问:
Can't seem to figure out how to keep score in Rock, Paper, Scissors
I am trying to make Rock, Paper, Scissors via The Odin Project, and I'm stuck in the last step. I don't seem to have trouble getting the prompt to work, just can't seem to either tally up points, or I'm having trouble ending the game when either the player or computer gets to 5 points. I did include some console.logs at the bottom, but I'm unable to actually see the score due to the endless prompts. What am I doing wrong? I just need the game to end when either the player or computer gets to 5 points.</p>
```<code>let playerScore = 0;
let computerScore = 0;

function computerPlay() {
    let allChoices = ["Rock", "Paper", "Scissors"];
    let randomChoice = allChoices[Math.floor(Math.random() * allChoices.length)];
    return randomChoice
}

function game() {
    while (playerScore <= 5 || computerScore <= 5) {
        const playerSelection = prompt("Would you like to choose R, P or S?")
        const computerSelection = computerPlay();
        alert(playRound(playerSelection, computerSelection));
    }
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection == computerSelection) {
        return "Tie game!"
    } else if (playerSelection == "Rock" && computerSelection == "Scissors") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else if (playerSelection == "Paper" && computerSelection == "Rock") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else if (playerSelection == "Scissors" && computerSelection == "Paper") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else {
        return `You lose! ${computerSelection} beats ${playerSelection}`
        computerScore += 1;
    }
}

function winGame() {
    if (playerScore == 5) {
        return "You win!"
    } else if (computerScore == 5) {
        return "You lose!"
    }
}

game();

console.log(playerScore);
console.log(computerScore);
</code>```

答:
```<code>function game() {
    while (playerScore < 5 && computerScore < 5) {
        const playerSelection = prompt("Would you like to choose Rock, Paper or Scissors?")
        const computerSelection = computerPlay();
        alert(playRound(playerSelection, computerSelection));
    }
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === computerSelection) {
        return "Tie game!"
    } else if (playerSelection === "Rock" && computerSelection === "Scissors") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else if (playerSelection === "Paper" && computerSelection === "Rock") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else if (playerSelection === "Scissors" && computerSelection === "Paper") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else {
        computerScore += 1;
        return `You lose! ${computerSelection} beats ${playerSelection}`
    }
}
</code>```

You returned from the function before incrementing the points. So they will never be incremented. Also (playerScore <= 5 || computerScore <= 5) means, that the game will go on until both - playerScore and computerScore are below 6. It has to stop when one of them reaches 5

Body:
I am trying to make Rock, Paper, Scissors via The Odin Project, and I'm stuck in the last step. I don't seem to have trouble getting the prompt to work, just can't seem to either tally up points, or I'm having trouble ending the game when either the player or computer gets to 5 points. I did include some console.logs at the bottom, but I'm unable to actually see the score due to the endless prompts. What am I doing wrong? I just need the game to end when either the player or computer gets to 5 points.

let playerScore = 0;
let computerScore = 0;

function computerPlay() {
    let allChoices = ["Rock", "Paper", "Scissors"];
    let randomChoice = allChoices[Math.floor(Math.random() * allChoices.length)];
    return randomChoice
}

function game() {
    while (playerScore <= 5 || computerScore <= 5) {
        const playerSelection = prompt("Would you like to choose R, P or S?")
        const computerSelection = computerPlay();
        alert(playRound(playerSelection, computerSelection));
    }
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection == computerSelection) {
        return "Tie game!"
    } else if (playerSelection == "Rock" && computerSelection == "Scissors") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else if (playerSelection == "Paper" && computerSelection == "Rock") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else if (playerSelection == "Scissors" && computerSelection == "Paper") {
        return `You win! ${playerSelection} beats ${computerSelection}!`
        playerScore += 1;
    } else {
        return `You lose! ${computerSelection} beats ${playerSelection}`
        computerScore += 1;
    }
}

function winGame() {
    if (playerScore == 5) {
        return "You win!"
    } else if (computerScore == 5) {
        return "You lose!"
    }
}

game();

console.log(playerScore);
console.log(computerScore);

Body:
function game() {
    while (playerScore < 5 && computerScore < 5) {
        const playerSelection = prompt("Would you like to choose Rock, Paper or Scissors?")
        const computerSelection = computerPlay();
        alert(playRound(playerSelection, computerSelection));
    }
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === computerSelection) {
        return "Tie game!"
    } else if (playerSelection === "Rock" && computerSelection === "Scissors") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else if (playerSelection === "Paper" && computerSelection === "Rock") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else if (playerSelection === "Scissors" && computerSelection === "Paper") {
        playerScore += 1;
        return `You win! ${playerSelection} beats ${computerSelection}!`

    } else {
        computerScore += 1;
        return `You lose! ${computerSelection} beats ${playerSelection}`
    }
}

You returned from the function before incrementing the points. So they will never be incremented. Also (playerScore <= 5 || computerScore <= 5) means, that the game will go on until both - playerScore and computerScore are below 6. It has to stop when one of them reaches 5


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答: Look into SQL Server Express, or SQL Server Compact Edition.</p>

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: John Saunders


问:
Sort numpy matrix based on a comparator function
I have a vector v and a matrix M. I want to sort M row-wise by comparing each row to v with Euclidean distance (np.linalg.norm) and sort from least distance to greatest distance. I've looked into np.argsort but am not sure how to apply it to this instance or if it even works here. Any help would be greatly appreciated!

Example input:

```<code>k = 5
n = 3
M = np.random.randn(k, n)
v = [1, 2, 3, 4, 5]
</code>```

答:
You first have to compute the distances of all rows to that given row. That you can do for example by subtracting the and computing the norm of the resulting rows. After that, you can sort the resulting distance vector using argsort which returns the indices that sort the vector in descending order. Finally, you use those indices to index into your original array and get back a sorted ones.

distances = np.linalg.norm(M-np.array(v)[:,None],axis=1)
M_sorted = M[np.argsort(distances),:]
```

Body:
I have a vector v and a matrix M. I want to sort M row-wise by comparing each row to v with Euclidean distance (np.linalg.norm) and sort from least distance to greatest distance. I've looked into np.argsort but am not sure how to apply it to this instance or if it even works here. Any help would be greatly appreciated!

Example input:

k = 5
n = 3
M = np.random.randn(k, n)
v = [1, 2, 3, 4, 5]


问:
How do we make text bold from .ts file to show in [innterText] html section
Just like we use \n instead of
 to see the line break changes in the interface, how do we bold the specific text? What can be the alternative solution apart from using [innerHTML]?

for example:
.ts file

string = This is a STRING bold testing.\n Thankyou!; // here I want to word STRING to be bold

.html file

```<code><h2 [innerText]="string"></h2>
</code>```

答:
You have to use a custom Pipe for making bold for a particular string. Please find the below URL for your reference.

apply bold text on part of string Angular


问:
How do you create a user and role at the same time?
I am trying to create a user and assign it a role at the same time. How do you do this since ApplicationUser doesnt have the tables needed and running it separate in an ApplicationRole or by itself pops it for a null NormalizedRoleName, even when you actually set the normalizeRoleName</p>
```<code>public async Task<IActionResult> CreateUser(UserInfo user)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser appUser = new ApplicationUser
                {
                    UserName = user.Email,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Email = user.Email,

                };
                IdentityResult result = await _userManager.CreateAsync(appUser, user.Password);

                if (result.Succeeded)

                {
                    ApplicationRole role = new ApplicationRole
                    {
                        RoleName = user.RoleName,
                        NormalizedRoleName = user.RoleName.ToUpper()
                    };

                 IdentityResult roleresult = await _userManager.AddToRoleAsync(appUser, role.RoleName);

                if (roleresult.Succeeded)
                    return RedirectToAction("Index");
                else
                {
                    foreach (IdentityError error in result.Errors)
                        ModelState.AddModelError("", error.Description);
                }
                }
            }

            return View(user);
    }
</code>```

答:
If you want to register user and role at the same time, you can create a ViewModel whitch contains user's attributes and role's attributes, Then use this ViewModel to pass the date from view to controller.

Here is a simple Demo

ViewModel

```<code>public class Register
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public string Rolename  { get; set; }
    }
</code>```

View

```<code>@model CustomIdentity.Models.Register

<form asp-controller="Test" asp-action="Register" method="post">
    <div class="form-group">
        <label asp-for="@Model.UserName"></label>
        <input asp-for="@Model.UserName" />
    </div>

    <div class="form-group">
        <label asp-for="@Model.Password"></label>
        <input asp-for="@Model.Password" />
    </div>

    <div class="form-group">
        <label asp-for="@Model.Rolename"></label>
        <input asp-for="@Model.Rolename" />
    </div>
    <button type="submit">Submit</button>
</form>
</code>```

controller

```<code>     //Inject UserManager and RoleManager into the controller
        [HttpPost]
        public async Task<IActionResult> Register(Register model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser { ClassName = model.ClassName};
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var role = new IdentityRole { Name = model.Rolename };
                    var result1 = await _roleManager.CreateAsync(role);
                    if (result1.Succeeded)
                    {
//make sure the user and role register successfully, then we can use `AddToRoleAsync` to add the relationship between them
                        await _userManager.AddToRoleAsync(user, role.Name);
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            return View(model);
        }
</code>```

Then you can create a user and assign it a role at the same time

Body:
I am trying to create a user and assign it a role at the same time. How do you do this since ApplicationUser doesnt have the tables needed and running it separate in an ApplicationRole or by itself pops it for a null NormalizedRoleName, even when you actually set the normalizeRoleName

public async Task<IActionResult> CreateUser(UserInfo user)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser appUser = new ApplicationUser
                {
                    UserName = user.Email,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Email = user.Email,

                };
                IdentityResult result = await _userManager.CreateAsync(appUser, user.Password);

                if (result.Succeeded)

                {
                    ApplicationRole role = new ApplicationRole
                    {
                        RoleName = user.RoleName,
                        NormalizedRoleName = user.RoleName.ToUpper()
                    };

                 IdentityResult roleresult = await _userManager.AddToRoleAsync(appUser, role.RoleName);

                if (roleresult.Succeeded)
                    return RedirectToAction("Index");
                else
                {
                    foreach (IdentityError error in result.Errors)
                        ModelState.AddModelError("", error.Description);
                }
                }
            }

            return View(user);
    }

Body:
If you want to register user and role at the same time, you can create a ViewModel whitch contains user's attributes and role's attributes, Then use this ViewModel to pass the date from view to controller.

Here is a simple Demo

ViewModel

public class Register
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public string Rolename  { get; set; }
    }

View

@model CustomIdentity.Models.Register

<form asp-controller="Test" asp-action="Register" method="post">
    <div class="form-group">
        <label asp-for="@Model.UserName"></label>
        <input asp-for="@Model.UserName" />
    </div>

    <div class="form-group">
        <label asp-for="@Model.Password"></label>
        <input asp-for="@Model.Password" />
    </div>

    <div class="form-group">
        <label asp-for="@Model.Rolename"></label>
        <input asp-for="@Model.Rolename" />
    </div>
    <button type="submit">Submit</button>
</form>

controller

     //Inject UserManager and RoleManager into the controller
        [HttpPost]
        public async Task<IActionResult> Register(Register model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser { ClassName = model.ClassName};
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var role = new IdentityRole { Name = model.Rolename };
                    var result1 = await _roleManager.CreateAsync(role);
                    if (result1.Succeeded)
                    {
//make sure the user and role register successfully, then we can use `AddToRoleAsync` to add the relationship between them
                        await _userManager.AddToRoleAsync(user, role.Name);
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            return View(model);
        }

Then you can create a user and assign it a role at the same time


问:
paste()ing columns whose names are stored in a variable
How do I create a new column from columns whose names are contained in a character vector?

Given these two variables:

```<code>data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")
</code>```

What command would produce this output?

```<code># A tibble: 10 x 3
   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j
</code>```

My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.

```<code>Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.
</code>```

答:
```<code> cbind( data , combined = paste( data[[ columns[1] ]], data[[ columns[2] ]], sep=“-“)
</code>```

Body:
How do I create a new column from columns whose names are contained in a character vector?

Given these two variables:

data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")

What command would produce this output?

# A tibble: 10 x 3
   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j

My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.

Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.


问:
What does the keyword ref mean in C#?
Below is my code please explain what is ref cboListType.</p>

```<code>Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}
</code>```

答: I assume this is a System.Web.UI.WebControls.DropDownList, and it almost certainly should not be declared ref.</p>

Title: What does the keyword ref mean in C#?

Body:
Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}


问:
Why is my modal not animating from the center of the screen?
The Goal: I would like my .modal class div to scale from 0 to 1 from the dead center of the screen. Currently, it originates on the bottom right of the screen and slowly progresses to the center before popping into the final location. I've tried reviewing the documentation on MDN for keyframes, transform-origin, position fixed, and other things I thought could cause the behavior and I'm lost. Any help would be appreciated especially if you can explain why this happens because I want to understand what I'm doing wrong.

CodePen Link: https://codepen.io/AlfredGarcia/pen/zYPNWgM?editors=1100

HTML:

```<code><div class="modal">
  <header class="modal__header">
    <h3 class="modal__title">Attention</d>
  </header>
  <div class="modal__content">
    <p class="modal__message">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Odit quibusdam debitis est voluptatem recusandae aliquid neque rerum, eum cum distinctio illum excepturi veniam illo suscipit, assumenda hic placeat minima? Ipsum.</p>
  </div>
  <div class="modal__actions">
    <button class="btn btn--positive" type="button">Confirm</button>
    <button class="btn btn--negative" type="button">Decline</button>
  </div>
</div>
</code>```

CSS

```<code>.modal {
  border-radius: 0.625em;
  box-shadow: 0 2px 10px -4px black;
  position: fixed;
  inset: 50% auto auto 50%;
  transform: translate(-50%, -50%);
  animation: 5s ease-in fadein;
}

.modal__header {
  background-color: lightgray;
  border-top-left-radius: 0.625em;
  border-top-right-radius: 0.625em;
  padding: 0.75em 0 0.75em 1em;
}

.modal__title {
  font: 1.25rem/1.1 poppins, sans-serif;
  margin: 0;
}

.modal__content {
  padding: 1em;
}

.modal__message {
  font: 1rem/1.4 calibri, sans-serif;
  margin: 0;
}

.modal__actions {
  display: flex;
  justify-content: flex-end;
  padding: 0 1em 1em 1em;
}

.btn {
  padding: 0.625em 1.25em;
  display: block;
  border: none;
  border-radius: 0.625em;
  box-shadow: 0 2px 10px -4px black;
  text-transform: uppercase;
}

.btn:active {
  transform: translateY(3px);
}

.btn + .btn {
  margin-left: 1em;
}

.btn--positive {
  background-color: lightgreen;
}

.btn--positive:hover {
  filter: brightness(110%);
}

.btn--negative {
  background-color: #ff3131;
  filter: brightness(90%);
  color: white;
}

.btn--negative:hover {
  filter: brightness(100%);
}

@keyframes fadein {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}
</code>```

答:
Your modal is not animating as you want because the transform in your class .modal is being overridden by the transform in your fadein keyframes, subsequently removing your transform: translate(-50%, -50%); -- this is what's causing the "jump".

Update your keyframes to include your desired position and add a transform-origin, for example:

```<code>@keyframes fadein {
  from {
    transform: scale(0) translate(-50%, -50%);
    transform-origin: 0 0;
  }
  to {
    transform: scale(1) translate(-50%, -50%);
    transform-origin: 0 0;
  }
}
</code>```

Working Codepen: https://codepen.io/scarabaeus/pen/QWOgLrZ/d8a3c1fa93d5dd198e1d681f0b29de32?editors=1100

Body:
The Goal: I would like my .modal class div to scale from 0 to 1 from the dead center of the screen. Currently, it originates on the bottom right of the screen and slowly progresses to the center before popping into the final location. I've tried reviewing the documentation on MDN for keyframes, transform-origin, position fixed, and other things I thought could cause the behavior and I'm lost. Any help would be appreciated especially if you can explain why this happens because I want to understand what I'm doing wrong.

CodePen Link: https://codepen.io/AlfredGarcia/pen/zYPNWgM?editors=1100

HTML:

Attention</d>

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Odit quibusdam debitis est voluptatem recusandae aliquid neque rerum, eum cum distinctio illum excepturi veniam illo suscipit, assumenda hic placeat minima? Ipsum.

    <button class="btn btn--positive" type="button">Confirm</button>
    <button class="btn btn--negative" type="button">Decline</button>

CSS

.modal {
  border-radius: 0.625em;
  box-shadow: 0 2px 10px -4px black;
  position: fixed;
  inset: 50% auto auto 50%;
  transform: translate(-50%, -50%);
  animation: 5s ease-in fadein;
}

.modal__header {
  background-color: lightgray;
  border-top-left-radius: 0.625em;
  border-top-right-radius: 0.625em;
  padding: 0.75em 0 0.75em 1em;
}

.modal__title {
  font: 1.25rem/1.1 poppins, sans-serif;
  margin: 0;
}

.modal__content {
  padding: 1em;
}

.modal__message {
  font: 1rem/1.4 calibri, sans-serif;
  margin: 0;
}

.modal__actions {
  display: flex;
  justify-content: flex-end;
  padding: 0 1em 1em 1em;
}

.btn {
  padding: 0.625em 1.25em;
  display: block;
  border: none;
  border-radius: 0.625em;
  box-shadow: 0 2px 10px -4px black;
  text-transform: uppercase;
}

.btn:active {
  transform: translateY(3px);
}

.btn + .btn {
  margin-left: 1em;
}

.btn--positive {
  background-color: lightgreen;
}

.btn--positive:hover {
  filter: brightness(110%);
}

.btn--negative {
  background-color: #ff3131;
  filter: brightness(90%);
  color: white;
}

.btn--negative:hover {
  filter: brightness(100%);
}

@keyframes fadein {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}

Body:
Your modal is not animating as you want because the transform in your class .modal is being overridden by the transform in your fadein keyframes, subsequently removing your transform: translate(-50%, -50%); -- this is what's causing the "jump".

Update your keyframes to include your desired position and add a transform-origin, for example:

@keyframes fadein {
  from {
    transform: scale(0) translate(-50%, -50%);
    transform-origin: 0 0;
  }
  to {
    transform: scale(1) translate(-50%, -50%);
    transform-origin: 0 0;
  }
}

Working Codepen: https://codepen.io/scarabaeus/pen/QWOgLrZ/d8a3c1fa93d5dd198e1d681f0b29de32?editors=1100


问:
How can I reshape the tensor
```<code>tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])
</code>```

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

```<code>tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])
</code>```

答:
Assuming that the tensor is a numpy array.

Firsly, flatten the matrix using x= x.flatten()

Then remove all occurences of zeros using x = x[x!=0]

Then reshape the array back in 2D using x = np.reshape(x, ( -1, x.shape[0] ))

This (x) would return you:

```<code>array([[17, 93,  4, 72, 83, 67, 34, 21, 19]])
</code>```

Title: How can I reshape the tensor

Body:
tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])

Body:
Assuming that the tensor is a numpy array.

Firsly, flatten the matrix using x= x.flatten()

Then remove all occurences of zeros using x = x[x!=0]

Then reshape the array back in 2D using x = np.reshape(x, ( -1, x.shape[0] ))

This (x) would return you:

array([[17, 93,  4, 72, 83, 67, 34, 21, 19]])


问:
refresh header component after login using angular 11
actually i am using angular 11 and i want to show username in header component but my header is load first then my login component is load so after loading login component data store in local storage that why when i refresh page then user name is show but i dont want refresh page so what can i do for that please help me

below code is my authservice

```<code>
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment'
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  baseUrl = environment.apiUrl;

  constructor(private http: HttpClient, private router: Router) { }
  loginUser(data: {}) {
    return this.http.post(this.baseUrl + 'signin', data)
  }

  isLoggedIn() {
    //console.log(localStorage.getItem('user_details'))
    if (localStorage.getItem('user_details') !== undefined && localStorage.getItem('user_details') !== null) {
      //console.log("if")
      return true;
    } else {
      return false;
    }
    //return !!localStorage.getItem('user_details')
  }
  getUserName(): any {
    const userName = localStorage.getItem('user_details');
    if (userName) {
      return JSON.parse(userName);
    }
    return false;
  }
  isLoggedOut() {
    localStorage.removeItem('user_details');
    this.router.navigate(['/login']);
  }
}

</code>```

this is my header component

```<code>import { Component, OnInit, HostListener } from '@angular/core';
import { AuthService } from '../../login/services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  scrolled: boolean = false;
  userName: string = '';
  fname: string = '';
  lname: string = "";

  @HostListener("window:scroll", [])
  onWindowScroll() {
    this.scrolled = window.scrollY > 1;
  }
  constructor(public auth: AuthService, private router: Router) { }

  ngOnInit(): void {
    if (this.auth.isLoggedIn()) {
      this.router.navigate(['dashboard']);
    }
    const user = this.auth.getUserName();
    this.userName = user.role_name;
    this.fname = user.first_name.charAt(0);
    this.lname = user.last_name.charAt(0);
  }

  logOut() {
    localStorage.removeItem('user_details');
    this.router.navigate(['/login']);
  }
}
</code>```

below is login component

```<code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AuthService } from './services/auth.service';
import { Router } from '@angular/router';
import { Md5 } from 'md5-typescript';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: any;
  data: any;
  success: any;
  message: any;

  constructor( private auth: AuthService, private router: Router ) {

    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.pattern('^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$')]),
      password: new FormControl('', Validators.required)
    });

  }

  ngOnInit(): void { }

  onSubmit() {
    console.log(this.loginForm.value);
    let data = {
      "email_id": this.loginForm.value.email,
      "password": Md5.init(this.loginForm.controls['password'].value)
    }
    this.auth.loginUser(data).subscribe(
      (response: any) => {
        this.data == response;
        this.success == response.success;
        if (response.success == 1) {
          localStorage.setItem("user_details", JSON.stringify(JSON.parse(response.data).user_details))
          console.log(localStorage.getItem('user_details'));
          this.router.navigate(['dashboard']);
        } else {
          this.message = response.message;
        }
      }
    );
    this.loginForm.reset();
  }
}

</code>```

答: You can't use local storage to get logged in user details, because you component is already loaded. You need to create shared service using Subject or Behaviorsubject (RXJS operatoer) You can find example https://medium.com/@hitensharma1515/sharing-data-between-components-using-service-2d662a653a89</p>

Body:
actually i am using angular 11 and i want to show username in header component but my header is load first then my login component is load so after loading login component data store in local storage that why when i refresh page then user name is show but i dont want refresh page so what can i do for that please help me

below code is my authservice

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment'
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  baseUrl = environment.apiUrl;

  constructor(private http: HttpClient, private router: Router) { }
  loginUser(data: {}) {
    return this.http.post(this.baseUrl + 'signin', data)
  }

  isLoggedIn() {
    //console.log(localStorage.getItem('user_details'))
    if (localStorage.getItem('user_details') !== undefined && localStorage.getItem('user_details') !== null) {
      //console.log("if")
      return true;
    } else {
      return false;
    }
    //return !!localStorage.getItem('user_details')
  }
  getUserName(): any {
    const userName = localStorage.getItem('user_details');
    if (userName) {
      return JSON.parse(userName);
    }
    return false;
  }
  isLoggedOut() {
    localStorage.removeItem('user_details');
    this.router.navigate(['/login']);
  }
}

this is my header component

import { Component, OnInit, HostListener } from '@angular/core';
import { AuthService } from '../../login/services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  scrolled: boolean = false;
  userName: string = '';
  fname: string = '';
  lname: string = "";

  @HostListener("window:scroll", [])
  onWindowScroll() {
    this.scrolled = window.scrollY > 1;
  }
  constructor(public auth: AuthService, private router: Router) { }

  ngOnInit(): void {
    if (this.auth.isLoggedIn()) {
      this.router.navigate(['dashboard']);
    }
    const user = this.auth.getUserName();
    this.userName = user.role_name;
    this.fname = user.first_name.charAt(0);
    this.lname = user.last_name.charAt(0);
  }

  logOut() {
    localStorage.removeItem('user_details');
    this.router.navigate(['/login']);
  }
}

below is login component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AuthService } from './services/auth.service';
import { Router } from '@angular/router';
import { Md5 } from 'md5-typescript';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: any;
  data: any;
  success: any;
  message: any;

  constructor( private auth: AuthService, private router: Router ) {

    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required, Validators.pattern('^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$')]),
      password: new FormControl('', Validators.required)
    });

  }

  ngOnInit(): void { }

  onSubmit() {
    console.log(this.loginForm.value);
    let data = {
      "email_id": this.loginForm.value.email,
      "password": Md5.init(this.loginForm.controls['password'].value)
    }
    this.auth.loginUser(data).subscribe(
      (response: any) => {
        this.data == response;
        this.success == response.success;
        if (response.success == 1) {
          localStorage.setItem("user_details", JSON.stringify(JSON.parse(response.data).user_details))
          console.log(localStorage.getItem('user_details'));
          this.router.navigate(['dashboard']);
        } else {
          this.message = response.message;
        }
      }
    );
    this.loginForm.reset();
  }
}


问:
Morphism, product, coproduct operator precedence and associativity
I am writing a parser that will parse a simple functional toy language.

I'm having tough time with operator precedence and associativity of morphism, product and coproduct operators.

My toy language looks a tiny bit like Haskell. Example for context:

let point: (int, int) = (0, 0)         // product
let either: (int | str) = "hello"      // coproduct
let increment: int -> int = a -> a + 1 // morphism
```

In parsing types, I have a hard time deciding if the binary infix morphism operator -> should be right or left associative. The binary infix functional composition operator . is right associative if I'm not mistaken; maybe it's the same with this operator too?

Should int -> int -> int be parsed as (int -> int) -> int or int -> (int -> int)?

What is the precedence of this operator in relation with the binary infix product and coproduct operators (,, |)?

Right now I have the following priorities (from highest to lowest):

morphism

product

coproduct

This means that in absence of round grouping parenthesis (...) the language behaves as follows:

The product str, int -> int, str gets parsed as str, (int -> int), str.

The coproduct int | str -> int | str has the same effect int | (str -> int) | str.

And str, int -> int | int gets parsed as (str, (int -> int) | int).

Is that correct or am I doing something wrong?

Reasons why this is a valid question

I apologise but I'm avoiding getting flagged when this is a good question because:

I could not find resources that explain how these three operators are related to each other, in which way, precedence and associativity.

I can't split the question in smaller questions because a change in the general behaviour of one of those things will affect the others significantly.

This is a programming related question since it is about abstract syntax tree generation of a programming language.

I haven't found similar questions regarding these operators in here (maybe I'm using the wrong keywords).

Other people might stumble upon the same problem when making a parser.

It doesn't look like it's opinion based to me.

So please consider leaving a comment to tell me how I should improve the question.

答: There is a good reason for associativity rules in Haskell. They follow the idea of the currying adjunction. A function of two arguments is isomorphic to a function returning a function. So (a, b) -> c is curried to a -> (b -> c). This is why a->b->c is interpreted as a function returning a function and not (a->b)->c, which would be a function taking a function as an argument. Conversely, for function application we parse f g h as f taking two arguments f and g. So function application is left associative, (f g) h: f acting on g produces a function that subsequently acts on h. As for products and coproducts, they are just treated like multiplication and addition with the usual precedence rules. Incidentally, a->b corresponds to the exponential b to the power of a, which also makes sense as far as associativity goes.

Body:
I am writing a parser that will parse a simple functional toy language.

I'm having tough time with operator precedence and associativity of morphism, product and coproduct operators.

My toy language looks a tiny bit like Haskell. Example for context:

let point: (int, int) = (0, 0)         // product
let either: (int | str) = "hello"      // coproduct
let increment: int -> int = a -> a + 1 // morphism

In parsing types, I have a hard time deciding if the binary infix morphism operator -> should be right or left associative. The binary infix functional composition operator . is right associative if I'm not mistaken; maybe it's the same with this operator too?

Should int -> int -> int be parsed as (int -> int) -> int or int -> (int -> int)?

What is the precedence of this operator in relation with the binary infix product and coproduct operators (,, |)?

Right now I have the following priorities (from highest to lowest):

morphism

product

coproduct

This means that in absence of round grouping parenthesis (...) the language behaves as follows:

The product str, int -> int, str gets parsed as str, (int -> int), str.

The coproduct int | str -> int | str has the same effect int | (str -> int) | str.

And str, int -> int | int gets parsed as (str, (int -> int) | int).

Is that correct or am I doing something wrong?

Reasons why this is a valid question

I apologise but I'm avoiding getting flagged when this is a good question because:

I could not find resources that explain how these three operators are related to each other, in which way, precedence and associativity.

I can't split the question in smaller questions because a change in the general behaviour of one of those things will affect the others significantly.

This is a programming related question since it is about abstract syntax tree generation of a programming language.

I haven't found similar questions regarding these operators in here (maybe I'm using the wrong keywords).

Other people might stumble upon the same problem when making a parser.

It doesn't look like it's opinion based to me.

So please consider leaving a comment to tell me how I should improve the question.


问:
Get data attribute of script tag?
Say I've got the following script tag:

```<code><script async data-id="p3PkBtuA" src="//example.com/embed.js"></script>
</code>```

Within that embed.js file, how can I get the value of data-id attribute?

I'm trying to keep the embed.js file as light as possible, so ideally it wouldn't need to use some sort of javascript library.

答:
Use currentScript

Script tag :

```<code><script async data-id="p3PkBtuA" data-foo ="bar" src="//example.com/example.js"></script>
</code>```

In example.js file :

```<code>let id = document.currentScript.getAttribute('data-id');
let foo = document.currentScript.getAttribute('data-foo');

console.log(id) // p3PkBtuA
console.log(foo) // bar
</code>```

Title: Get data attribute of script tag?

Body:
Say I've got the following script tag:

Within that embed.js file, how can I get the value of data-id attribute?

I'm trying to keep the embed.js file as light as possible, so ideally it wouldn't need to use some sort of javascript library.

Body:
Use currentScript

Script tag :

<script async data-id="p3PkBtuA" data-foo ="bar" src="//example.com/example.js"></script>

In example.js file :

let id = document.currentScript.getAttribute('data-id');
let foo = document.currentScript.getAttribute('data-foo');

console.log(id) // p3PkBtuA
console.log(foo) // bar


问:
Creating new column with sets in Pandas DataFrame
Hello_world!

I have a DataFrame like this:

```<code>from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})
</code>```

or

```<code>    A   B   C   D   E
0   sd  hj  hf  1q  9i
1   df  4r  qw  nc  g7
2   gh  tg  e4  xf  ce
3   rv  2s  7u  7y  x3
</code>```

I need to create a new column that will contain values of the set type, consisting of the values of the first five columns.

Expected result is:

```<code>    A   B   C   D   E   F
0   sd  hj  hf  1q  9i  {'sd','hj', 'hf', '1q', '9i'}
1   df  4r  qw  nc  g7  {'df','4r', 'qw', 'nc', 'g7'}
2   gh  tg  e4  xf  ce  {'gh','tg', 'e4', 'xf', 'ce'}
3   rv  2s  7u  7y  x3  {'rv','2s', '7u', '7y', 'x3'}

print(type(df.loc[0, 'F']))    # <class 'set'>
print(type(df.loc[0, 'A']))    # <class 'str'>
</code>```

My code:

```<code>from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})

f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D'], df.loc[0, 'E']}

df = df.assign(F = f)

print(df)
</code>```

...have ValueError: Length of values (5) does not match length of index (4).

If I rewrite the code so that the length of the values matches the length of the index:

```<code>from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})

f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D']}

df = df.assign(F = f)

print(df)
</code>```

...I have TypeError: 'set' type is unordered.

I ask the respected community for help to solve my problem.

答:
Simply use:

```<code>df['F'] = df.apply(set, axis=1)
</code>```

Note however that you have no control over the displayed order of sets as they are unordered containers.

Output:

```<code>    A   B   C   D   E                     F
0  sd  hj  hf  1q  9i  {hj, 1q, 9i, sd, hf}
1  df  4r  qw  nc  g7  {nc, df, qw, g7, 4r}
2  gh  tg  e4  xf  ce  {e4, xf, gh, ce, tg}
3  rv  2s  7u  7y  x3  {7u, x3, rv, 2s, 7y}
</code>```

Body:
Hello_world!

I have a DataFrame like this:

from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})

or

    A   B   C   D   E
0   sd  hj  hf  1q  9i
1   df  4r  qw  nc  g7
2   gh  tg  e4  xf  ce
3   rv  2s  7u  7y  x3

I need to create a new column that will contain values of the set type, consisting of the values of the first five columns.

Expected result is:

    A   B   C   D   E   F
0   sd  hj  hf  1q  9i  {'sd','hj', 'hf', '1q', '9i'}
1   df  4r  qw  nc  g7  {'df','4r', 'qw', 'nc', 'g7'}
2   gh  tg  e4  xf  ce  {'gh','tg', 'e4', 'xf', 'ce'}
3   rv  2s  7u  7y  x3  {'rv','2s', '7u', '7y', 'x3'}

print(type(df.loc[0, 'F']))    # <class 'set'>
print(type(df.loc[0, 'A']))    # <class 'str'>

My code:

from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})

f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D'], df.loc[0, 'E']}

df = df.assign(F = f)

print(df)

...have ValueError: Length of values (5) does not match length of index (4).

If I rewrite the code so that the length of the values matches the length of the index:

from pandas import DataFrame

df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
                "B": ['hj', '4r', 'tg', '2s'],
                "C": ['hf', 'qw', 'e4', '7u'],
                "D": ['1q', 'nc', 'xf', '7y'],
                "E": ['9i', 'g7', 'ce', 'x3']})

f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D']}

df = df.assign(F = f)

print(df)

...I have TypeError: 'set' type is unordered.

I ask the respected community for help to solve my problem.

Body:
Simply use:

df['F'] = df.apply(set, axis=1)

Note however that you have no control over the displayed order of sets as they are unordered containers.

Output:

    A   B   C   D   E                     F
0  sd  hj  hf  1q  9i  {hj, 1q, 9i, sd, hf}
1  df  4r  qw  nc  g7  {nc, df, qw, g7, 4r}
2  gh  tg  e4  xf  ce  {e4, xf, gh, ce, tg}
3  rv  2s  7u  7y  x3  {7u, x3, rv, 2s, 7y}


问:
requests only partially obtains status codes for a list of URLs
The script below gets status codes for a list of URLs found in the variable link, then checks for the status codes before appending them to respective URLs.

Unfortunately, I've been facing an issue where only some URLs have status codes appended to them, while others don't.

I'm not sure if the problem is with the requests library obtaining the status codes, or with the process of appending. Either way, something goes awry.

I tried removing session and replacing it with requests. I also tried replacing the user agent with another one, and removing it entirely. Nothing worked.

I was able to replicate the output using an online Python compiler, so it goes to show that there's something possibly wrong with the code or the requests library.

Additionally, I tried a different regex (http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+, one that catches all URLs) and with a different list, and I got similar results: some with status codes, others without.

Script

```<code>import requests, re
from requests import Session
session = Session()

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/tiredarabwoman/status&matchType=prefix&filter=statuscode:200&from=20220207&to=20220209"
banana = []
y = session.get(link).text
urls = re.findall(r'https?://(?:www\.)?(?:mobile\.)?twitter\.com/(?:#!/)?\w+/status(?:es)?/\d+', y)

for url in urls:
    banana.append(f"{url}")

apple = list(set(banana))

results = []
headers = {'user-agent':'Mozilla/5.0 (compatible; DuckDuckBot-Https/1.1; https://duckduckgo.com/duckduckbot)'}

for url in apple:
    response = session.get(url, headers=headers)
    status_code = response.status_code
    results.append((url, status_code))

for url, status_code in results:
    apple.append(f"{url} {status_code}")

print(apple)
</code>```

Output

```<code>['https://twitter.com/tiredarabwoman/status/1490817344339329026', 'https://twitter.com/tiredarabwoman/status/1490792906596175872', 'https://twitter.com/tiredarabwoman/status/1491208045388775426', 'https://twitter.com/tiredarabwoman/status/1491465751697502213', 'https://twitter.com/tiredarabwoman/status/1491545382832250880', 'https://twitter.com/tiredarabwoman/status/1491545181165920268', 'https://twitter.com/tiredarabwoman/status/1490855316661149697', 'https://twitter.com/tiredarabwoman/status/1491546028239110145', 'https://twitter.com/tiredarabwoman/status/1491464782150615042', 'https://twitter.com/tiredarabwoman/status/1491547108331118597', 'https://twitter.com/tiredarabwoman/status/1490597347629404164', 'https://twitter.com/tiredarabwoman/status/1491545016052981763', 'https://twitter.com/tiredarabwoman/status/1491180990127276033', 'https://twitter.com/tiredarabwoman/status/1490833920669061124', 'https://twitter.com/tiredarabwoman/status/1490823383780630529', 'https://twitter.com/tiredarabwoman/status/1491545630333976579', 'https://twitter.com/tiredarabwoman/status/1490785997243793412', 'https://twitter.com/tiredarabwoman/status/1490824991608557570', 'https://twitter.com/tiredarabwoman/status/1490854364831174657', 'https://twitter.com/tiredarabwoman/status/1491455740984573954', 'https://twitter.com/tiredarabwoman/status/1490825179076825089', 'https://twitter.com/tiredarabwoman/status/1490855625034985473', 'https://twitter.com/tiredarabwoman/status/1490821052183846915', 'https://twitter.com/tiredarabwoman/status/1491515906199068678', 'https://twitter.com/tiredarabwoman/status/1491193051779563522', 'https://twitter.com/tiredarabwoman/status/1491498731585343491', 'https://twitter.com/tiredarabwoman/status/1490642306759864325', 'https://twitter.com/tiredarabwoman/status/1491454956984881156', 'https://twitter.com/tiredarabwoman/status/1491455552282853376', 'https://twitter.com/tiredarabwoman/status/1490817344339329026 200', 'https://twitter.com/tiredarabwoman/status/1490792906596175872 200', 'https://twitter.com/tiredarabwoman/status/1491208045388775426 200', 'https://twitter.com/tiredarabwoman/status/1491465751697502213 200', 'https://twitter.com/tiredarabwoman/status/1491545382832250880 200', 'https://twitter.com/tiredarabwoman/status/1491545181165920268 200', 'https://twitter.com/tiredarabwoman/status/1490855316661149697 200', 'https://twitter.com/tiredarabwoman/status/1491546028239110145 200', 'https://twitter.com/tiredarabwoman/status/1491464782150615042 200', 'https://twitter.com/tiredarabwoman/status/1491547108331118597 200', 'https://twitter.com/tiredarabwoman/status/1490597347629404164 200', 'https://twitter.com/tiredarabwoman/status/1491545016052981763 200', 'https://twitter.com/tiredarabwoman/status/1491180990127276033 200', 'https://twitter.com/tiredarabwoman/status/1490833920669061124 200', 'https://twitter.com/tiredarabwoman/status/1490823383780630529 200', 'https://twitter.com/tiredarabwoman/status/1491545630333976579 200', 'https://twitter.com/tiredarabwoman/status/1490785997243793412 200', 'https://twitter.com/tiredarabwoman/status/1490824991608557570 200', 'https://twitter.com/tiredarabwoman/status/1490854364831174657 200', 'https://twitter.com/tiredarabwoman/status/1491455740984573954 200', 'https://twitter.com/tiredarabwoman/status/1490825179076825089 200', 'https://twitter.com/tiredarabwoman/status/1490855625034985473 200', 'https://twitter.com/tiredarabwoman/status/1490821052183846915 200', 'https://twitter.com/tiredarabwoman/status/1491515906199068678 200', 'https://twitter.com/tiredarabwoman/status/1491193051779563522 200', 'https://twitter.com/tiredarabwoman/status/1491498731585343491 200', 'https://twitter.com/tiredarabwoman/status/1490642306759864325 200', 'https://twitter.com/tiredarabwoman/status/1491454956984881156 200', 'https://twitter.com/tiredarabwoman/status/1491455552282853376 200']
</code>```

答: You are printing the apple list, which also contains the original list of URLs. All items in your result list seems to have status code, which is what you want.

Body:
The script below gets status codes for a list of URLs found in the variable link, then checks for the status codes before appending them to respective URLs.

Unfortunately, I've been facing an issue where only some URLs have status codes appended to them, while others don't.

I'm not sure if the problem is with the requests library obtaining the status codes, or with the process of appending. Either way, something goes awry.

I tried removing session and replacing it with requests. I also tried replacing the user agent with another one, and removing it entirely. Nothing worked.

I was able to replicate the output using an online Python compiler, so it goes to show that there's something possibly wrong with the code or the requests library.

Additionally, I tried a different regex (http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+, one that catches all URLs) and with a different list, and I got similar results: some with status codes, others without.

Script

import requests, re
from requests import Session
session = Session()

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/tiredarabwoman/status&matchType=prefix&filter=statuscode:200&from=20220207&to=20220209"
banana = []
y = session.get(link).text
urls = re.findall(r'https?://(?:www\.)?(?:mobile\.)?twitter\.com/(?:#!/)?\w+/status(?:es)?/\d+', y)

for url in urls:
    banana.append(f"{url}")

apple = list(set(banana))

results = []
headers = {'user-agent':'Mozilla/5.0 (compatible; DuckDuckBot-Https/1.1; https://duckduckgo.com/duckduckbot)'}

for url in apple:
    response = session.get(url, headers=headers)
    status_code = response.status_code
    results.append((url, status_code))

for url, status_code in results:
    apple.append(f"{url} {status_code}")

print(apple)

Output

['https://twitter.com/tiredarabwoman/status/1490817344339329026', 'https://twitter.com/tiredarabwoman/status/1490792906596175872', 'https://twitter.com/tiredarabwoman/status/1491208045388775426', 'https://twitter.com/tiredarabwoman/status/1491465751697502213', 'https://twitter.com/tiredarabwoman/status/1491545382832250880', 'https://twitter.com/tiredarabwoman/status/1491545181165920268', 'https://twitter.com/tiredarabwoman/status/1490855316661149697', 'https://twitter.com/tiredarabwoman/status/1491546028239110145', 'https://twitter.com/tiredarabwoman/status/1491464782150615042', 'https://twitter.com/tiredarabwoman/status/1491547108331118597', 'https://twitter.com/tiredarabwoman/status/1490597347629404164', 'https://twitter.com/tiredarabwoman/status/1491545016052981763', 'https://twitter.com/tiredarabwoman/status/1491180990127276033', 'https://twitter.com/tiredarabwoman/status/1490833920669061124', 'https://twitter.com/tiredarabwoman/status/1490823383780630529', 'https://twitter.com/tiredarabwoman/status/1491545630333976579', 'https://twitter.com/tiredarabwoman/status/1490785997243793412', 'https://twitter.com/tiredarabwoman/status/1490824991608557570', 'https://twitter.com/tiredarabwoman/status/1490854364831174657', 'https://twitter.com/tiredarabwoman/status/1491455740984573954', 'https://twitter.com/tiredarabwoman/status/1490825179076825089', 'https://twitter.com/tiredarabwoman/status/1490855625034985473', 'https://twitter.com/tiredarabwoman/status/1490821052183846915', 'https://twitter.com/tiredarabwoman/status/1491515906199068678', 'https://twitter.com/tiredarabwoman/status/1491193051779563522', 'https://twitter.com/tiredarabwoman/status/1491498731585343491', 'https://twitter.com/tiredarabwoman/status/1490642306759864325', 'https://twitter.com/tiredarabwoman/status/1491454956984881156', 'https://twitter.com/tiredarabwoman/status/1491455552282853376', 'https://twitter.com/tiredarabwoman/status/1490817344339329026 200', 'https://twitter.com/tiredarabwoman/status/1490792906596175872 200', 'https://twitter.com/tiredarabwoman/status/1491208045388775426 200', 'https://twitter.com/tiredarabwoman/status/1491465751697502213 200', 'https://twitter.com/tiredarabwoman/status/1491545382832250880 200', 'https://twitter.com/tiredarabwoman/status/1491545181165920268 200', 'https://twitter.com/tiredarabwoman/status/1490855316661149697 200', 'https://twitter.com/tiredarabwoman/status/1491546028239110145 200', 'https://twitter.com/tiredarabwoman/status/1491464782150615042 200', 'https://twitter.com/tiredarabwoman/status/1491547108331118597 200', 'https://twitter.com/tiredarabwoman/status/1490597347629404164 200', 'https://twitter.com/tiredarabwoman/status/1491545016052981763 200', 'https://twitter.com/tiredarabwoman/status/1491180990127276033 200', 'https://twitter.com/tiredarabwoman/status/1490833920669061124 200', 'https://twitter.com/tiredarabwoman/status/1490823383780630529 200', 'https://twitter.com/tiredarabwoman/status/1491545630333976579 200', 'https://twitter.com/tiredarabwoman/status/1490785997243793412 200', 'https://twitter.com/tiredarabwoman/status/1490824991608557570 200', 'https://twitter.com/tiredarabwoman/status/1490854364831174657 200', 'https://twitter.com/tiredarabwoman/status/1491455740984573954 200', 'https://twitter.com/tiredarabwoman/status/1490825179076825089 200', 'https://twitter.com/tiredarabwoman/status/1490855625034985473 200', 'https://twitter.com/tiredarabwoman/status/1490821052183846915 200', 'https://twitter.com/tiredarabwoman/status/1491515906199068678 200', 'https://twitter.com/tiredarabwoman/status/1491193051779563522 200', 'https://twitter.com/tiredarabwoman/status/1491498731585343491 200', 'https://twitter.com/tiredarabwoman/status/1490642306759864325 200', 'https://twitter.com/tiredarabwoman/status/1491454956984881156 200', 'https://twitter.com/tiredarabwoman/status/1491455552282853376 200']


问:
About Swift closure captures a weak property
Let us say we have a class A like below

```<code>    class SomeView {
       var didDoneSomething: () -> Void = {}
    }
    class A {
       weak delegate: B?

       private lazy var someView: SomeView {
           let view = someView()
           view.didDoneSomething = { [delegate] in
              delegate?.someFunction()
           }
           return view
       }
    }
</code>```

I was reading this article by Sundell
https://www.swiftbysundell.com/articles/swifts-closure-capturing-mechanics/

It looks like you can directly capture any properties as long as those properties either contain reference types (class instances), or immutable value types.

I am not so sure if it has retain cycle problem or not. Should I use [weak delegate] or not?

Any suggestion? Thank you!

答:
Assuming request method is an instance function of ImageLoader, there should not be a retain cycle at all.

On the other hand, if we have something like this:

```<code>class ImageLoader {
    private let service: ServiceProtocol

    private let cache = Cache<URL, Image>()

    func loadImage(
        from url: URL,
        then handler: @escaping (Result<Image, Error>) -> Void
    ) {
        service.request(url) { [cache] result in
            do {
                let image = try result.decodedAsImage()
                cache.insert(image, forKey: url)
                handler(.success(image))
            } catch {
                handler(.failure(error))
            }
        }
    }
}
</code>```

This indeed creates a retain cycle because ImageLoader will have a strong reference to the service dependency, and service will reference ImageLoader (it calls self.cache) in its closure. In this case, Cache would need to be captured as a weak reference.

Body:
Let us say we have a class A like below

    class SomeView {
       var didDoneSomething: () -> Void = {}
    }
    class A {
       weak delegate: B?

       private lazy var someView: SomeView {
           let view = someView()
           view.didDoneSomething = { [delegate] in
              delegate?.someFunction()
           }
           return view
       }
    }

I was reading this article by Sundell
https://www.swiftbysundell.com/articles/swifts-closure-capturing-mechanics/

It looks like you can directly capture any properties as long as those properties either contain reference types (class instances), or immutable value types.

I am not so sure if it has retain cycle problem or not. Should I use [weak delegate] or not?

Any suggestion? Thank you!

Body:
Assuming request method is an instance function of ImageLoader, there should not be a retain cycle at all.

On the other hand, if we have something like this:

class ImageLoader {
    private let service: ServiceProtocol

    private let cache = Cache<URL, Image>()

    func loadImage(
        from url: URL,
        then handler: @escaping (Result<Image, Error>) -> Void
    ) {
        service.request(url) { [cache] result in
            do {
                let image = try result.decodedAsImage()
                cache.insert(image, forKey: url)
                handler(.success(image))
            } catch {
                handler(.failure(error))
            }
        }
    }
}

This indeed creates a retain cycle because ImageLoader will have a strong reference to the service dependency, and service will reference ImageLoader (it calls self.cache) in its closure. In this case, Cache would need to be captured as a weak reference.


问:
Reset conda root directory?
I recently switched mac computers. My old computer had conda and all the relevant libraries and environments installed. I transferred all the files from the old computer to my new one. However, my new computer has a different username (home directory name) than the old one, so whenever I run conda commands, I get errors like the following:

```<code>__conda_exe:2: no such file or directory: /Users/[old_username]/anaconda/bin/conda
</code>```

I can circumvent this initial error by manually setting $PATH each time, but then I still get errors like this:

```<code>__add_sys_prefix_to_path:6: command not found: dirname
__add_sys_prefix_to_path:7: command not found: dirname
__conda_exe:2: no such file or directory: /Users/[old_username]/anaconda/bin/conda
</code>```

Is there a way to change this so the commands point to my new home directory?

答:
I believe you need to use CPR (conda-prefix-replacement) for this.

However, I'd instead recommend not manually transferring the files, since this usually fails to retain hardlinks. Instead, dump each of your environments to YAML

```<code>conda env export -n envname > env.yaml
</code>```

and recreate them on the new system (after a minimal base install, like Miniconda)

```<code>conda env create -n envname -f env.yaml
</code>```

I would not recommend transferring the old base, but if you must, put it in a new location:

```<code># old system
conda env export -n base > old_base.yaml

# new system
conda env create -n old_base -f old_base.yaml
</code>```

Title: Reset conda root directory?

Body:
I recently switched mac computers. My old computer had conda and all the relevant libraries and environments installed. I transferred all the files from the old computer to my new one. However, my new computer has a different username (home directory name) than the old one, so whenever I run conda commands, I get errors like the following:

__conda_exe:2: no such file or directory: /Users/[old_username]/anaconda/bin/conda

I can circumvent this initial error by manually setting $PATH each time, but then I still get errors like this:

__add_sys_prefix_to_path:6: command not found: dirname
__add_sys_prefix_to_path:7: command not found: dirname
__conda_exe:2: no such file or directory: /Users/[old_username]/anaconda/bin/conda

Is there a way to change this so the commands point to my new home directory?

Body:
I believe you need to use CPR (conda-prefix-replacement) for this.

However, I'd instead recommend not manually transferring the files, since this usually fails to retain hardlinks. Instead, dump each of your environments to YAML

conda env export -n envname > env.yaml

and recreate them on the new system (after a minimal base install, like Miniconda)

conda env create -n envname -f env.yaml

I would not recommend transferring the old base, but if you must, put it in a new location:

# old system
conda env export -n base > old_base.yaml

# new system
conda env create -n old_base -f old_base.yaml


问:
confusionMatrix for knn classification in R
I wanted to use the optimal k value to conduct kNN clasification and predict the dependent variable diabetes in test set using train set and compare the results with the real values.

I've already got optimal k value and got the accruacy already. After that, I wanted to compare the results with the real value with using confussionMatrix but I got the problem with the different length.

I've already checked that nrow and length quantities are same(with 74) but it still have same problem.

Could you help me to overcome this problem?

My codes are as like below

```<code>install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)

NN

Accuracy3 <- sum(NN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
Knn_K <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = kk)
AccuracyK <- c(AccuracyK, sum(Knn_K == MLTrainY$'MLTrain[, 9]') / length(MLTrainY$'MLTrain[, 9]'))

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
 data = ValidK,
 type = "o",
 pch = 5,
 main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 120)

Accuracy120 <- sum(NN120 == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy120

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
           test = TestXNormDF,
           cl = MLTrainY$`MLTrain[, 9]`,
           k = 120)

AccuracyFinal <- sum(FinalNN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

AccuracyFinal
</code>```

And here I got the problem.

```<code>Result <- confusionMatrix(FinalNN, TestXNormDF)
</code>```

答:
I think you are looking to this:

```<code>Result <- confusionMatrix(FinalNN, MLTestY$`MLTest[, 9]` )
Confusion Matrix and Statistics

          Reference
Prediction neg pos
       neg  49  22
       pos   0   3

               Accuracy : 0.7027
                 95% CI : (0.5852, 0.8034)
    No Information Rate : 0.6622
    P-Value [Acc > NIR] : 0.2724

                  Kappa : 0.153

 Mcnemar's Test P-Value : 7.562e-06

            Sensitivity : 1.0000
            Specificity : 0.1200
         Pos Pred Value : 0.6901
         Neg Pred Value : 1.0000
             Prevalence : 0.6622
         Detection Rate : 0.6622
   Detection Prevalence : 0.9595
      Balanced Accuracy : 0.5600

       'Positive' Class : neg
</code>```

Besides that, I recommend to fix the brackets on the for and change some code. A good refactoring would help !

Body:
I wanted to use the optimal k value to conduct kNN clasification and predict the dependent variable diabetes in test set using train set and compare the results with the real values.

I've already got optimal k value and got the accruacy already. After that, I wanted to compare the results with the real value with using confussionMatrix but I got the problem with the different length.

I've already checked that nrow and length quantities are same(with 74) but it still have same problem.

Could you help me to overcome this problem?

My codes are as like below

install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)

NN

Accuracy3 <- sum(NN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
Knn_K <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = kk)
AccuracyK <- c(AccuracyK, sum(Knn_K == MLTrainY$'MLTrain[, 9]') / length(MLTrainY$'MLTrain[, 9]'))

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
 data = ValidK,
 type = "o",
 pch = 5,
 main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 120)

Accuracy120 <- sum(NN120 == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy120

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
           test = TestXNormDF,
           cl = MLTrainY$`MLTrain[, 9]`,
           k = 120)

AccuracyFinal <- sum(FinalNN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

AccuracyFinal

And here I got the problem.

Result <- confusionMatrix(FinalNN, TestXNormDF)

Body:
I think you are looking to this:

Result <- confusionMatrix(FinalNN, MLTestY$`MLTest[, 9]` )
Confusion Matrix and Statistics

          Reference
Prediction neg pos
       neg  49  22
       pos   0   3

               Accuracy : 0.7027
                 95% CI : (0.5852, 0.8034)
    No Information Rate : 0.6622
    P-Value [Acc > NIR] : 0.2724

                  Kappa : 0.153

 Mcnemar's Test P-Value : 7.562e-06

            Sensitivity : 1.0000
            Specificity : 0.1200
         Pos Pred Value : 0.6901
         Neg Pred Value : 1.0000
             Prevalence : 0.6622
         Detection Rate : 0.6622
   Detection Prevalence : 0.9595
      Balanced Accuracy : 0.5600

       'Positive' Class : neg

Besides that, I recommend to fix the brackets on the for and change some code. A good refactoring would help !


问:
Target a button with its content
I've two buttons with same class but different content

```<code><a class="button ordrViewBtn">Sold Out</a>
<a class="button ordrViewBtn">Re-Sell</a>
</code>```

I would like to change color of Sold Out button. is it possible to target a button with its content?

答:
```<code><a class="button ordrViewBtn" id="ordrViewBtn">Sold Out</a>

alert($("#ordrViewBtn").text());
</code>```

Title: Target a button with its content

Body:
I've two buttons with same class but different content

Sold Out
Re-Sell

I would like to change color of Sold Out button. is it possible to target a button with its content?


答:
Use List comprehension for better performance:

```<code>In [1069]: df['F'] = [set(i) for i in df.values]

In [1070]: df
Out[1070]:
    A   B   C   D   E                     F
0  sd  hj  hf  1q  9i  {sd, 1q, hf, 9i, hj}
1  df  4r  qw  nc  g7  {g7, 4r, nc, df, qw}
2  gh  tg  e4  xf  ce  {xf, gh, ce, e4, tg}
3  rv  2s  7u  7y  x3  {2s, x3, 7y, rv, 7u}
</code>```

OR as suggested by @jezrael:

```<code>df['F'] = [set(i) for i in df.to_numpy()]
</code>```

To use specific columns:

If you want to use let's say : B,C,D, do this:

```<code>In [1103]: df['F'] = [set(i) for i in df[['B', 'C', 'D']].to_numpy()]

In [1104]: df
Out[1104]:
    A   B   C   D   E             F
0  sd  hj  hf  1q  9i  {hf, hj, 1q}
1  df  4r  qw  nc  g7  {nc, qw, 4r}
2  gh  tg  e4  xf  ce  {xf, tg, e4}
3  rv  2s  7u  7y  x3  {7y, 7u, 2s}
</code>```

Performance timings:

@mozway's solution:

```<code>In [1078]: %timeit df.apply(set, axis=1)
395 µs ± 24.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

My solution:

```<code>In [1079]: %timeit [set(i) for i in df.values]
7.3 µs ± 31.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Title: Creating new column with sets in Pandas DataFrame

Body:
Use List comprehension for better performance:

In [1069]: df['F'] = [set(i) for i in df.values]

In [1070]: df
Out[1070]:
    A   B   C   D   E                     F
0  sd  hj  hf  1q  9i  {sd, 1q, hf, 9i, hj}
1  df  4r  qw  nc  g7  {g7, 4r, nc, df, qw}
2  gh  tg  e4  xf  ce  {xf, gh, ce, e4, tg}
3  rv  2s  7u  7y  x3  {2s, x3, 7y, rv, 7u}

OR as suggested by @jezrael:

df['F'] = [set(i) for i in df.to_numpy()]

To use specific columns:

If you want to use let's say : B,C,D, do this:

In [1103]: df['F'] = [set(i) for i in df[['B', 'C', 'D']].to_numpy()]

In [1104]: df
Out[1104]:
    A   B   C   D   E             F
0  sd  hj  hf  1q  9i  {hf, hj, 1q}
1  df  4r  qw  nc  g7  {nc, qw, 4r}
2  gh  tg  e4  xf  ce  {xf, tg, e4}
3  rv  2s  7u  7y  x3  {7y, 7u, 2s}

Performance timings:

@mozway's solution:

In [1078]: %timeit df.apply(set, axis=1)
395 µs ± 24.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

My solution:

In [1079]: %timeit [set(i) for i in df.values]
7.3 µs ± 31.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
Unable to combine and generate reports on cypress
I am unable to combine and generate reports of the CLI run on cypress, but when I run the script manually it saves the report

package.json
 scripts" />

 dependencies" />

config.json

答:
Your package.json should look like this

And cypress.json should look like this