问:
ValueError: Expected 2D array, got scalar array instead: array=750
```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.linear_model import LinearRegression

data=pd.read_csv('real_estate_price_size.csv')
y=data['price']
x=data['size']
y.shape
x.shape
</code>```

both out put is same (100,)

```<code>x_matrix = x.values.reshape(-1,1)
reg = LinearRegression()
reg.fit(x_matrix,y)
reg.predict(750)
</code>```

when i run this i get error as

```<code>ValueError: Expected 2D array, got scalar array instead:
array=750.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or
array.reshape(1, -1) if it contains a single sample.
</code>```

i cant under stand what to do i tried reshaping it but it dint work out.

and (2) previously when i typed

```<code>reg = LinearRegression()
reg.fit(x_matrix,y)
</code>```

i used to get output like this

```<code>LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
</code>```

now i just get text like

```<code> LinearRegression()
</code>```

help would be much appriciated .

答:
You are missing a dimension. Your prediction input should have the shape (n_samples, n_features). Try something like this:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.linear_model import LinearRegression

y=np.random.random((100, 1))
x=np.random.random((100, 1))

reg = LinearRegression()
reg.fit(x,y)

predict_input = np.array([[750]])
predict_input.shape
reg.predict(predict_input)
```
```(1, 1)
array([[-26.07506481]])
```

Body:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.linear_model import LinearRegression

data=pd.read_csv('real_estate_price_size.csv')
y=data['price']
x=data['size']
y.shape
x.shape

both out put is same (100,)

x_matrix = x.values.reshape(-1,1)
reg = LinearRegression()
reg.fit(x_matrix,y)
reg.predict(750)

when i run this i get error as

ValueError: Expected 2D array, got scalar array instead:
array=750.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or
array.reshape(1, -1) if it contains a single sample.

i cant under stand what to do i tried reshaping it but it dint work out.

and (2) previously when i typed

reg = LinearRegression()
reg.fit(x_matrix,y)

i used to get output like this

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

now i just get text like

 LinearRegression()

help would be much appriciated .

Body:
You are missing a dimension. Your prediction input should have the shape (n_samples, n_features). Try something like this:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.linear_model import LinearRegression

y=np.random.random((100, 1))
x=np.random.random((100, 1))

reg = LinearRegression()
reg.fit(x,y)

predict_input = np.array([[750]])
predict_input.shape
reg.predict(predict_input)

(1, 1)
array([[-26.07506481]])


来源: stackexchange

问:
windows git bash on startup can't find agent.env
```<code>Windows 10
Git for Windows 64 v2.13.0.windows.1
</code>```

To config ssh with private-key passphrase I'm following this GitHub doc :

https://help.github.com/articles/working-with-ssh-key-passphrases/

Specifically, I add to my ~/.ssh/.bashrc the following script:

```<code>env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env
</code>```

However when I start Git Bash it can't find ~/.ssh/agent.env :

```<code>bash: env=~/.ssh/agent.env: No such file or directory
bash: : No such file or directory
bash: : No such file or directory
Could not open a connection to your authentication agent.
</code>```

What is agent.env and how is it typically installed or what should it contain ?

答: For others who end up here trying to figure out why their script isn't executing when they add it to either ~/.profile or ~/.bashrc, I found I needed to add it to ~/.bash_profile for it to get picked up and used by Git Bash on Windows.

ContentLicense: CC BY-SA 3.0

Body:
Windows 10
Git for Windows 64 v2.13.0.windows.1

To config ssh with private-key passphrase I'm following this GitHub doc :

https://help.github.com/articles/working-with-ssh-key-passphrases/

Specifically, I add to my ~/.ssh/.bashrc the following script:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

However when I start Git Bash it can't find ~/.ssh/agent.env :

bash: env=~/.ssh/agent.env: No such file or directory
bash: : No such file or directory
bash: : No such file or directory
Could not open a connection to your authentication agent.

What is agent.env and how is it typically installed or what should it contain ?

ContentLicense: CC BY-SA 4.0


问:
Rock, Paper, Scissors - debugging multiple round game
Kindly assist with the completion of the code. Especially with the game() function. The problems are listed below.

The computerPlay() does not change when the loop runs over, it maintains the same answer to the end of the loop.

Also, I need the game() function to be able to print out the player with the most WIN OUTPUT

WHAT MY CODE DOES

Because the outputs are the same, it is able to tell the winner after the number of rounds set.

The output is then stored in an array.

Kindly note that some of the codes are commented. You can uncomment it to help me modify it if possible or give similar solutions.

//Computer player argorithm
function computerPlay(){
    let comOption = ""
    const guess = Math.floor(Math.random()*10)+1;
    let finalAnswer = guess % 3;
    if(finalAnswer > 1){
        comOption = "Rock";
    }else if(finalAnswer === 1){
        comOption = "Paper";
    }else if(finalAnswer < 1){
        comOption = "Scissors";
    }
    return comOption;
}

//Single round function
function playRound(computerSelection, playerSelection){
    let ansDeclaration = "";
    var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
    var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
    var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;

    if(playerSelection == "Scissors" && computerSelection == "Paper"){
        ansDeclaration = youWin;
    }else if(playerSelection =="Paper" && computerSelection == "Rock"){
        ansDeclaration = youWin;
    }else if(playerSelection =="Rock" && computerSelection == "Scissors"){
        ansDeclaration = youWin;
    }else if(computerSelection == "Paper" && playerSelection == "Rock"){
        ansDeclaration = computerWin;
    }else if(computerSelection == "Scissors" && playerSelection == "Paper"){
        ansDeclaration = computerWin;
    }else if(computerSelection == "Rock" && playerSelection == "Scissors"){
        ansDeclaration = computerWin;
    }else{
        ansDeclaration = noBodyWin;
    }
    return ansDeclaration;
}

//Creating game function
function game(){
  var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
  var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
  var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;

   const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
   let outComeArr = []; //Outcome of the game in array
    for(let count = 0; count < rounds; count++){
        let outCome = (playRound(computerSelection, playerSelection));
        outComeArr.push(outCome);
    }
    for(let count = 0; count < outComeArr.length; count++){
        if(outComeArr[count]=== youWin){
          console.log("Player Win")
        }else if(outComeArr[count] === computerWin){
          console.log("Computer Win")
        }else if(outComeArr[count]=== noBodyWin){
          console.log("Draw Round")
        }
      }
    return outComeArr;

    //The code below helps in breaking the array "outComeArray to determine the winner"
   /*  for(let count = 0; count < outComeArr.length; count++){
        if(outComeArr[count] === youWin){
            let countWin = 0;
            countWin++
          console.log(`Player win ${countWin} times`);
        }else if(outComeArr[count]=== computerWin){
          let countWin = 0;
          countWin++;
          console.log(`Computer Win ${countWin} times`);
        }else if(outComeArr[count]=== noBodyWin){
          let countWin = 0;
          countWin++;
          console.log(`Draw Round ${countWin} times`);
        }
      } */
}

const computerSelection = computerPlay();
const playerSelection = "Scissors";
console.log(game());```

答:
The problem is that you define the moves exactly once at the end of the file. You need to redefine them upon each move. I fixed the issue and also implemented player move for you.

//Computer player argorithm
function computerPlay(){
    let comOption = ""
    const guess = Math.floor(Math.random()*10)+1;
    let finalAnswer = guess % 3;
    if(finalAnswer > 1){
        comOption = "Rock";
    }else if(finalAnswer === 1){
        comOption = "Paper";
    }else if(finalAnswer < 1){
        comOption = "Scissors";
    }
    return comOption;
}

function playerPlay() {
    let move = prompt("What do you move?");
    if (['Rock', 'Paper', 'Scrissors'].indexOf(move) === -1) move = 'Scrissors';
    return move;
}

//Single round function
function playRound(){
    computerSelection = computerPlay();
    playerSelection = playerPlay();
    let ansDeclaration = "";
    var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
    var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
    var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;

    if(playerSelection == "Scissors" && computerSelection == "Paper"){
        ansDeclaration = youWin;
    }else if(playerSelection =="Paper" && computerSelection == "Rock"){
        ansDeclaration = youWin;
    }else if(playerSelection =="Rock" && computerSelection == "Scissors"){
        ansDeclaration = youWin;
    }else if(computerSelection == "Paper" && playerSelection == "Rock"){
        ansDeclaration = computerWin;
    }else if(computerSelection == "Scissors" && playerSelection == "Paper"){
        ansDeclaration = computerWin;
    }else if(computerSelection == "Rock" && playerSelection == "Scissors"){
        ansDeclaration = computerWin;
    }else{
        ansDeclaration = noBodyWin;
    }
    return ansDeclaration;
}

//Creating game function
function game(){
  var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
  var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
  var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;

   const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
   let outComeArr = []; //Outcome of the game in array
    for(let count = 0; count < rounds; count++){
        let outCome = (playRound());
        outComeArr.push(outCome);
    }
    for(let count = 0; count < outComeArr.length; count++){
        if(outComeArr[count]=== youWin){
          console.log("Player Win")
        }else if(outComeArr[count] === computerWin){
          console.log("Computer Win")
        }else if(outComeArr[count]=== noBodyWin){
          console.log("Draw Round")
        }
      }
    return outComeArr;

    //The code below helps in breaking the array "outComeArray to determine the winner"
   /*  for(let count = 0; count < outComeArr.length; count++){
        if(outComeArr[count] === youWin){
            let countWin = 0;
            countWin++
          console.log(`Player win ${countWin} times`);
        }else if(outComeArr[count]=== computerWin){
          let countWin = 0;
          countWin++;
          console.log(`Computer Win ${countWin} times`);
        }else if(outComeArr[count]=== noBodyWin){
          let countWin = 0;
          countWin++;
          console.log(`Draw Round ${countWin} times`);
        }
      } */
}

var computerSelection;
var playerSelection;
console.log(game());```


问:
How to change max duration or refresh AWS session in Airflow 2.0
Can we increase session duration or refresh session for AWS in Apache Airflow v 2.0.2 when we use assume role like in AWS connection extra?

```<code>{
  "role_arn": "arn:aws:iam::xxx:role/airflow-connection-role",
  "region_name": "ap-southeast-1"
}
</code>```

I understand that default max duration is 1 hour and refreshable credential is supported in Airflow 2.1.

https://github.com/apache/airflow/issues/8301

https://github.com/apache/airflow/pull/16771

But I am currently using Airflow v2.0.2 in MWAA (Amazon Managed Workflows for Apache Airflow). so we can not use the option above.

https://docs.aws.amazon.com/mwaa/latest/userguide/airflow-versions.html#airflow-versions-v222

Airflow version v2.0.2

apache-airflow-providers-amazon==1.3.0

答:
In apache-airflow-providers-amazon==1.3.0, AwsBaseHook will take kwargs for assuming the role. Set extras in your connection to

```<code>{
  "role_arn": "arn:aws:iam::xxx:role/airflow-connection-role",
  "region_name": "ap-southeast-1",
  "assume_role_kwargs": "{ 'DurationSeconds': 7200 }"
}
</code>```

In the issue you reference, one comment says

After digging a little into the code, it appears that #7619 introduced the ability to set arbitrary kwargs for the assume role function call.

Here are the lines in Airflow supporting this.
https://github.com/apache/airflow/blob/0823d46a7f267f2e45195a175021825367938add/airflow/providers/amazon/aws/hooks/base_aws.py#L92
https://github.com/apache/airflow/blob/0823d46a7f267f2e45195a175021825367938add/airflow/providers/amazon/aws/hooks/base_aws.py#L172

Body:
Can we increase session duration or refresh session for AWS in Apache Airflow v 2.0.2 when we use assume role like in AWS connection extra?

{
  "role_arn": "arn:aws:iam::xxx:role/airflow-connection-role",
  "region_name": "ap-southeast-1"
}

I understand that default max duration is 1 hour and refreshable credential is supported in Airflow 2.1.

https://github.com/apache/airflow/issues/8301

https://github.com/apache/airflow/pull/16771

But I am currently using Airflow v2.0.2 in MWAA (Amazon Managed Workflows for Apache Airflow). so we can not use the option above.

https://docs.aws.amazon.com/mwaa/latest/userguide/airflow-versions.html#airflow-versions-v222

Airflow version v2.0.2

apache-airflow-providers-amazon==1.3.0

Body:
In apache-airflow-providers-amazon==1.3.0, AwsBaseHook will take kwargs for assuming the role. Set extras in your connection to

{
  "role_arn": "arn:aws:iam::xxx:role/airflow-connection-role",
  "region_name": "ap-southeast-1",
  "assume_role_kwargs": "{ 'DurationSeconds': 7200 }"
}

In the issue you reference, one comment says

After digging a little into the code, it appears that #7619 introduced the ability to set arbitrary kwargs for the assume role function call.

Here are the lines in Airflow supporting this.
https://github.com/apache/airflow/blob/0823d46a7f267f2e45195a175021825367938add/airflow/providers/amazon/aws/hooks/base_aws.py#L92
https://github.com/apache/airflow/blob/0823d46a7f267f2e45195a175021825367938add/airflow/providers/amazon/aws/hooks/base_aws.py#L172


问:
Flutter FLCharts Grid not rendering correctly
I am showing a chart in my Flutter App using fl_chart library.
I am trying to show spots with an y value of either 1, 2, or 3 and I want to draw a horizontal line on the chart on the values 1, 2 and 3.

Here is my code:

```<code>class MyChart extends StatelessWidget {
  final List<ScatterSpot> spots;

  const MyChart({
    Key? key,
    required this.spots,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScatterChart(
      ScatterChartData(
        minX: 1,
        maxX: 5,
        minY: 1,
        maxY: 3,
        scatterSpots: spots,
        gridData: FlGridData(
          show: true,
          drawHorizontalLine: true,
          drawVerticalLine: false,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: Colors.grey.shade300,
              strokeWidth: 1,
            );
          },
          horizontalInterval: 1,
        ),
        borderData: FlBorderData(
          show: false,
        ),
        titlesData: FlTitlesData(
          leftTitles: SideTitles(
            showTitles: true,
            getTitles: (value) => value.toString(),
            interval: 1,
          ),
          rightTitles: SideTitles(
            showTitles: false,
          ),
          topTitles: SideTitles(
            showTitles: false,
          ),
          bottomTitles: SideTitles(
            showTitles: false,
          ),
        ),
      ),
    );
  }
}
</code>```

So, as you can see, I have defined a minY Value of 1 and a maxY Value of 3. I am drawing a horizontal line with an Interval of 1. The Titles on the y-axis are shown correctly for 1, 2 and 3, but the line is only drawn for the value 2, not for the values 1 and 3. How can I fix this?

答:
Fixed it ^^
I just set borderData with bottom and top BorderSide</p>

Body:
I am showing a chart in my Flutter App using fl_chart library.
I am trying to show spots with an y value of either 1, 2, or 3 and I want to draw a horizontal line on the chart on the values 1, 2 and 3.

Here is my code:

class MyChart extends StatelessWidget {
  final List<ScatterSpot> spots;

  const MyChart({
    Key? key,
    required this.spots,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScatterChart(
      ScatterChartData(
        minX: 1,
        maxX: 5,
        minY: 1,
        maxY: 3,
        scatterSpots: spots,
        gridData: FlGridData(
          show: true,
          drawHorizontalLine: true,
          drawVerticalLine: false,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: Colors.grey.shade300,
              strokeWidth: 1,
            );
          },
          horizontalInterval: 1,
        ),
        borderData: FlBorderData(
          show: false,
        ),
        titlesData: FlTitlesData(
          leftTitles: SideTitles(
            showTitles: true,
            getTitles: (value) => value.toString(),
            interval: 1,
          ),
          rightTitles: SideTitles(
            showTitles: false,
          ),
          topTitles: SideTitles(
            showTitles: false,
          ),
          bottomTitles: SideTitles(
            showTitles: false,
          ),
        ),
      ),
    );
  }
}

So, as you can see, I have defined a minY Value of 1 and a maxY Value of 3. I am drawing a horizontal line with an Interval of 1. The Titles on the y-axis are shown correctly for 1, 2 and 3, but the line is only drawn for the value 2, not for the values 1 and 3. How can I fix this?


问:
reusable UI in android app
I am working on android app where I am thinking to develop reusable UI interface. How it can be developed and included in my .xml's

Here I want to develop a progress bar with my image and it will be display on some .xml's.
Please provide any code help.

I am a new in this field.

答:
you can use <Include> xml tag within your layout xml,

read this :)
http://developer.android.com/resources/articles/layout-tricks-merge.html

Title: reusable UI in android app


问:
How to check if Coupon is valid for customer before checkout in stripe api
I have a use case where I need to find that whether applied code is valid for a specific customer or not before making the payment using the Stripe. Assume there is one coupon code as "50%off" created in the Stripe which can only be used once by customers. There will be two scenario:

If customer using it for first time, they discount will be applied which is fine.

If customer using it second time, I dont want to show them discounted price at application level. And at the Stripe level, discount will not be provided as well.

I am not managing coupon code at my application level and using below code to retrieve coupon code data:

```<code>\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon);
</code>```

The above code share with me below details

```<code>[body] => {
  "id": "50%off",
  "object": "coupon",
  "amount_off": 600,
  "created": 1494427220,
  "currency": "usd",
  "duration": "once",
  "duration_in_months": null,
  "livemode": false,
  "max_redemptions": null,
  "metadata": {
  },
  "name": null,
  "percent_off": null,
  "percent_off_precise": null,
  "redeem_by": null,
  "times_redeemed": 4,
  "valid": true
}
</code>```

but I can not figure out if the customer has already used this coupon code earlier or not. I tried to pass customer id as well as below:

```<code>\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon, ['customer' => $stripe_customer_id]);
</code>```

but it shares the same response.

Can anyone please help me in this, thanks!

答:
As @koopajah mentions details on customer redemptions as see in    Stripe coupon dashboard under Active Redemptions are not available via the API.

From stripe mailing list:

This is not something that we support via the API at the moment. You would need to keep track of coupon redemptions on your end if you want to get the list and number of customers that have claimed those.
You can keep track of redemptions via webhooks.

This would apply to one-off coupons however recurring coupons are available via discount attributes for Stripe customer and subscription objects:

Subscription Discount

Customer Discount

The Discount object contains details of the coupon or promotion code in use.

Therefore should be possible to parse a Stripe customer or their subscription for any applied coupons.

If using promotion codes there are limits that can be applied which Stripe would check to stop the coupon code being used again.

Body:
I have a use case where I need to find that whether applied code is valid for a specific customer or not before making the payment using the Stripe. Assume there is one coupon code as "50%off" created in the Stripe which can only be used once by customers. There will be two scenario:

If customer using it for first time, they discount will be applied which is fine.

If customer using it second time, I dont want to show them discounted price at application level. And at the Stripe level, discount will not be provided as well.

I am not managing coupon code at my application level and using below code to retrieve coupon code data:

\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon);

The above code share with me below details

[body] => {
  "id": "50%off",
  "object": "coupon",
  "amount_off": 600,
  "created": 1494427220,
  "currency": "usd",
  "duration": "once",
  "duration_in_months": null,
  "livemode": false,
  "max_redemptions": null,
  "metadata": {
  },
  "name": null,
  "percent_off": null,
  "percent_off_precise": null,
  "redeem_by": null,
  "times_redeemed": 4,
  "valid": true
}

but I can not figure out if the customer has already used this coupon code earlier or not. I tried to pass customer id as well as below:

\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon, ['customer' => $stripe_customer_id]);

but it shares the same response.

Can anyone please help me in this, thanks!


问:
Could not resolve peer dependency between my Angular app and my custom Angular library
I have created this Angular library that I now want to use in my other Angular apps, but I seem to have trouble with my peer dependencies. I have tried fiddling around in my App's package.json, but couldn't seem to remove any of my errors.

What I have tried (in that order) :

Removing node_modules

ng update

npm update

npm audit --fix

npm i

Recreating a new test app all together

Here are the errors :

```<code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: lib-test@0.0.0
npm ERR! Found: @angular/common@13.0.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.0.0" from the root project
npm ERR!   peer @angular/common@"^13.0.0 || ^14.0.0-0" from @angular/cdk@13.2.2
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^13.2.0" from the root project
npm ERR!     peer @angular/cdk@"^13.0.0" from @my-group/angular-lib@1.1.4
npm ERR!     node_modules/@my-group/angular-lib
npm ERR!       @my-group/angular-lib@"*" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^13.1.0" from @my-group/angular-lib@1.1.4
npm ERR! node_modules/@my-group/angular-lib
npm ERR!   @my-group/angular-lib@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
</code>```

package.json (App)

```<code>{
  "name": "lib-test",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.0.0",
    "@angular/cdk": "^13.2.2",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/material": "^13.2.2",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "@cloud-republic/angular-lib": "^1.1.4",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.3",
    "@angular/cli": "~13.0.3",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.4.3"
  }
}
</code>```

package.json (Library)

```<code>{
  "name": "@my-group/angular-lib",
  "version": "1.0.6",
  "publishConfig": {
    "@my-group:registry": "https://gitlab.com/api/v4/projects/XXXXXX/packages/npm/"
  },
  "scripts": {
    "build-lib": "ng build lib-angular",
    "semantic-release": "semantic-release"
  },
  "peerDependencies": {
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.1.0",
    "@angular/core": "^13.1.0",
    "@angular/material": "^13.2.0",
    "ngx-bootstrap": "^8.0.0",
    "rxjs": "~7.4.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "devDependencies": {
    "@semantic-release/gitlab": "^7.0.4",
    "semantic-release": "^19.0.2"
  }
}
</code>```

Thanks in advance

答:
This is not the issue with peer dependencies. This is more to do with version conflict. I guess you are using npm >=7 that's why you are getting this error:-

As mentioned in the error log try the below command to fix the issue:-

```<code>npm install --legacy-peer-deps
</code>```

The above solution will solve your problem. However, the main issue is with your library.
In your library package you are saying use the below package:-

```<code> "@angular/common": "^13.1.0"
</code>```

However, in your application, you have installed the below version.
"@angular/common": "~13.0.0".
So your library package is greater than the one installed in the application.
Either install the same version in your application or downgrade the version in your library.

In this way, npm install command will work without any issue.

Body:
I have created this Angular library that I now want to use in my other Angular apps, but I seem to have trouble with my peer dependencies. I have tried fiddling around in my App's package.json, but couldn't seem to remove any of my errors.

What I have tried (in that order) :

Removing node_modules

ng update

npm update

npm audit --fix

npm i

Recreating a new test app all together

Here are the errors :

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: lib-test@0.0.0
npm ERR! Found: @angular/common@13.0.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.0.0" from the root project
npm ERR!   peer @angular/common@"^13.0.0 || ^14.0.0-0" from @angular/cdk@13.2.2
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^13.2.0" from the root project
npm ERR!     peer @angular/cdk@"^13.0.0" from @my-group/angular-lib@1.1.4
npm ERR!     node_modules/@my-group/angular-lib
npm ERR!       @my-group/angular-lib@"*" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^13.1.0" from @my-group/angular-lib@1.1.4
npm ERR! node_modules/@my-group/angular-lib
npm ERR!   @my-group/angular-lib@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

package.json (App)

{
  "name": "lib-test",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.0.0",
    "@angular/cdk": "^13.2.2",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/material": "^13.2.2",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "@cloud-republic/angular-lib": "^1.1.4",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.3",
    "@angular/cli": "~13.0.3",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.4.3"
  }
}

package.json (Library)

{
  "name": "@my-group/angular-lib",
  "version": "1.0.6",
  "publishConfig": {
    "@my-group:registry": "https://gitlab.com/api/v4/projects/XXXXXX/packages/npm/"
  },
  "scripts": {
    "build-lib": "ng build lib-angular",
    "semantic-release": "semantic-release"
  },
  "peerDependencies": {
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.1.0",
    "@angular/core": "^13.1.0",
    "@angular/material": "^13.2.0",
    "ngx-bootstrap": "^8.0.0",
    "rxjs": "~7.4.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "devDependencies": {
    "@semantic-release/gitlab": "^7.0.4",
    "semantic-release": "^19.0.2"
  }
}

Thanks in advance

Body:
This is not the issue with peer dependencies. This is more to do with version conflict. I guess you are using npm >=7 that's why you are getting this error:-

As mentioned in the error log try the below command to fix the issue:-

npm install --legacy-peer-deps

The above solution will solve your problem. However, the main issue is with your library.
In your library package you are saying use the below package:-

 "@angular/common": "^13.1.0"

However, in your application, you have installed the below version.
"@angular/common": "~13.0.0".
So your library package is greater than the one installed in the application.
Either install the same version in your application or downgrade the version in your library.

In this way, npm install command will work without any issue.


问:
Changing Plot Font with Cairo in R
I have found R's default plots to be poorly aliased. As a solution, I set Cairo as the graphics device, and now the plots look much better.

Unfortunately, using Cairo has created another issue, which is that for some reason, I am not able to apply the font that I was using when the graph was displayed in the plot window (in the left-hand diagram above, Cambria is used, but the right-hand diagram fails to apply this font).

Here is my code:

```<code>library(readxl)
library(scales)
library(ggplot2)
library(dplyr)
library('Cairo')

windowsFonts(Cam = windowsFont("Cambria"))

dataset <- read_excel('CW Data.xlsx')
colnames(dataset)[4] <- "Broadband Subs (%)"

options(scipen = 1000)

# Scatter plot FDI~GDP with regression line
CairoWin()
ggplot(dataset, aes(x=`2019 GDP ($bn)`, y=`2019 FDI ($m)`)) +
  geom_point(size=3, shape=1) +
  geom_smooth(method='lm',formula=y~x, se=FALSE, color='black') +
  scale_x_continuous(label = comma) + scale_y_continuous(label=comma) +
  theme(panel.background = element_rect(fill="peachpuff"),
        plot.background = element_rect(fill="peachpuff")) +
  theme(panel.grid.major = element_line(colour = "gray72"),
        panel.grid.minor = element_line(colour = "gray72")) +
  theme(text = element_text(family = "Cam"))

ggsave("FDI~GDP.png", device="png", type = "cairo")

</code>```

And here is a OneDrive link for the Excel data that I am using

https://1drv.ms/x/s!AvGKDeEV3LOs4gNr714Ie0KbOjhO?e=bkdPvk

答:
I suggest you have a look at the packages ragg and systemfonts. They make working with fonts extremly easy and the results are better than the output of the base options.

First, I suggest you query all available fonts using View(systemfonts::system_fonts()). You can select every font present here and use it for plotting or saving a plot.

I recreated your plot using a built in dataset as the onedrive link you shared was broken. I used the Cambria font like this.

plot <- ggplot(dataset, aes(x = mpg, y = hp)) +
  geom_point(size = 3, shape = 1) +
  geom_smooth(
    method = 'lm',
    formula = y ~ x,
    se = FALSE,
    color = 'black'
  ) +
  scale_x_continuous(label = comma) +
  scale_y_continuous(label = comma) +
  labs(x = "2019 GDP ($bn)", y = "2019 FDI ($m)") +
  theme(
    panel.background = element_rect(fill = "peachpuff"),
    plot.background = element_rect(fill = "peachpuff")
  ) +
  theme(
    panel.grid.major = element_line(colour = "gray72"),
    panel.grid.minor = element_line(colour = "gray72")
  ) +
  theme(text = element_text(family = "Cambria")) # relevant line
```
<p>I prefer saving the plot in an object and passing it explicitly to the save function.</p>
<pre class="lang-r prettyprint-override"><code>ggsave(
  "FDI~GDP.png",
  plot = plot,
  device = ragg::agg_png, # this is the relevant part
  width = 1920,
  height = 1080,
  units = "px"
)
</code>```

Here is the result:

I would say it worked flawlessly. You can also use ragg as your graphics device in RStudio to make this more consistent. Have a look here.

If you want to output the plot to a PDF, you can use showtext to register system fonts with all newly opening graphics devices. So what you need to do is:

library(showtext)
showtext_auto()
ggsave(
  "FDI~GDP.pdf",
  plot = plot,
  width = 1920,
  height = 1080,
  units = "px"
)
```

Title: Changing Plot Font with Cairo in R

Body:
I have found R's default plots to be poorly aliased. As a solution, I set Cairo as the graphics device, and now the plots look much better.

Unfortunately, using Cairo has created another issue, which is that for some reason, I am not able to apply the font that I was using when the graph was displayed in the plot window (in the left-hand diagram above, Cambria is used, but the right-hand diagram fails to apply this font).

Here is my code:

library(readxl)
library(scales)
library(ggplot2)
library(dplyr)
library('Cairo')

windowsFonts(Cam = windowsFont("Cambria"))

dataset <- read_excel('CW Data.xlsx')
colnames(dataset)[4] <- "Broadband Subs (%)"

options(scipen = 1000)

# Scatter plot FDI~GDP with regression line
CairoWin()
ggplot(dataset, aes(x=`2019 GDP ($bn)`, y=`2019 FDI ($m)`)) +
  geom_point(size=3, shape=1) +
  geom_smooth(method='lm',formula=y~x, se=FALSE, color='black') +
  scale_x_continuous(label = comma) + scale_y_continuous(label=comma) +
  theme(panel.background = element_rect(fill="peachpuff"),
        plot.background = element_rect(fill="peachpuff")) +
  theme(panel.grid.major = element_line(colour = "gray72"),
        panel.grid.minor = element_line(colour = "gray72")) +
  theme(text = element_text(family = "Cam"))

ggsave("FDI~GDP.png", device="png", type = "cairo")

And here is a OneDrive link for the Excel data that I am using

https://1drv.ms/x/s!AvGKDeEV3LOs4gNr714Ie0KbOjhO?e=bkdPvk

Body:
I suggest you have a look at the packages ragg and systemfonts. They make working with fonts extremly easy and the results are better than the output of the base options.

First, I suggest you query all available fonts using View(systemfonts::system_fonts()). You can select every font present here and use it for plotting or saving a plot.

I recreated your plot using a built in dataset as the onedrive link you shared was broken. I used the Cambria font like this.

plot <- ggplot(dataset, aes(x = mpg, y = hp)) +
  geom_point(size = 3, shape = 1) +
  geom_smooth(
    method = 'lm',
    formula = y ~ x,
    se = FALSE,
    color = 'black'
  ) +
  scale_x_continuous(label = comma) +
  scale_y_continuous(label = comma) +
  labs(x = "2019 GDP ($bn)", y = "2019 FDI ($m)") +
  theme(
    panel.background = element_rect(fill = "peachpuff"),
    plot.background = element_rect(fill = "peachpuff")
  ) +
  theme(
    panel.grid.major = element_line(colour = "gray72"),
    panel.grid.minor = element_line(colour = "gray72")
  ) +
  theme(text = element_text(family = "Cambria")) # relevant line

I prefer saving the plot in an object and passing it explicitly to the save function.

ggsave(
  "FDI~GDP.png",
  plot = plot,
  device = ragg::agg_png, # this is the relevant part
  width = 1920,
  height = 1080,
  units = "px"
)

Here is the result:

I would say it worked flawlessly. You can also use ragg as your graphics device in RStudio to make this more consistent. Have a look here.

If you want to output the plot to a PDF, you can use showtext to register system fonts with all newly opening graphics devices. So what you need to do is:

library(showtext)
showtext_auto()
ggsave(
  "FDI~GDP.pdf",
  plot = plot,
  width = 1920,
  height = 1080,
  units = "px"
)


问:
Hi, I'm new to python and I'm having a problem about loops and lists
Problem:
I'll ask the user for inputs(integers only) and put it on an empty list, and if the user entered "end" end function should be called and the sum of the list should be shown.

My problem is that whenever i enter "end" it goes straight to error "Invalid input, try again!" instead of going to the function "end". Please help me

Here is my code:

```<code>list1 = []
while True:
    try:
        number = input("Enter a number: ")
        list1.append(float(number))
        if number == "end":
            end(list1)
    except:
        print("Invalid input, try again!")
print (list1)
</code>```

答:
You can use a for loop and the iter function to get input until the user types "end". Any input other than end will enter the loop's body.

```<code>list1 = []

for x in iter(lambda: input("Enter a number"), "end"):
    try:
        number = float(x)
    except ValueError:
        print(f"Invalid number {x}, try again!")
        continue

    list1.append(number)

end(list1)
print(sum(list1))
</code>```

Body:
Problem:
I'll ask the user for inputs(integers only) and put it on an empty list, and if the user entered "end" end function should be called and the sum of the list should be shown.

My problem is that whenever i enter "end" it goes straight to error "Invalid input, try again!" instead of going to the function "end". Please help me

Here is my code:

list1 = []
while True:
    try:
        number = input("Enter a number: ")
        list1.append(float(number))
        if number == "end":
            end(list1)
    except:
        print("Invalid input, try again!")
print (list1)

Body:
You can use a for loop and the iter function to get input until the user types "end". Any input other than end will enter the loop's body.

list1 = []

for x in iter(lambda: input("Enter a number"), "end"):
    try:
        number = float(x)
    except ValueError:
        print(f"Invalid number {x}, try again!")
        continue

    list1.append(number)

end(list1)
print(sum(list1))


问:
fread(): read of 8192 bytes failed with errno=21 Is a directory in
I was editing WordPress and the error message below came out.

" Notice: fread(): read of 8192 bytes failed with errno=21 Is a directory in /home/c7006248/public_html/ondine199918.com/wp-includes/functions.php on line 6574"

The code is as follows.

```<code>*/
function get_file_data( $file, $default_headers, $context = '' ) {
    // We don't need to write to the file, so just open for reading.
    $fp = fopen( $file, 'r' );

    if ( $fp ) {
        // Pull only the first 8 KB of the file in.
      $file_data = fread( $fp, 8 * KB_IN_BYTES );

        // PHP will close file handle, but we are good citizens.
        fclose( $fp );
    } else {
        $file_data = '';
    }
</code>```

Does anyone have any idea of a potential fix for that issue?

I would be more than grateful if you help me with a fix. Thanks in advance! :)

Hitomi

For the additional information.
The error location I'm getting is
" Notice: fread(): read of 8192 bytes failed with errno=21 Is a directory in /home/c7006248/public_html/ondine199918.com/wp-includes/functions.php on line 6574 "

And the line 6574 is

```<code>$file_data = fread( $fp, 8 * KB_IN_BYTES );
</code>```

from the extracted code above.

Sorry for the incomplete information.

答:
I guess you are trying to open a directory instead of file
So you need to check if it's a file or not before trying to read the first 8kb</p>
```<code>function get_file_data( $file, $default_headers, $context = '' ) {
    if (!is_file($path) === false) {
        return;
    }
</code>```

Body:
I was editing WordPress and the error message below came out.

" Notice: fread(): read of 8192 bytes failed with errno=21 Is a directory in /home/c7006248/public_html/ondine199918.com/wp-includes/functions.php on line 6574"

The code is as follows.

*/
function get_file_data( $file, $default_headers, $context = '' ) {
    // We don't need to write to the file, so just open for reading.
    $fp = fopen( $file, 'r' );

    if ( $fp ) {
        // Pull only the first 8 KB of the file in.
      $file_data = fread( $fp, 8 * KB_IN_BYTES );

        // PHP will close file handle, but we are good citizens.
        fclose( $fp );
    } else {
        $file_data = '';
    }

Does anyone have any idea of a potential fix for that issue?

I would be more than grateful if you help me with a fix. Thanks in advance! :)

Hitomi

For the additional information.
The error location I'm getting is
" Notice: fread(): read of 8192 bytes failed with errno=21 Is a directory in /home/c7006248/public_html/ondine199918.com/wp-includes/functions.php on line 6574 "

And the line 6574 is

$file_data = fread( $fp, 8 * KB_IN_BYTES );

from the extracted code above.

Sorry for the incomplete information.

Body:
I guess you are trying to open a directory instead of file
So you need to check if it's a file or not before trying to read the first 8kb

function get_file_data( $file, $default_headers, $context = '' ) {
    if (!is_file($path) === false) {
        return;
    }


问:
Remove shadow from top and bottom of ListView in android?
I have created a custom listView with the row as follows:

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"  android:id="@+id/lay1"
  android:layout_height="wrap_content" android:background="#ffffff">

  <TextView android:layout_width="fill_parent" android:textColor="#000000" android:id="@+id/text"
  android:layout_height="wrap_content" android:layout_toRightOf="@+id/check"
  android:textSize="15dip" android:paddingBottom="5dip" android:paddingRight="10dip" android:paddingLeft="10dip"></TextView>

  <Button android:id="@+id/check"  android:layout_centerVertical="true"
          android:background="@drawable/uncheck" android:layout_width="wrap_content"
          android:layout_height="wrap_content" android:visibility="gone"></Button>

  <EditText android:layout_width="fill_parent" android:textColor="#000000" android:id="@+id/edit"
  android:layout_height="wrap_content"  android:background="@null" android:layout_below="@+id/text"
  android:textSize="15dip" android:paddingTop="5dip" android:paddingRight="10dip" android:paddingLeft="10dip"
  android:layout_toRightOf="@+id/check" android:paddingBottom="5dip" ></EditText>

</RelativeLayout>
</code>```

And listview code used in my main xml is:

```<code><ListView android:layout_width="450dip" android:background="#FFFFFF" android:layout_height="340dip"
  android:layout_marginLeft="9dip" android:layout_marginTop="10dip"  android:id="@+id/mainlist1"
  android:divider="@drawable/grayline"
    android:cacheColorHint="#00000000" ></ListView>
</code>```

And adapter used is as follows:

```<code>public class Adapter extends BaseAdapter {

        ArrayList<Row> row;
        private Context context;

        public Adapter(Context context, ArrayList<SongRow> songrow) {

            this.context = context;
            this.row = row;

        }

        public int getCount() {

            return row.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            long sub_id = row.get(position).getSub_id();
            String sub_title = row.get(position).getSub_title();
            String sub_text = row.get(position).getSub_text();

            if (convertView == null) {
                LayoutInflater inflat = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflat.inflate(R.layout.mainrow, null);

            } else {
                LayoutInflater inflat1 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflat1.inflate(R.layout.mainrow, null);
                            }
            final TextView name = (TextView) convertView.findViewById(R.id.text);
            final EditText et = (EditText) convertView.findViewById(R.id.edit);
            name.setText(sub_title);
            et.setText(sub_text);
            et.setFilters(new InputFilter[] { new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                        int end, Spanned dst, int dstart, int dend) {
                       InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                       mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                       et.setCursorVisible(false);
                       return dst.subSequence(dstart, dend);

                }
            } });
            et.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    if (hasFocus) {
                         InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                         mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                         et.setCursorVisible(false);
                    }
                }

            });
            et.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                     InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                     mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                     et.setCursorVisible(false);

                }
            });
            return convertView;
        }
    }
</code>```

And adapter called in main activity through code as follows:

```<code>Adapter s = new Adapter(MainActivity.this, row);
            mainlist.setAdapter(s);
            mainlist.setSelection(length-1);
</code>```

My coding is working fine. My problem is that while showing listview which is scrollable is droping shadow at top and bottom of listview and I don't want to show it. How can I remove that shadow?

Thanks in advance

答:
I'm assuming you're talking about the fading edges. To disable them:

```<code>android:fadingEdge="none"
</code>```

or

```<code>listView.setVerticalFadingEdgeEnabled(false);
</code>```

UPDATE

As Pim Reijersen pointed out in the comments, android:fadingEdge is deprecated and will be ignored as of API level 14. Please use:

```<code>android:fadingEdgeLength="0dp"
</code>```

Body:
I have created a custom listView with the row as follows:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"  android:id="@+id/lay1"
  android:layout_height="wrap_content" android:background="#ffffff">

  <TextView android:layout_width="fill_parent" android:textColor="#000000" android:id="@+id/text"
  android:layout_height="wrap_content" android:layout_toRightOf="@+id/check"
  android:textSize="15dip" android:paddingBottom="5dip" android:paddingRight="10dip" android:paddingLeft="10dip"></TextView>

  <Button android:id="@+id/check"  android:layout_centerVertical="true"
          android:background="@drawable/uncheck" android:layout_width="wrap_content"
          android:layout_height="wrap_content" android:visibility="gone"></Button>

  <EditText android:layout_width="fill_parent" android:textColor="#000000" android:id="@+id/edit"
  android:layout_height="wrap_content"  android:background="@null" android:layout_below="@+id/text"
  android:textSize="15dip" android:paddingTop="5dip" android:paddingRight="10dip" android:paddingLeft="10dip"
  android:layout_toRightOf="@+id/check" android:paddingBottom="5dip" ></EditText>

</RelativeLayout>

And listview code used in my main xml is:

<ListView android:layout_width="450dip" android:background="#FFFFFF" android:layout_height="340dip"
  android:layout_marginLeft="9dip" android:layout_marginTop="10dip"  android:id="@+id/mainlist1"
  android:divider="@drawable/grayline"
    android:cacheColorHint="#00000000" ></ListView>

And adapter used is as follows:

public class Adapter extends BaseAdapter {

        ArrayList<Row> row;
        private Context context;

        public Adapter(Context context, ArrayList<SongRow> songrow) {

            this.context = context;
            this.row = row;

        }

        public int getCount() {

            return row.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            long sub_id = row.get(position).getSub_id();
            String sub_title = row.get(position).getSub_title();
            String sub_text = row.get(position).getSub_text();

            if (convertView == null) {
                LayoutInflater inflat = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflat.inflate(R.layout.mainrow, null);

            } else {
                LayoutInflater inflat1 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflat1.inflate(R.layout.mainrow, null);
                            }
            final TextView name = (TextView) convertView.findViewById(R.id.text);
            final EditText et = (EditText) convertView.findViewById(R.id.edit);
            name.setText(sub_title);
            et.setText(sub_text);
            et.setFilters(new InputFilter[] { new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                        int end, Spanned dst, int dstart, int dend) {
                       InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                       mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                       et.setCursorVisible(false);
                       return dst.subSequence(dstart, dend);

                }
            } });
            et.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    if (hasFocus) {
                         InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                         mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                         et.setCursorVisible(false);
                    }
                }

            });
            et.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                     InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                     mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
                     et.setCursorVisible(false);

                }
            });
            return convertView;
        }
    }

And adapter called in main activity through code as follows:

Adapter s = new Adapter(MainActivity.this, row);
            mainlist.setAdapter(s);
            mainlist.setSelection(length-1);

My coding is working fine. My problem is that while showing listview which is scrollable is droping shadow at top and bottom of listview and I don't want to show it. How can I remove that shadow?

Thanks in advance

Body:
I'm assuming you're talking about the fading edges. To disable them:

android:fadingEdge="none"

or

listView.setVerticalFadingEdgeEnabled(false);

UPDATE

As Pim Reijersen pointed out in the comments, android:fadingEdge is deprecated and will be ignored as of API level 14. Please use:

android:fadingEdgeLength="0dp"


问:
How to split octets of ip addressses from csv
I'm trying to take an IP log list (in CSV format) remove all duplicate addresses, then split it up into separate octets and store it in a list. I'm going to eventually add in checking for subnet duplicates (same ip in the same subnet), but I'm stuck here. there is extra information in the CSV file, but its been a long time since I've coded, so I'm mostly just focused on the IPs right now. I don't care if I lose the rest of the info.

I originally tried to try set character blocks (ex. take character 0-2 as the first octect, 4-6 as second, etc.) but that obviously doesn't work if octets are less than 3 digits. Then I tried using re.split to split up the octets, but it was saying that it wouldn't accept strings (for some reason). I then tried what I currently have in my code, but with blah=int(fin.append(lst[each].re.split(r".",int))), but that wouldn't work because of the periods in the intiger.

```<code>import pandas
import re

#set column names and input the data
colnames = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven']
data = pandas.read_csv(r'C:\Users\xxx\Desktop\Projects\Find the IPs\tiny version.csv', names=colnames)

#tell which column to read from then put in list called "lst"
ip = data.five.tolist()
lst = list(dict.fromkeys(ip))

#create final list
fin = []
#for every entry in lst, split it up at the periods, then add it to fin
for each in lst:
    print("I got here")
    blah = lst([each]).re.split(r".",int)

    fin.append(blah)
</code>```

right now, I'm hoping for a list with each entry containing all four octets as integers.

答:
Old thread, but posting for anyone else who runs into this problem in the future. This is not the most elegant solution by far, but here is one that worked for me:</p>
```<code>import pandas
import re

#start of OP's code

data = pandas.read_csv(r'INSERT_FILEPATH_HERE') #reads in your csv file, please put the file path for your CSV where it says INSERT_FILEPATH_HERE, keep quotes
ip_addresses = data["IP"].tolist() #converts the column containing the IP into a list please replace IP with your IP column name
ip_list = list(dict.fromkeys(ip_addresses)) #converts list into dict to remove duplicates, converts it back

#end of OP's code

#creating lists to be used for ip octet columns

octet_1 = list()
octet_2 = list()
octet_3 = list()
octet_4 = list()

#for loop to iterate through each IP in the column
for ip_entry in ip_list:
    split_ip = [int(octet) for octet in ip_entry.split('.')] #solution shared by earlier comment, splits up IP into octets by splitting string at periods
    octet_1.append(split_ip[0]) #appending octets into appropriate columns
    octet_2.append(split_ip[1])
    octet_3.append(split_ip[2])
    octet_4.append(split_ip[3])

#this solves the problem of generating octet lists, If you wish to append these lists as columns, please see the code below:

#adding columns to new,edited csv
data["Octet 1"] = octet_1
data["Octet 2"] = octet_2
data["Octet 3"] = octet_3
data["Octet 4"] = octet_4

data.to_csv('INSERT_FILEPATH_TO_NEW_CSV') #creates csv with new columns. If you want to update the original file, please insert the filepath to the original file.
</code>```

Body:
I'm trying to take an IP log list (in CSV format) remove all duplicate addresses, then split it up into separate octets and store it in a list. I'm going to eventually add in checking for subnet duplicates (same ip in the same subnet), but I'm stuck here. there is extra information in the CSV file, but its been a long time since I've coded, so I'm mostly just focused on the IPs right now. I don't care if I lose the rest of the info.

I originally tried to try set character blocks (ex. take character 0-2 as the first octect, 4-6 as second, etc.) but that obviously doesn't work if octets are less than 3 digits. Then I tried using re.split to split up the octets, but it was saying that it wouldn't accept strings (for some reason). I then tried what I currently have in my code, but with blah=int(fin.append(lst[each].re.split(r".",int))), but that wouldn't work because of the periods in the intiger.

import pandas
import re

#set column names and input the data
colnames = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven']
data = pandas.read_csv(r'C:\Users\xxx\Desktop\Projects\Find the IPs\tiny version.csv', names=colnames)

#tell which column to read from then put in list called "lst"
ip = data.five.tolist()
lst = list(dict.fromkeys(ip))

#create final list
fin = []
#for every entry in lst, split it up at the periods, then add it to fin
for each in lst:
    print("I got here")
    blah = lst([each]).re.split(r".",int)

    fin.append(blah)

right now, I'm hoping for a list with each entry containing all four octets as integers.

Body:
Old thread, but posting for anyone else who runs into this problem in the future. This is not the most elegant solution by far, but here is one that worked for me:

import pandas
import re

#start of OP's code

data = pandas.read_csv(r'INSERT_FILEPATH_HERE') #reads in your csv file, please put the file path for your CSV where it says INSERT_FILEPATH_HERE, keep quotes
ip_addresses = data["IP"].tolist() #converts the column containing the IP into a list please replace IP with your IP column name
ip_list = list(dict.fromkeys(ip_addresses)) #converts list into dict to remove duplicates, converts it back

#end of OP's code

#creating lists to be used for ip octet columns

octet_1 = list()
octet_2 = list()
octet_3 = list()
octet_4 = list()

#for loop to iterate through each IP in the column
for ip_entry in ip_list:
    split_ip = [int(octet) for octet in ip_entry.split('.')] #solution shared by earlier comment, splits up IP into octets by splitting string at periods
    octet_1.append(split_ip[0]) #appending octets into appropriate columns
    octet_2.append(split_ip[1])
    octet_3.append(split_ip[2])
    octet_4.append(split_ip[3])

#this solves the problem of generating octet lists, If you wish to append these lists as columns, please see the code below:

#adding columns to new,edited csv
data["Octet 1"] = octet_1
data["Octet 2"] = octet_2
data["Octet 3"] = octet_3
data["Octet 4"] = octet_4

data.to_csv('INSERT_FILEPATH_TO_NEW_CSV') #creates csv with new columns. If you want to update the original file, please insert the filepath to the original file.


问:
java.lang.ClassNotFoundException on working app
I have created and published my first Android app. It's very simple. It works fine on simulator and some phones, but I am getting this error:

```<code>java.lang.RuntimeException: Unable to instantiate application cz.teamnovak.droid.Novak ESC Track guide: java.lang.ClassNotFoundException: cz.teamnovak.droid.Novak ESC Track guide in loader dalvik.system.PathClassLoader[/data/app/cz.teamnovak.droid-1.apk]
    at android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:649)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4232)
    at android.app.ActivityThread.access$3000(ActivityThread.java:125)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2071)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4627)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: cz.teamnovak.droid.Novak ESC Track guide in loader dalvik.system.PathClassLoader[/data/app/cz.teamnovak.droid-1.apk]
    at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
    at android.app.Instrumentation.newApplication(Instrumentation.java:942)
    at android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:644)
    ... 11 more
</code>```

Any idea what can cause this?

答:
Make sure that you have package

```<code>com.aaraf.demowithdoc //Your Package Name
</code>```

com.aaraf.demowithdoc [YOUR PACKAGE NAME]
is there in your class where this java.lang.classnotfoundexception is occuring

Body:
I have created and published my first Android app. It's very simple. It works fine on simulator and some phones, but I am getting this error:

java.lang.RuntimeException: Unable to instantiate application cz.teamnovak.droid.Novak ESC Track guide: java.lang.ClassNotFoundException: cz.teamnovak.droid.Novak ESC Track guide in loader dalvik.system.PathClassLoader[/data/app/cz.teamnovak.droid-1.apk]
    at android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:649)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4232)
    at android.app.ActivityThread.access$3000(ActivityThread.java:125)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2071)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4627)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: cz.teamnovak.droid.Novak ESC Track guide in loader dalvik.system.PathClassLoader[/data/app/cz.teamnovak.droid-1.apk]
    at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
    at android.app.Instrumentation.newApplication(Instrumentation.java:942)
    at android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:644)
    ... 11 more

Any idea what can cause this?

Body:
Make sure that you have package

com.aaraf.demowithdoc //Your Package Name

com.aaraf.demowithdoc [YOUR PACKAGE NAME]
is there in your class where this java.lang.classnotfoundexception is occuring


问:
C++ equivalent of Java StringUtils.indexOfDifference
For C++20, is there a library equivalent of Java's StringUtils.indexOfDifference()?

What is the efficient way of comparing two large strings and determining where they differ?

答:
You can use std::mismatch from <algorithm>

Returns the first mismatching pair of elements from two ranges

For example

```<code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
    auto diff = std::mismatch(lhs.begin(), lhs.end(), rhs.begin());
    return std::distance(lhs.begin(), diff.first);
}

int main() {
    std::cout << IndexOfDifference("foobar", "foocar");
}
</code>```

Will output

```<code>3
</code>```

Body:
You can use std::mismatch from <algorithm>

Returns the first mismatching pair of elements from two ranges

For example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
    auto diff = std::mismatch(lhs.begin(), lhs.end(), rhs.begin());
    return std::distance(lhs.begin(), diff.first);
}

int main() {
    std::cout << IndexOfDifference("foobar", "foocar");
}

Will output

3


问:
Redux state is not rendering properly
Screen A --> Flatlist --> Card A --> QtyButton Component

Screen B --> Flatlist --> Card B --> QtyButton Component

Screen C --> Flatlist --> Card C --> QtyButton Component

Im passing array in flatlist and product object in card and then quantity from that object in QtyButton Component. Quantity is displayed in between minus and plus button.

And from QtyButton Component I'm updating qty of product object based on id in redux. And in Redux the state updates. I'm not retrieving quantity directly in QtyButton. But instead getting the quantity this way.

Flatlist --> card --> QtyButton

But I'm facing some weird problems.

Screen A --> Flatlist --> Card A --> QtyButton Component Qty doesn't update on run time. If it does its very slow and sluggish render

Screen B --> Flatlist --> Card A --> QtyButton Component Same Screen A scenario

Screen C --> Flatlist --> Card A --> QtyButton Component If products are more than two then quantity starts to render slowly.

And here Reducer

```<code>Cart = [];

export default (state = Cart, action) => {
  const {type, payload, error} = action;
  switch (type) {

   case ACTION_TYPES.CART:
    let cartItems = [...state.Cart];

    // Check if product already exist in cart

    if (cartItems.some(x => x.product_id ===
        payload.item.product_id)) {
         cartItems.map(item =>
          item.product_id === payload.item.product_id
        ? {...item, quantity: item.quantity + 1}
        : item,
    );
    } else {
     cartItems.push({...payload.item, quantity: 1});
    }
   return {...state, Cart: cartItems};

   case ACTION_TYPES.REMOVE_FROM_CART:
    return {
     ...state,
     Cart: state.Cart.filter(x => x.product_id !== payload.id),
   };

   case ACTION_TYPES.INCREMENT:
    return {
    ...state,
    Cart: state.Cart.map(x =>
      x.product_id === payload.id
        ? {...x, quantity: x.quantity + payload.quantity}
        : x,
    ),
  };

  case ACTION_TYPES.DECREMENT:
     return {
    ...state,
    Cart: state.Cart.map(x =>
            x.product_id === payload.id
              ? {...x, quantity: x.quantity - payload.quantity}
              : x,
          ),
  };

 default:
  return state;
</code>```

}

答:
So I figured out the problem.

I was updating the quantity in the nested component(QtyButton) and nowhere in Screen A and Screen B, I was not setting the updated quantity from redux store to API array.

Because initially, I was displaying the quantity from the Api array in Flat list and all the way down to the QtyButton component.

Call the api
get data from API in state

After setting the state I needed to set the updated quantity from redux store to API state.
This will check the quantity in redux, and whatever the quantity stored in redux will be set to API array.

```<code>let cart = props.cart;

  for (let i = 0; i < apiState.length; i++) {
    for (let j = 0; j < cart.length; j++) {
      if (apiState[i].id === cart [j].id) {
        apiState[i].quantity = cart [j].quantity;
      }
    }
  }

And then in render function

Flatlist
 data={apiState}
 //remaining flatlist stuff
/>
</code>```

And Now I have the updated quantity.

Title: Redux state is not rendering properly

Body:
Screen A --> Flatlist --> Card A --> QtyButton Component

Screen B --> Flatlist --> Card B --> QtyButton Component

Screen C --> Flatlist --> Card C --> QtyButton Component

Im passing array in flatlist and product object in card and then quantity from that object in QtyButton Component. Quantity is displayed in between minus and plus button.

And from QtyButton Component I'm updating qty of product object based on id in redux. And in Redux the state updates. I'm not retrieving quantity directly in QtyButton. But instead getting the quantity this way.

Flatlist --> card --> QtyButton

But I'm facing some weird problems.

Screen A --> Flatlist --> Card A --> QtyButton Component Qty doesn't update on run time. If it does its very slow and sluggish render

Screen B --> Flatlist --> Card A --> QtyButton Component Same Screen A scenario

Screen C --> Flatlist --> Card A --> QtyButton Component If products are more than two then quantity starts to render slowly.

And here Reducer

Cart = [];

export default (state = Cart, action) => {
  const {type, payload, error} = action;
  switch (type) {

   case ACTION_TYPES.CART:
    let cartItems = [...state.Cart];

    // Check if product already exist in cart

    if (cartItems.some(x => x.product_id ===
        payload.item.product_id)) {
         cartItems.map(item =>
          item.product_id === payload.item.product_id
        ? {...item, quantity: item.quantity + 1}
        : item,
    );
    } else {
     cartItems.push({...payload.item, quantity: 1});
    }
   return {...state, Cart: cartItems};

   case ACTION_TYPES.REMOVE_FROM_CART:
    return {
     ...state,
     Cart: state.Cart.filter(x => x.product_id !== payload.id),
   };

   case ACTION_TYPES.INCREMENT:
    return {
    ...state,
    Cart: state.Cart.map(x =>
      x.product_id === payload.id
        ? {...x, quantity: x.quantity + payload.quantity}
        : x,
    ),
  };

  case ACTION_TYPES.DECREMENT:
     return {
    ...state,
    Cart: state.Cart.map(x =>
            x.product_id === payload.id
              ? {...x, quantity: x.quantity - payload.quantity}
              : x,
          ),
  };

 default:
  return state;

}

Body:
So I figured out the problem.

I was updating the quantity in the nested component(QtyButton) and nowhere in Screen A and Screen B, I was not setting the updated quantity from redux store to API array.

Because initially, I was displaying the quantity from the Api array in Flat list and all the way down to the QtyButton component.

Call the api
get data from API in state

After setting the state I needed to set the updated quantity from redux store to API state.
This will check the quantity in redux, and whatever the quantity stored in redux will be set to API array.

let cart = props.cart;

  for (let i = 0; i < apiState.length; i++) {
    for (let j = 0; j < cart.length; j++) {
      if (apiState[i].id === cart [j].id) {
        apiState[i].quantity = cart [j].quantity;
      }
    }
  }

And then in render function

Flatlist
 data={apiState}
 //remaining flatlist stuff
/>

And Now I have the updated quantity.


问:
using dark mode in react-select
I think the best way to change color is using the theme props or in the doc look something like this :

```<code>
import { flavourOptions } from '../data';
import Select from 'react-select';

export default () => (
  <Select
    defaultValue={flavourOptions[2]}
    label="Single select"
    options={flavourOptions}
    theme={theme => ({
      ...theme,
      borderRadius: 0,
      colors: {
        ...theme.colors,
        primary25: 'hotpink',
        primary: 'black',
      },
    })}
  />
);
</code>```

but, I am not stuck at figuring out how to "connect" it dark mode togggle..

答:
Here's an example with tailwind css making use of the className and classNamePrefix arguments:

React usage:

```<code><Select
   className="my-react-select-container"
   classNamePrefix="my-react-select"
...
</code>```

Tailwind CSS index.css

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  /* .my-react-select-container {
  } */
  .my-react-select-container .my-react-select__control {
    @apply bg-white dark:bg-neutral-700 border-2 border-neutral-300 dark:border-neutral-700 hover:border-neutral-400 dark:hover:border-neutral-500;
  }

  .my-react-select-container .my-react-select__control--is-focused {
    @apply border-neutral-500 hover:border-neutral-500 dark:border-neutral-400 dark:hover:border-neutral-400 shadow-none;
  }

  .my-react-select-container .my-react-select__menu {
    @apply bg-neutral-100 dark:bg-neutral-700 border-2 border-neutral-300 dark:border-neutral-600;
  }

  .my-react-select-container .my-react-select__option {
    @apply text-neutral-600 dark:text-neutral-200 bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-700 dark:hover:bg-neutral-800;
  }
  /* .my-react-select-container .my-react-select__option--is-focused {
    @apply bg-neutral-200 dark:bg-neutral-800;
  } */

  .my-react-select-container .my-react-select__indicator-separator {
    @apply bg-neutral-400;
  }

  .my-react-select-container .my-react-select__input-container,
  .my-react-select-container .my-react-select__placeholder,
  .my-react-select-container .my-react-select__single-value {
    @apply text-neutral-600 dark:text-neutral-200;
  }
}
</code>```

Result:

Title: using dark mode in react-select

Body:
I think the best way to change color is using the theme props or in the doc look something like this :

import { flavourOptions } from '../data';
import Select from 'react-select';

export default () => (
  <Select
    defaultValue={flavourOptions[2]}
    label="Single select"
    options={flavourOptions}
    theme={theme => ({
      ...theme,
      borderRadius: 0,
      colors: {
        ...theme.colors,
        primary25: 'hotpink',
        primary: 'black',
      },
    })}
  />
);

but, I am not stuck at figuring out how to "connect" it dark mode togggle..

Body:
Here's an example with tailwind css making use of the className and classNamePrefix arguments:

React usage:

<Select
   className="my-react-select-container"
   classNamePrefix="my-react-select"
...

Tailwind CSS index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  /* .my-react-select-container {
  } */
  .my-react-select-container .my-react-select__control {
    @apply bg-white dark:bg-neutral-700 border-2 border-neutral-300 dark:border-neutral-700 hover:border-neutral-400 dark:hover:border-neutral-500;
  }

  .my-react-select-container .my-react-select__control--is-focused {
    @apply border-neutral-500 hover:border-neutral-500 dark:border-neutral-400 dark:hover:border-neutral-400 shadow-none;
  }

  .my-react-select-container .my-react-select__menu {
    @apply bg-neutral-100 dark:bg-neutral-700 border-2 border-neutral-300 dark:border-neutral-600;
  }

  .my-react-select-container .my-react-select__option {
    @apply text-neutral-600 dark:text-neutral-200 bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-700 dark:hover:bg-neutral-800;
  }
  /* .my-react-select-container .my-react-select__option--is-focused {
    @apply bg-neutral-200 dark:bg-neutral-800;
  } */

  .my-react-select-container .my-react-select__indicator-separator {
    @apply bg-neutral-400;
  }

  .my-react-select-container .my-react-select__input-container,
  .my-react-select-container .my-react-select__placeholder,
  .my-react-select-container .my-react-select__single-value {
    @apply text-neutral-600 dark:text-neutral-200;
  }
}

Result:


问:
How to convert extended ascii characters from char to wstring in c++
I read a file using ifstream's read method into a char* memory block. I call my GetChar method on each char in the memory block to write to a wstring. I am trying to write the unicode characters to the screen (at least I think they are unicode, please correct me if I am wrong - oh no it looks like I was wrong its extended ascii). Unfortunately the only way I've got it to work is to hard code the unicode characters in a switch statement, but I'd rather it work for any character, not just the ones I've encountered and added by hard coding them.

Here is what I'm currently using:

```<code>std::wstring GetChar(char o)
{
  switch (o)
  {
  case 0x0D:
    return L"♪";
  case 0x0A:
    return L"◙";
  case -38:
    return L"┌";
  case -60:
    return L"─";
  case -77:
    return L"│";
  case -65:
    return L"┐";
  case -61:
    return L"├";
  case -76:
    return L"┤";
  case -2:
    return L"■";
  }

  std::wstring tmp_string(1, o);
  return tmp_string;
}
</code>```

Any idea how to convert -38 to L"┌" in a generic way?
[Edit] I discovered that my mappings are actually extended ascii!, see the webpage https://www.sciencebuddies.org/science-fair-projects/references/ascii-table

I think what I will try is to create a txt file with extended ascii mapping based on this webpage: https://theasciicode.com.ar/ Is there is a simpler programmatic way (eg with setlocale)?

答:
I got a solution I am happy with. I wrote a key file containing bytes 00 to FF, then I viewed the file with eXtreme (no longer exists) which could show the extended ascii values which I then copied into Notepad++ and saved as unicode values file. I then had mapping for 0x00 to 0xFF to their nice looking extended ascii characters (saved as unicode) all displaying well as wstrings (no hard coded values). I may want to support regular unicode too some day as another mode, but extended ascii is good enough for the files I'm currently working with.
Here is an archived version of eXtreme if anyone needs it: http://members.iinet.net.au/~bertdb/ryan/eXtreme/</p>

Body:
I read a file using ifstream's read method into a char* memory block. I call my GetChar method on each char in the memory block to write to a wstring. I am trying to write the unicode characters to the screen (at least I think they are unicode, please correct me if I am wrong - oh no it looks like I was wrong its extended ascii). Unfortunately the only way I've got it to work is to hard code the unicode characters in a switch statement, but I'd rather it work for any character, not just the ones I've encountered and added by hard coding them.

Here is what I'm currently using:

std::wstring GetChar(char o)
{
  switch (o)
  {
  case 0x0D:
    return L"♪";
  case 0x0A:
    return L"◙";
  case -38:
    return L"┌";
  case -60:
    return L"─";
  case -77:
    return L"│";
  case -65:
    return L"┐";
  case -61:
    return L"├";
  case -76:
    return L"┤";
  case -2:
    return L"■";
  }

  std::wstring tmp_string(1, o);
  return tmp_string;
}

Any idea how to convert -38 to L"┌" in a generic way?
[Edit] I discovered that my mappings are actually extended ascii!, see the webpage https://www.sciencebuddies.org/science-fair-projects/references/ascii-table

I think what I will try is to create a txt file with extended ascii mapping based on this webpage: https://theasciicode.com.ar/ Is there is a simpler programmatic way (eg with setlocale)?


问:
GCC and TC giving different outputs?
Consider the following code:

```<code>#include <stdio.h>

int main()
{
        printf("%d", 300 * 300 / 300);
        return 0;
}
</code>```

This code when run on a standard GCC compiler gives the result as 300 but when i run it using Turbo C, the result is 81. Why is it so?
I understand that TC uses 2 bytes for storing integers, and the result 300 * 300 would clearly exceed this limit, but before it is printed it is again divided with a 300 right?
And additionally what is computed first? 300 / 300 or 300 * 300?)
What is the reason for this behavior??

答:
Before it prints it divides it by 300, but the overflow already happend, since integer literals are evaluated as ints, when you divide, you already with the overflowed int result.

Since * and / has the same priority, the * is evaluated first (since evaluation is left to right)

You can, however, do either 300 * (300/300) or 300L * 300 / 300

Title: GCC and TC giving different outputs?

Body:
Consider the following code:

#include <stdio.h>

int main()
{
        printf("%d", 300 * 300 / 300);
        return 0;
}

This code when run on a standard GCC compiler gives the result as 300 but when i run it using Turbo C, the result is 81. Why is it so?
I understand that TC uses 2 bytes for storing integers, and the result 300 * 300 would clearly exceed this limit, but before it is printed it is again divided with a 300 right?
And additionally what is computed first? 300 / 300 or 300 * 300?)
What is the reason for this behavior??


问:
Google Sheets: Determining if a time falls within a two specified times
I'm trying to find a way to determine if a time falls between two specific times - with two  different scenarios to flag. So far, I'm coming up empty (and frustrated!)

Column B has date/times such as:

```<code>February 9, 2022 09:55AM
February 9, 2022 01:15PM
February 9, 2022 09:39PM
</code>```

Flag 1: Time is between 4AM and Noon

Flag 2: Time is between 8PM and 4AM -- does this need to be broken down into two separate conditions given that it spreads over midnight?

Resulting Output in Column C:

```<code>FLAG 1
[Blank Cell - No Flag]
FLAG 2
</code>```

Appreciate any ideas - thanks to the community, as always.

CTO

答:
You can use a much simpler formula that involves a bit of math:

=arrayformula(if(A1:A="","",iferror(choose(1+mod(3+int((mod(A1:A,1)-4/24)*24/8),3),"FLAG 1","","FLAG 2"))))

We are extracting the time from the date (mod), offsetting the result by -4 hours (-4/24)and int-dividing the result by 8 hours (*24/8, which is same as /(24/8)) to get the index 0,1 or 2

Body:
I'm trying to find a way to determine if a time falls between two specific times - with two  different scenarios to flag. So far, I'm coming up empty (and frustrated!)

Column B has date/times such as:

February 9, 2022 09:55AM
February 9, 2022 01:15PM
February 9, 2022 09:39PM

Flag 1: Time is between 4AM and Noon

Flag 2: Time is between 8PM and 4AM -- does this need to be broken down into two separate conditions given that it spreads over midnight?

Resulting Output in Column C:

FLAG 1
[Blank Cell - No Flag]
FLAG 2

Appreciate any ideas - thanks to the community, as always.

CTO


问:
Properties page not displaying in Visual Studio 2008
I'm using Visual Studio 2008 Team Development Edition and my Project properties page will not display.  I right-clicked the project name and selected "Properties" and no page displayed as it normally would.  Also, when I double-click the Settings.settings the normal Settings GUI does not display.   I only see the XML in the Settings.settings file.  Please Help.  Thanks.</p>

答: Check if you opened the solution or it may be pointing to your local folder from file explorer.</p>

OwnerDisplayName: Billkamm

ContentLicense: CC BY-SA 2.5


问:
Matching a number against a comma-separated sequence of ranges
I'm writing a bash script which takes a number, and also a comma-separated sequence of values and strings, e.g.: 3,15,4-7,19-20. I want to check whether the number is contained in the set corresponding to the sequence. For simplicity, assume no comma-separated elements intersect, and that the elements are sorted in ascending order.

Is there a simple way to do this in bash other than the brute-force naive way? Some shell utility which does something like that for me, maybe something related to lpr which already knows how to process page range sequences etc.

Body:
Pure bash:

check() {
  IFS=, a=($2)
  for b in "${a[@]}"; do
    IFS=- c=($b); c+=(${c[0]})
    (( $1 >= c[0] && $1 <= c[1] )) && break
  done
}

$ check 6 '3,15,4-7,19-20' && echo "yes" || echo "no"
yes
$ check 42 '3,15,4-7,19-20' && echo "yes" || echo "no"
no


问:
How to Enable SSI (Server Side Includes) on Tomcat 7 at Ubuntu?
How can I enable SSI on Tomcat 7?.

I follow the directions however it doesn't work. I changed my main file's extension from html to shtml (not imported one) and unquoted that lines at web.xml:

```<code><servlet>

    <servlet-name>ssi</servlet-name>

    <servlet-class>

      org.apache.catalina.ssi.SSIServlet

    </servlet-class>

    <init-param>

      <param-name>buffered</param-name>

      <param-value>1</param-value>

    </init-param>

    <init-param>

      <param-name>debug</param-name>

      <param-value>0</param-value>

    </init-param>

    <init-param>

      <param-name>expires</param-name>

      <param-value>666</param-value>

    </init-param>

    <init-param>

      <param-name>isVirtualWebappRelative</param-name>

      <param-value>0</param-value>

    </init-param>

    <load-on-startup>4</load-on-startup>

</servlet>
</code>```

What do do more, where is the wrong?

答:
http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Introduction_to_SSL

You have to add the SSL configuration to the tomcat config this is detailed above and should help you out any questions after reading this let me know

Body:
How can I enable SSI on Tomcat 7?.

I follow the directions however it doesn't work. I changed my main file's extension from html to shtml (not imported one) and unquoted that lines at web.xml:

<servlet>

    <servlet-name>ssi</servlet-name>

    <servlet-class>

      org.apache.catalina.ssi.SSIServlet

    </servlet-class>

    <init-param>

      <param-name>buffered</param-name>

      <param-value>1</param-value>

    </init-param>

    <init-param>

      <param-name>debug</param-name>

      <param-value>0</param-value>

    </init-param>

    <init-param>

      <param-name>expires</param-name>

      <param-value>666</param-value>

    </init-param>

    <init-param>

      <param-name>isVirtualWebappRelative</param-name>

      <param-value>0</param-value>

    </init-param>

    <load-on-startup>4</load-on-startup>

</servlet>

What do do more, where is the wrong?


问:
Tables in Data Modeler's Browser, not showing in Oracle Connection
I created an entity-relationship diagram (logical model) and engineered it to a relational model.
The tables were generated. Now I need to use them from the connection XE as you see in the picture.

The tables I made can only be seen on the data modeler design view in the "Browser", how do I get them on the connection "XE" to generate data dictionary, etc?

答:
There are three possibilities:

you just need to expand the tables item in the tree to see your tables

You are looking in the wrong schema/user - go down to Other Users, and find the schema those tables belong to

The tables do not exist in the current database

If #3 is the issue, you would need to create them, possibly using the information in your Data Model - that is, you can generate the DDL/SQL scripts for those tables.

Then taking those scripts, run them while connected to the appropriate database/schema.

Disclaimer: I'm an Oracle employee and the product manager for these tools.


问:
using address sanitizer with OpenCV
I'm trying to use Google's Address Sanitizer with a CUDA project, more precisely with OpenCV cuda functions. However I got an 'out of memory' error on the first cuda call.

```<code>OpenCV Error: Gpu API call (out of memory) in getDevice, file opencv-2.4.11/src/opencv-2.4.11/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp, line 664
terminate called after throwing an instance of 'cv::Exception'
  what():  opencv-2.4.11/src/opencv-2.4.11/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp:664: error: (-217) out of memory in function getDevice
</code>```

It can be reproduced with

```<code>#include <opencv2/gpu/gpu.hpp>
int main()
{
  cv::gpu::printCudaDeviceInfo(cv::gpu::getDevice());
  return 0;
}
</code>```

compiled with

```<code>clang++ -fsanitize=address -lstdc++ -lopencv_gpu -lopencv_core -o sanitizer sanitizer.cpp && LD_LIBRARY_PATH=/usr/local/lib ./sanitizer
</code>```

I've got the same result with gcc.
I've also tried blacklisting cuda functions without result.

Now using cuda without opencv:

```<code>#include <cuda_runtime.h>
int main()
{
  int count = -1;
  cudaGetDevice(&count);
  cout << "Device count: " << count << endl;
  return 0;
}
clang++ -O1 -g -fsanitize=address -fsanitize-blacklist=asan.blacklist -stdlib=libstdc++ -lstdc++ -I/opt/cuda/include -L/opt/cuda/lib64 -lcudart  -o sanitizer sanitizer.cpp && ./sanitizer
</code>```

The sanitizer stops on a memory leak:

```<code>=================================================================
==25344==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 136 byte(s) in 1 object(s) allocated from:
    #0 0x4bc4a2  (/home/pluc/work/tests/sanitizer+0x4bc4a2)
    #1 0x7f71f0fa69ba  (<unknown module>)

SUMMARY: AddressSanitizer: 136 byte(s) leaked in 1 allocation(s).
</code>```

My question is how can I use the address sanitizer to sanitize my software without getting stuck with this? How can I at least properly blacklist all cuda related calls?

I didn't find anything relevant on a famous web search engine. It's like people don't use cuda or asan or both. Do guys just have a build with cuda completly disabled?

I'm guessing asan is having a hard time with cuda memory management but I'm looking for a way to use this tool for the rest of my codebase at least.

答:
For people looking here: The solution I have found (based on the related github issue mentioned by @BenC) is to run export ASAN_OPTIONS=protect_shadow_gap=0.

I have not succeeded in finding a way to change the behavior when compiling yet.

Title: using address sanitizer with OpenCV

Body:
I'm trying to use Google's Address Sanitizer with a CUDA project, more precisely with OpenCV cuda functions. However I got an 'out of memory' error on the first cuda call.

OpenCV Error: Gpu API call (out of memory) in getDevice, file opencv-2.4.11/src/opencv-2.4.11/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp, line 664
terminate called after throwing an instance of 'cv::Exception'
  what():  opencv-2.4.11/src/opencv-2.4.11/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp:664: error: (-217) out of memory in function getDevice

It can be reproduced with

#include <opencv2/gpu/gpu.hpp>
int main()
{
  cv::gpu::printCudaDeviceInfo(cv::gpu::getDevice());
  return 0;
}

compiled with

clang++ -fsanitize=address -lstdc++ -lopencv_gpu -lopencv_core -o sanitizer sanitizer.cpp && LD_LIBRARY_PATH=/usr/local/lib ./sanitizer

I've got the same result with gcc.
I've also tried blacklisting cuda functions without result.

Now using cuda without opencv:

#include <cuda_runtime.h>
int main()
{
  int count = -1;
  cudaGetDevice(&count);
  cout << "Device count: " << count << endl;
  return 0;
}
clang++ -O1 -g -fsanitize=address -fsanitize-blacklist=asan.blacklist -stdlib=libstdc++ -lstdc++ -I/opt/cuda/include -L/opt/cuda/lib64 -lcudart  -o sanitizer sanitizer.cpp && ./sanitizer

The sanitizer stops on a memory leak:

=================================================================
==25344==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 136 byte(s) in 1 object(s) allocated from:
    #0 0x4bc4a2  (/home/pluc/work/tests/sanitizer+0x4bc4a2)
    #1 0x7f71f0fa69ba  (<unknown module>)

SUMMARY: AddressSanitizer: 136 byte(s) leaked in 1 allocation(s).

My question is how can I use the address sanitizer to sanitize my software without getting stuck with this? How can I at least properly blacklist all cuda related calls?

I didn't find anything relevant on a famous web search engine. It's like people don't use cuda or asan or both. Do guys just have a build with cuda completly disabled?

I'm guessing asan is having a hard time with cuda memory management but I'm looking for a way to use this tool for the rest of my codebase at least.


问:
wpf combine events
How can I combine two events and create a new event ?

e.g : if the mouse leave the control and focus on another control (so that focus is lost) then fire event custom_event.

I'm new at WPF and I've got not complete the zen of wpf. If there is another way to do that, let me know.

答:
It's possible in XAML with MultiDataTriggers, see this article from Josh Smith:</p>

```<code><!-- This MultiDataTrigger affects losers of the race. -->
<MultiDataTrigger>
  <MultiDataTrigger.Conditions>
    <Condition Binding="{Binding IsFinished}" Value="True" />
    <Condition Binding="{Binding IsWinner}" Value="False" />
  </MultiDataTrigger.Conditions>

  <!-- Apply the "finished the race" brush to
       the horse's progress indicator. -->
  <Setter TargetName="progressIndicator"
          Property="Fill" Value="{StaticResource FinishedBrush}" />

  <!-- Fade the race pit in and out if the horse lost the race. -->
  <MultiDataTrigger.EnterActions>
    <!-- Fade away the RaceHorse's Border element when it loses a race. -->
  </MultiDataTrigger.EnterActions>

  <MultiDataTrigger.ExitActions>
    <!-- Fade in the RaceHorse's Border element when a new race starts. -->
  </MultiDataTrigger.ExitActions>
</MultiDataTrigger>
</code>```

Title: wpf combine events

Body:
It's possible in XAML with MultiDataTriggers, see this article from Josh Smith:

<!-- This MultiDataTrigger affects losers of the race. -->
<MultiDataTrigger>
  <MultiDataTrigger.Conditions>
    <Condition Binding="{Binding IsFinished}" Value="True" />
    <Condition Binding="{Binding IsWinner}" Value="False" />
  </MultiDataTrigger.Conditions>

  <!-- Apply the "finished the race" brush to
       the horse's progress indicator. -->
  <Setter TargetName="progressIndicator"
          Property="Fill" Value="{StaticResource FinishedBrush}" />

  <!-- Fade the race pit in and out if the horse lost the race. -->
  <MultiDataTrigger.EnterActions>
    <!-- Fade away the RaceHorse's Border element when it loses a race. -->
  </MultiDataTrigger.EnterActions>

  <MultiDataTrigger.ExitActions>
    <!-- Fade in the RaceHorse's Border element when a new race starts. -->
  </MultiDataTrigger.ExitActions>
</MultiDataTrigger>


问:
How to handle 404 in webclient retrive
I am new to spring webclient and i have written a generic method which can be used to consume rest apis in my application:

```<code>public <T> List<T> get(URI url, Class<T> responseType) {
        return  WebClient.builder().build().get().uri(url)
                   .header("Authorization", "Basic " + principal)
                   .retrieve().bodyToFlux(responseType).collectList().block();
}
</code>```

i wanted to return and empty list if consumed rest-api return 404.

can someone suggest how to achieve that?

答:
As of Spring WebFlux 5.3 they've added the exchange methods which allows you to easily handle different responses, like this:</p>
```<code>public <T> List<T> get(URI url, Class<T> responseType) {
    return WebClient.builder().build().get().uri(url)
        .header("Authorization", "Basic " + principal)
        .exchangeToFlux(clientResponse -> {
            if (clientResponse.statusCode().equals(HttpStatus.NOT_FOUND)) {
                return Flux.empty();
            } else {
                return clientResponse.bodyToFlux(responseType);
            }
        })
        .collectList()
        .block();
}
</code>```

Title: How to handle 404 in webclient retrive

Body:
I am new to spring webclient and i have written a generic method which can be used to consume rest apis in my application:

public <T> List<T> get(URI url, Class<T> responseType) {
        return  WebClient.builder().build().get().uri(url)
                   .header("Authorization", "Basic " + principal)
                   .retrieve().bodyToFlux(responseType).collectList().block();
}

i wanted to return and empty list if consumed rest-api return 404.

can someone suggest how to achieve that?

Body:
As of Spring WebFlux 5.3 they've added the exchange methods which allows you to easily handle different responses, like this:

public <T> List<T> get(URI url, Class<T> responseType) {
    return WebClient.builder().build().get().uri(url)
        .header("Authorization", "Basic " + principal)
        .exchangeToFlux(clientResponse -> {
            if (clientResponse.statusCode().equals(HttpStatus.NOT_FOUND)) {
                return Flux.empty();
            } else {
                return clientResponse.bodyToFlux(responseType);
            }
        })
        .collectList()
        .block();
}