问:
Condition on attribute in sass
I want to apply style depending on condition on the typa attribute provided by html like this:

```<code><img src="pf_brise_lame_bdef_034.jpg?itok=3vKP-E25" width="325" height="183" alt="Présentation de l'Association" title="Présentation de l'Association" loading="lazy" typeof="Image" class="lazy-hidden">
</code>```

So I don't know how to write the condition into my scss file, here is the starting point:

```<code>   $attribut:[typeof="Image"];
                @if $attribut == [typeof="Image"]{
                background: transparent;
                  a{
                      display: none;
                  }
                  }
                  @else {
                  background: $gris-anthracite;
                    a{
                        display: initial;
                    }
                  }
</code>```

what could be the right syntax to achieve this ? into a li element.

Thanks

答:
Using SASS for this is unneeded. You can use vanilla CSS with attribute selectors. See the following example - images by default have no border, however here with the typeof attribute being assigned 'image' they will receive the defined border.

img {
  border: none;
}
img[typeof='image'] {
  border: 2px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src='https://via.placeholder.com/50' typeof='image' />
<img src='https://via.placeholder.com/50' typeof='' /></code>```

But if you're set on SASS...

What you're trying to do in your example is simply setting a variable and then running a comparison on it.  However you need to wrap that variable in quotes for that to work.

```<code>$attribut: '[typeof="Image"]';
@if $attribut == '[typeof="Image"]' {
...
}
</code>```

However this is just comparing the defined variable 'attribut' and in no way is defining a rule for images containing that attribute.  To do that I stand by my first suggestion, just using CSS.

Title: Condition on attribute in sass

Body:
I want to apply style depending on condition on the typa attribute provided by html like this:

So I don't know how to write the condition into my scss file, here is the starting point:

   $attribut:[typeof="Image"];
                @if $attribut == [typeof="Image"]{
                background: transparent;
                  a{
                      display: none;
                  }
                  }
                  @else {
                  background: $gris-anthracite;
                    a{
                        display: initial;
                    }
                  }

what could be the right syntax to achieve this ? into a li element.

Thanks

Body:
Using SASS for this is unneeded. You can use vanilla CSS with attribute selectors. See the following example - images by default have no border, however here with the typeof attribute being assigned 'image' they will receive the defined border.

img {
  border: none;
}
img[typeof='image'] {
  border: 2px solid red;
}

<img src='https://via.placeholder.com/50' typeof='image' />
<img src='https://via.placeholder.com/50' typeof='' />

But if you're set on SASS...

What you're trying to do in your example is simply setting a variable and then running a comparison on it.  However you need to wrap that variable in quotes for that to work.

$attribut: '[typeof="Image"]';
@if $attribut == '[typeof="Image"]' {
...
}

However this is just comparing the defined variable 'attribut' and in no way is defining a rule for images containing that attribute.  To do that I stand by my first suggestion, just using CSS.


来源: stackexchange

问:
How do I set a random image from an array invisible when a button is pressed
I am building an app that when a button is pressed a random image in a gridLayout disappears revealing something behind it.

There are 28 images in the gridLayout.

I have my images in an array and inside the buttons onClick i want to get a random image from that array and set its visibility to invisible.

I appreciate if anyone can help.

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    ImageView image1;

    ImageView image2;

    ImageView image3;

    ImageView image4;

    ImageView image5;

    ImageView image6;

    ImageView image7;

    ImageView image8;

    ImageView image9;

    ImageView image10;

    ImageView image11;

    ImageView image12;

    ImageView image13;

    ImageView image14;

    ImageView image15;

    ImageView image16;

    ImageView image17;

    ImageView image18;

    ImageView image19;

    ImageView image20;

    ImageView image21;

    ImageView image22;

    ImageView image23;

    ImageView image24;

    ImageView image25;

    ImageView image26;

    ImageView image27;

    ImageView image28;

    Button revealButton;

    Random rand;

    Integer[] imagesArray = {

            R.id.imageView1,
            R.id.imageView1,
            R.id.imageView2,
            R.id.imageView3,
            R.id.imageView4,
            R.id.imageView5,
            R.id.imageView6,
            R.id.imageView7,
            R.id.imageView8,
            R.id.imageView9,
            R.id.imageView10,
            R.id.imageView11,
            R.id.imageView12,
            R.id.imageView13,
            R.id.imageView14,
            R.id.imageView15,
            R.id.imageView16,
            R.id.imageView17,
            R.id.imageView18,
            R.id.imageView19,
            R.id.imageView20,
            R.id.imageView21,
            R.id.imageView22,
            R.id.imageView23,
            R.id.imageView24,
            R.id.imageView25,
            R.id.imageView26,
            R.id.imageView27,
            R.id.imageView28

    };

    public void reveal(View view) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image1 = findViewById(R.id.imageView1);
        image2 = findViewById(R.id.imageView2);
        image3 = findViewById(R.id.imageView3);
        image4 = findViewById(R.id.imageView4);
        image5 = findViewById(R.id.imageView5);
        image6 = findViewById(R.id.imageView6);
        image7 = findViewById(R.id.imageView7);
        image8 = findViewById(R.id.imageView8);
        image9 = findViewById(R.id.imageView9);
        image10 = findViewById(R.id.imageView10);
        image11 = findViewById(R.id.imageView11);
        image12 = findViewById(R.id.imageView12);
        image13 = findViewById(R.id.imageView13);
        image14 = findViewById(R.id.imageView14);
        image15 = findViewById(R.id.imageView15);
        image16 = findViewById(R.id.imageView16);
        image17 = findViewById(R.id.imageView17);
        image18 = findViewById(R.id.imageView18);
        image19 = findViewById(R.id.imageView19);
        image20 = findViewById(R.id.imageView20);
        image21 = findViewById(R.id.imageView21);
        image22 = findViewById(R.id.imageView22);
        image23 = findViewById(R.id.imageView23);
        image24 = findViewById(R.id.imageView24);
        image25 = findViewById(R.id.imageView25);
        image26 = findViewById(R.id.imageView26);
        image27 = findViewById(R.id.imageView27);
        image28 = findViewById(R.id.imageView28);

        revealButton = findViewById(R.id.reveal);

        rand = new Random();

    }

}
</code>```

答:
you can use nextInt method like the code below

```<code>public class MainActivity extends AppCompatActivity {

Button revealButton;

Random rand;

Integer[] imagesArray = {

        R.id.imageView1,
        R.id.imageView1,
        R.id.imageView2,
        R.id.imageView3,
        R.id.imageView4,
        R.id.imageView5,
        R.id.imageView6,
        R.id.imageView7,
        R.id.imageView8,
        R.id.imageView9,
        R.id.imageView10,
        R.id.imageView11,
        R.id.imageView12,
        R.id.imageView13,
        R.id.imageView14,
        R.id.imageView15,
        R.id.imageView16,
        R.id.imageView17,
        R.id.imageView18,
        R.id.imageView19,
        R.id.imageView20,
        R.id.imageView21,
        R.id.imageView22,
        R.id.imageView23,
        R.id.imageView24,
        R.id.imageView25,
        R.id.imageView26,
        R.id.imageView27,
        R.id.imageView28

};

public void reveal(View view) {

int randomImagePosition= new Random().nextInt(imagesArray.length);
int imageId = imagesArray[randomImagePosition] ;
findViewById(imageId).setVisibility(View.INVISIBLE)

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    revealButton = findViewById(R.id.reveal);

}
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
I am building an app that when a button is pressed a random image in a gridLayout disappears revealing something behind it.

There are 28 images in the gridLayout.

I have my images in an array and inside the buttons onClick i want to get a random image from that array and set its visibility to invisible.

I appreciate if anyone can help.

Here is my code:

public class MainActivity extends AppCompatActivity {

    ImageView image1;

    ImageView image2;

    ImageView image3;

    ImageView image4;

    ImageView image5;

    ImageView image6;

    ImageView image7;

    ImageView image8;

    ImageView image9;

    ImageView image10;

    ImageView image11;

    ImageView image12;

    ImageView image13;

    ImageView image14;

    ImageView image15;

    ImageView image16;

    ImageView image17;

    ImageView image18;

    ImageView image19;

    ImageView image20;

    ImageView image21;

    ImageView image22;

    ImageView image23;

    ImageView image24;

    ImageView image25;

    ImageView image26;

    ImageView image27;

    ImageView image28;

    Button revealButton;

    Random rand;

    Integer[] imagesArray = {

            R.id.imageView1,
            R.id.imageView1,
            R.id.imageView2,
            R.id.imageView3,
            R.id.imageView4,
            R.id.imageView5,
            R.id.imageView6,
            R.id.imageView7,
            R.id.imageView8,
            R.id.imageView9,
            R.id.imageView10,
            R.id.imageView11,
            R.id.imageView12,
            R.id.imageView13,
            R.id.imageView14,
            R.id.imageView15,
            R.id.imageView16,
            R.id.imageView17,
            R.id.imageView18,
            R.id.imageView19,
            R.id.imageView20,
            R.id.imageView21,
            R.id.imageView22,
            R.id.imageView23,
            R.id.imageView24,
            R.id.imageView25,
            R.id.imageView26,
            R.id.imageView27,
            R.id.imageView28

    };

    public void reveal(View view) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image1 = findViewById(R.id.imageView1);
        image2 = findViewById(R.id.imageView2);
        image3 = findViewById(R.id.imageView3);
        image4 = findViewById(R.id.imageView4);
        image5 = findViewById(R.id.imageView5);
        image6 = findViewById(R.id.imageView6);
        image7 = findViewById(R.id.imageView7);
        image8 = findViewById(R.id.imageView8);
        image9 = findViewById(R.id.imageView9);
        image10 = findViewById(R.id.imageView10);
        image11 = findViewById(R.id.imageView11);
        image12 = findViewById(R.id.imageView12);
        image13 = findViewById(R.id.imageView13);
        image14 = findViewById(R.id.imageView14);
        image15 = findViewById(R.id.imageView15);
        image16 = findViewById(R.id.imageView16);
        image17 = findViewById(R.id.imageView17);
        image18 = findViewById(R.id.imageView18);
        image19 = findViewById(R.id.imageView19);
        image20 = findViewById(R.id.imageView20);
        image21 = findViewById(R.id.imageView21);
        image22 = findViewById(R.id.imageView22);
        image23 = findViewById(R.id.imageView23);
        image24 = findViewById(R.id.imageView24);
        image25 = findViewById(R.id.imageView25);
        image26 = findViewById(R.id.imageView26);
        image27 = findViewById(R.id.imageView27);
        image28 = findViewById(R.id.imageView28);

        revealButton = findViewById(R.id.reveal);

        rand = new Random();

    }

}

Body:
you can use nextInt method like the code below

public class MainActivity extends AppCompatActivity {

Button revealButton;

Random rand;

Integer[] imagesArray = {

        R.id.imageView1,
        R.id.imageView1,
        R.id.imageView2,
        R.id.imageView3,
        R.id.imageView4,
        R.id.imageView5,
        R.id.imageView6,
        R.id.imageView7,
        R.id.imageView8,
        R.id.imageView9,
        R.id.imageView10,
        R.id.imageView11,
        R.id.imageView12,
        R.id.imageView13,
        R.id.imageView14,
        R.id.imageView15,
        R.id.imageView16,
        R.id.imageView17,
        R.id.imageView18,
        R.id.imageView19,
        R.id.imageView20,
        R.id.imageView21,
        R.id.imageView22,
        R.id.imageView23,
        R.id.imageView24,
        R.id.imageView25,
        R.id.imageView26,
        R.id.imageView27,
        R.id.imageView28

};

public void reveal(View view) {

int randomImagePosition= new Random().nextInt(imagesArray.length);
int imageId = imagesArray[randomImagePosition] ;
findViewById(imageId).setVisibility(View.INVISIBLE)

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    revealButton = findViewById(R.id.reveal);

}

}


问:
SQL query to display both the sum of column and value of column in a date range
I'm trying to do a SQL query to give the cash transactions by day with a sum of the total cash balance grouped by Company and Department.  I can get each query to work separately, but can't figure out how to nest the summary query as a subquery successfully. Below are the two queries that work.  I thought I could do a temporary table, but have not been able to get that to work either (get error message that token "temporary" , "private temporary" invalid with Oracle DB) and most of the information I've researched says you can do the same thing with a subquery.  I'd prefer to do a subquery anyway if it's possible.

#sum of YTD cash balance

Select Company, department, sum(amount) as Balance

From GL_Table

Where Company in ('A','B','C') and FY = 21 and account = 'cash' and date between 1/1/2021 and 1/31/2021

Group By Company, department

#transactions by day

Select Company, Department, date, Amount

From GL_Table

Where Company in ('A','B','C') and FY = 21 and and account = 'cash' and date = 1/1/2021-1/31/2021

Group By Company, department, date

答:
You can GROUP BY date and the correct date that corresponds to the most recent transaction via sub query.

```<code>SELECT Company, department, sum(amount) FROM (
    SELECT MAX(date), Company, department, amount FROM GL_TABLE GROUP BY date
) WHERE
   Company in ('A','B','C') and FY = 21 and account = 'cash' and date between
   1/1/2021 and 1/31/2021
   GROUP BY
   Company, department, date
</code>```

also check out: SQL: Select most recent date for each category

Body:
You can GROUP BY date and the correct date that corresponds to the most recent transaction via sub query.

SELECT Company, department, sum(amount) FROM (
    SELECT MAX(date), Company, department, amount FROM GL_TABLE GROUP BY date
) WHERE
   Company in ('A','B','C') and FY = 21 and account = 'cash' and date between
   1/1/2021 and 1/31/2021
   GROUP BY
   Company, department, date

also check out: SQL: Select most recent date for each category


问:
What is the difference between gradlew build and gradlew assembleRelease
I want to build apk from command line with the help of gradle. Which command should I use to build apks for only release flavours?</p>

答:
If you want to upload the APK file to your firebase app distribtion, use the below command:

```<code># generates debug signed APK
./gradlew assembleDebug
</code>```

It will generate an APK file, but it couldn't be released to Play Store, as it signed with your debug signature. GPC won't allow it to be uploaded.

If you want to upload the APK or AAB file to Google Play Console, use one of the commands below:

```<code># generates release signed APK
./gradlew assembleRelease
# generates release signed AAB
./gradlew bundleRelease
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to upload the APK file to your firebase app distribtion, use the below command:

# generates debug signed APK
./gradlew assembleDebug

It will generate an APK file, but it couldn't be released to Play Store, as it signed with your debug signature. GPC won't allow it to be uploaded.

If you want to upload the APK or AAB file to Google Play Console, use one of the commands below:

# generates release signed APK
./gradlew assembleRelease
# generates release signed AAB
./gradlew bundleRelease


问:
Saving data from a switch used as a menu in C#?
I'm trying to make a bank program that is going to have the switch as a menu that i can call the different cases from. But the problem is that i don't know how i can call one of the cases in the switch, and then let the user enter data that will be saved the variable.

The thing is if i let the user put like 100 into his account, the balance says it still is 0.

It's probably because I've set the balance (saldo) to zero and when the menu loops it gets that value? But I don't know how to do since I have to give the saldo a value to start with.

Here is my code:

```<code>class Konto
{
    static void Main(string[] args)
    {
        Console.WriteLine("Välkommen till Andreas bank!");
        bool avsluta = true;

        while (avsluta)
        {
            Console.WriteLine("Ange det alternativ för vad du vill göra: ");
            Console.WriteLine("[I]nsättning");
            Console.WriteLine("[U]ttag");
            Console.WriteLine("[S]aldo");
            Console.WriteLine("[R]äntebetalning");
            Console.WriteLine("[A]vsluta");

            char menuAlternativ = Convert.ToChar(Console.ReadLine());
            Console.WriteLine(GetMenu(menuAlternativ));

            Console.ReadLine();
        }
    }

    static string GetMenu(char menu)
    {
        string menuChoice;
        double insättning;
        double saldo = 0;
        double uttag;

        switch (menu)
        {
            case 'I':
                Console.WriteLine("Ange hur mycket du vill sätta in: ");
                insättning = Convert.ToInt32(Console.ReadLine());
                saldo = insättning + saldo;
                menuChoice = "Du har satt in " + insättning + " Kronor.";
                break;
            case 'U':
                Console.WriteLine("Ange hur mycket du vill ta ut: ");
                uttag = Convert.ToInt32(Console.ReadLine());
                menuChoice = "Du har tagit ut " + uttag + " Kronor.";
                break;
            case 'S':
                menuChoice = "Ditt saldo är: " + saldo + " Kronor.";
                break;

            case 'R':
                double Summa = 0, ränta, sparandeÅr, totaltSparande;
                Console.Write("Skriv in ditt årliga sparande: ");
                totaltSparande = Convert.ToDouble(Console.ReadLine());
                Console.Write("Ange räntan per år: ");
                ränta = Convert.ToDouble(Console.ReadLine()) / 100;
                Console.Write("Ange antal år du vill spara: ");
                sparandeÅr = Convert.ToDouble(Console.ReadLine());

                //Om antal år är mindre än antal år användaren vill spara, öka med 1 år tills användarens antal år är nådd.
                for (int år = 1; år < sparandeÅr + 1; år++)
                {
                    Summa = totaltSparande * Math.Pow((1 + ränta / sparandeÅr), (sparandeÅr * år));
                    Console.Write("Ditt totala sparande för år {0} " + " är: {1:F0}. \n", år, Summa);
                }
                menuChoice = "Så här kommer din ränta att se ut.";
                break;

            case 'A':
                menuChoice = "Du har valt att avsluta programmet.";
                break;

            default:
                menuChoice = "Invalid menu character";
                break;

        }

        return menuChoice;
    }
}
</code>```

答:
I have placed saldo above class definition. This will make it global which means it can be access from anywhere in the program. You placed saldo inside GetMenu() which was private for the method setting it to zero every time it was called.

Learn More

```<code>namespace Bank
{
    class Konto
    {
        double saldo = 0; //<--------Place saldo here (GLOBALLY!) to persist value between method calls.

        static void Main(string[] args)
        {
            Console.WriteLine("Välkommen till Andreas bank!");
            bool avsluta = true;

            while (avsluta)
            {
                Console.WriteLine("Ange det alternativ för vad du vill göra: ");
                Console.WriteLine("[I]nsättning");
                Console.WriteLine("[U]ttag");
                Console.WriteLine("[S]aldo");
                Console.WriteLine("[R]äntebetalning");
                Console.WriteLine("[A]vsluta");

                char menuAlternativ = Convert.ToChar(Console.ReadLine());
                Console.WriteLine(GetMenu(menuAlternativ));

                Console.ReadLine();
            }
        }

        static string GetMenu(char menu)
        {
            string menuChoice;
            double insättning;
            double uttag;

            switch (menu)
            {
                case 'I':
                    Console.WriteLine("Ange hur mycket du vill sätta in: ");
                    insättning = Convert.ToInt32(Console.ReadLine());
                    saldo = insättning + saldo;
                    menuChoice = "Du har satt in " + insättning + " Kronor.";
                break;
                case 'U':
                    Console.WriteLine("Ange hur mycket du vill ta ut: ");
                    uttag = Convert.ToInt32(Console.ReadLine());
                    menuChoice = "Du har tagit ut " + uttag + " Kronor.";
                break;
                case 'S':
                    menuChoice = "Ditt saldo är: " + saldo + " Kronor.";
                break;
                case 'R':
                    double Summa = 0, ränta, sparandeÅr, totaltSparande;
                    Console.Write("Skriv in ditt årliga sparande: ");
                    totaltSparande = Convert.ToDouble(Console.ReadLine());
                    Console.Write("Ange räntan per år: ");
                    ränta = Convert.ToDouble(Console.ReadLine()) / 100;
                    Console.Write("Ange antal år du vill spara: ");
                    sparandeÅr = Convert.ToDouble(Console.ReadLine());

                    //Om antal år är mindre än antal år användaren vill spara, öka med 1 år tills användarens antal år är nådd.
                    for (int år = 1; år < sparandeÅr + 1; år++)
                    {
                        Summa = totaltSparande * Math.Pow((1 + ränta / sparandeÅr), (sparandeÅr * år));
                        Console.Write("Ditt totala sparande för år {0} " + " är: {1:F0}. \n", år, Summa);
                    }
                    menuChoice = "Så här kommer din ränta att se ut.";
                break;
                case 'A':
                    menuChoice = "Du har valt att avsluta programmet.";
                break;
                default:
                    menuChoice = "Invalid menu character";
                break;
            }
            return menuChoice;
        }
    }
}
</code>```

Body:
I'm trying to make a bank program that is going to have the switch as a menu that i can call the different cases from. But the problem is that i don't know how i can call one of the cases in the switch, and then let the user enter data that will be saved the variable.

The thing is if i let the user put like 100 into his account, the balance says it still is 0.

It's probably because I've set the balance (saldo) to zero and when the menu loops it gets that value? But I don't know how to do since I have to give the saldo a value to start with.

Here is my code:

class Konto
{
    static void Main(string[] args)
    {
        Console.WriteLine("Välkommen till Andreas bank!");
        bool avsluta = true;

        while (avsluta)
        {
            Console.WriteLine("Ange det alternativ för vad du vill göra: ");
            Console.WriteLine("[I]nsättning");
            Console.WriteLine("[U]ttag");
            Console.WriteLine("[S]aldo");
            Console.WriteLine("[R]äntebetalning");
            Console.WriteLine("[A]vsluta");

            char menuAlternativ = Convert.ToChar(Console.ReadLine());
            Console.WriteLine(GetMenu(menuAlternativ));

            Console.ReadLine();
        }
    }

    static string GetMenu(char menu)
    {
        string menuChoice;
        double insättning;
        double saldo = 0;
        double uttag;

        switch (menu)
        {
            case 'I':
                Console.WriteLine("Ange hur mycket du vill sätta in: ");
                insättning = Convert.ToInt32(Console.ReadLine());
                saldo = insättning + saldo;
                menuChoice = "Du har satt in " + insättning + " Kronor.";
                break;
            case 'U':
                Console.WriteLine("Ange hur mycket du vill ta ut: ");
                uttag = Convert.ToInt32(Console.ReadLine());
                menuChoice = "Du har tagit ut " + uttag + " Kronor.";
                break;
            case 'S':
                menuChoice = "Ditt saldo är: " + saldo + " Kronor.";
                break;

            case 'R':
                double Summa = 0, ränta, sparandeÅr, totaltSparande;
                Console.Write("Skriv in ditt årliga sparande: ");
                totaltSparande = Convert.ToDouble(Console.ReadLine());
                Console.Write("Ange räntan per år: ");
                ränta = Convert.ToDouble(Console.ReadLine()) / 100;
                Console.Write("Ange antal år du vill spara: ");
                sparandeÅr = Convert.ToDouble(Console.ReadLine());

                //Om antal år är mindre än antal år användaren vill spara, öka med 1 år tills användarens antal år är nådd.
                for (int år = 1; år < sparandeÅr + 1; år++)
                {
                    Summa = totaltSparande * Math.Pow((1 + ränta / sparandeÅr), (sparandeÅr * år));
                    Console.Write("Ditt totala sparande för år {0} " + " är: {1:F0}. \n", år, Summa);
                }
                menuChoice = "Så här kommer din ränta att se ut.";
                break;

            case 'A':
                menuChoice = "Du har valt att avsluta programmet.";
                break;

            default:
                menuChoice = "Invalid menu character";
                break;

        }

        return menuChoice;
    }
}

Body:
I have placed saldo above class definition. This will make it global which means it can be access from anywhere in the program. You placed saldo inside GetMenu() which was private for the method setting it to zero every time it was called.

Learn More

namespace Bank
{
    class Konto
    {
        double saldo = 0; //<--------Place saldo here (GLOBALLY!) to persist value between method calls.

        static void Main(string[] args)
        {
            Console.WriteLine("Välkommen till Andreas bank!");
            bool avsluta = true;

            while (avsluta)
            {
                Console.WriteLine("Ange det alternativ för vad du vill göra: ");
                Console.WriteLine("[I]nsättning");
                Console.WriteLine("[U]ttag");
                Console.WriteLine("[S]aldo");
                Console.WriteLine("[R]äntebetalning");
                Console.WriteLine("[A]vsluta");

                char menuAlternativ = Convert.ToChar(Console.ReadLine());
                Console.WriteLine(GetMenu(menuAlternativ));

                Console.ReadLine();
            }
        }

        static string GetMenu(char menu)
        {
            string menuChoice;
            double insättning;
            double uttag;

            switch (menu)
            {
                case 'I':
                    Console.WriteLine("Ange hur mycket du vill sätta in: ");
                    insättning = Convert.ToInt32(Console.ReadLine());
                    saldo = insättning + saldo;
                    menuChoice = "Du har satt in " + insättning + " Kronor.";
                break;
                case 'U':
                    Console.WriteLine("Ange hur mycket du vill ta ut: ");
                    uttag = Convert.ToInt32(Console.ReadLine());
                    menuChoice = "Du har tagit ut " + uttag + " Kronor.";
                break;
                case 'S':
                    menuChoice = "Ditt saldo är: " + saldo + " Kronor.";
                break;
                case 'R':
                    double Summa = 0, ränta, sparandeÅr, totaltSparande;
                    Console.Write("Skriv in ditt årliga sparande: ");
                    totaltSparande = Convert.ToDouble(Console.ReadLine());
                    Console.Write("Ange räntan per år: ");
                    ränta = Convert.ToDouble(Console.ReadLine()) / 100;
                    Console.Write("Ange antal år du vill spara: ");
                    sparandeÅr = Convert.ToDouble(Console.ReadLine());

                    //Om antal år är mindre än antal år användaren vill spara, öka med 1 år tills användarens antal år är nådd.
                    for (int år = 1; år < sparandeÅr + 1; år++)
                    {
                        Summa = totaltSparande * Math.Pow((1 + ränta / sparandeÅr), (sparandeÅr * år));
                        Console.Write("Ditt totala sparande för år {0} " + " är: {1:F0}. \n", år, Summa);
                    }
                    menuChoice = "Så här kommer din ränta att se ut.";
                break;
                case 'A':
                    menuChoice = "Du har valt att avsluta programmet.";
                break;
                default:
                    menuChoice = "Invalid menu character";
                break;
            }
            return menuChoice;
        }
    }
}


问:
Flutter TextFormField not updating it's value
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

```<code>  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();
</code>```

And this is the code of TextFormField

```<code> TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),
</code>```

And this is the code for the method _selectTime

```<code>_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }
</code>```

答:
Do as follows:</p>
```<code>_timeController.text=timeOfDay.toString();
</code>```

Body:
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();

And this is the code of TextFormField

 TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),

And this is the code for the method _selectTime

_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }

Body:
Do as follows:

_timeController.text=timeOfDay.toString();


问:
Get the rank of each string extracted from split_string
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

```<code>select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null
</code>```

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

答:
Split_string has an option to output this rank, called ordinal. Just add an extra parameter with the value of 1:

```<code>SELECT *FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ', 1);
</code>```

That returns:

```<code>value   ordinal
Lorem   1
ipsum   2
dolor   3
sit 4
amet.   5
</code>```

In your case the query would be:

```<code>select top 10 id,[DYS385],t.* from dys OUTER APPLY(select * from string_split([DYS385],'-',1)) t where dys385 is not null
</code>```

Body:
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

Body:
Split_string has an option to output this rank, called ordinal. Just add an extra parameter with the value of 1:

SELECT *FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ', 1);

That returns:

value   ordinal
Lorem   1
ipsum   2
dolor   3
sit 4
amet.   5

In your case the query would be:

select top 10 id,[DYS385],t.* from dys OUTER APPLY(select * from string_split([DYS385],'-',1)) t where dys385 is not null


问:
calculate sum of squares with rows above
I have a dataset that looks like this:

```<code>Value         Type       X_sq
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather
</code>```

I want to iterate through each row and calculate a sum of squares value for each row above (only if the Type matches). I want to put this value in the X.sq column.

So for example, in the first row, there's nothing above. So only (-1.975767 x -1.975767). In the second row, there's no FRUITS row above it, so it will just be -0.540979 x -0.540979. However, in the third row, when we scan all previous rows, we should find that FRUITS is already there. So we should get the last's FRUIT's  .....  X_sq value and calculate a new sum of squares.

```<code>Value         Type       X_sq
-1.975767     Weather   -1.975767 * -1.975767    = x
-0.540979     Fruits    -0.540979 * -0.540979    = y
-2.359127     Fruits    y + ( -2.359127 x -2.359127)
-2.815604     Corona    -2.815604 * -2.815604
-0.929755     Weather   x + (-0.929755 * -0.929755)
</code>```

What would be an efficient way to do this?

```<code>def updateSS(X_sq, X_new):
    return X_sq + X_new**2
</code>```

EDIT:

```<code>----> 1 df['sumOfSquares'] = df['avg_country_tone'].pow(2).groupby(['themes', 'suppliers_country']).cumsum()

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/series.py:1929, in Series.groupby(self, by, axis, level, as_index, sort, group_keys, squeeze, observed, dropna)
   1925 axis = self._get_axis_number(axis)
   1927 # error: Argument "squeeze" to "SeriesGroupBy" has incompatible type
   1928 # "Union[bool, NoDefault]"; expected "bool"
-> 1929 return SeriesGroupBy(
   1930     obj=self,
   1931     keys=by,
   1932     axis=axis,
   1933     level=level,
   1934     as_index=as_index,
   1935     sort=sort,
   1936     group_keys=group_keys,
   1937     squeeze=squeeze,  # type: ignore[arg-type]
   1938     observed=observed,
   1939     dropna=dropna,
   1940 )

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/groupby.py:882, in GroupBy.__init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, squeeze, observed, mutated, dropna)
    879 if grouper is None:
    880     from pandas.core.groupby.grouper import get_grouper
--> 882     grouper, exclusions, obj = get_grouper(
    883         obj,
    884         keys,
    885         axis=axis,
    886         level=level,
    887         sort=sort,
    888         observed=observed,
    889         mutated=self.mutated,
    890         dropna=self.dropna,
    891     )
    893 self.obj = obj
    894 self.axis = obj._get_axis_number(axis)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/grouper.py:882, in get_grouper(obj, key, axis, level, sort, observed, mutated, validate, dropna)
    880         in_axis, level, gpr = False, gpr, None
    881     else:
--> 882         raise KeyError(gpr)
    883 elif isinstance(gpr, Grouper) and gpr.key is not None:
    884     # Add key to exclusions
    885     exclusions.add(gpr.key)

KeyError: 'themes'
even though themes is there. Themes = type
</code>```

Body:
I have a dataset that looks like this:

Value         Type       X_sq
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather

I want to iterate through each row and calculate a sum of squares value for each row above (only if the Type matches). I want to put this value in the X.sq column.

So for example, in the first row, there's nothing above. So only (-1.975767 x -1.975767). In the second row, there's no FRUITS row above it, so it will just be -0.540979 x -0.540979. However, in the third row, when we scan all previous rows, we should find that FRUITS is already there. So we should get the last's FRUIT's  .....  X_sq value and calculate a new sum of squares.

Value         Type       X_sq
-1.975767     Weather   -1.975767 * -1.975767    = x
-0.540979     Fruits    -0.540979 * -0.540979    = y
-2.359127     Fruits    y + ( -2.359127 x -2.359127)
-2.815604     Corona    -2.815604 * -2.815604
-0.929755     Weather   x + (-0.929755 * -0.929755)

What would be an efficient way to do this?

def updateSS(X_sq, X_new):
    return X_sq + X_new**2

EDIT:

----> 1 df['sumOfSquares'] = df['avg_country_tone'].pow(2).groupby(['themes', 'suppliers_country']).cumsum()

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/series.py:1929, in Series.groupby(self, by, axis, level, as_index, sort, group_keys, squeeze, observed, dropna)
   1925 axis = self._get_axis_number(axis)
   1927 # error: Argument "squeeze" to "SeriesGroupBy" has incompatible type
   1928 # "Union[bool, NoDefault]"; expected "bool"
-> 1929 return SeriesGroupBy(
   1930     obj=self,
   1931     keys=by,
   1932     axis=axis,
   1933     level=level,
   1934     as_index=as_index,
   1935     sort=sort,
   1936     group_keys=group_keys,
   1937     squeeze=squeeze,  # type: ignore[arg-type]
   1938     observed=observed,
   1939     dropna=dropna,
   1940 )

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/groupby.py:882, in GroupBy.__init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, squeeze, observed, mutated, dropna)
    879 if grouper is None:
    880     from pandas.core.groupby.grouper import get_grouper
--> 882     grouper, exclusions, obj = get_grouper(
    883         obj,
    884         keys,
    885         axis=axis,
    886         level=level,
    887         sort=sort,
    888         observed=observed,
    889         mutated=self.mutated,
    890         dropna=self.dropna,
    891     )
    893 self.obj = obj
    894 self.axis = obj._get_axis_number(axis)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/groupby/grouper.py:882, in get_grouper(obj, key, axis, level, sort, observed, mutated, validate, dropna)
    880         in_axis, level, gpr = False, gpr, None
    881     else:
--> 882         raise KeyError(gpr)
    883 elif isinstance(gpr, Grouper) and gpr.key is not None:
    884     # Add key to exclusions
    885     exclusions.add(gpr.key)

KeyError: 'themes'
even though themes is there. Themes = type

Body:
Use:

df['X_sq'] = df['Value'].pow(2).groupby(df['Type']).cumsum()
print(df)

# Output
      Value     Type      X_sq
0 -1.975767  Weather  3.903655
1 -0.540979   Fruits  0.292658
2 -2.359127   Fruits  5.858138
3 -2.815604   Corona  7.927626
4 -0.929755  Weather  4.768100


问:
RedShift: Simple insert Queries are not running on concurrent cluster
We have added concurrent cluster support for our redshift cluster. It runs select queries in case of high load.

I have below questions:

Does it give the higher priority to read queries over write?

We have simple insert statement, but they are not being picked up by concurrent cluster. what could be the possible reason for it?

答:
Yes, concurrent clusters are designed to run read-only queries as the master copy of the data remains on the main cluster AND a limited set of write queries.  A full list of these write limitations are given at https://docs.aws.amazon.com/redshift/latest/dg/concurrency-scaling.html

Also, since concurrent clusters are remote from the source data there is an inherent cost to run queries on these clusters.  Simple queries generally won't gain enough from the concurrent cluster's resource availability to overcome these costs for short, simple queries.

What you are seeing seems quite normal from my Redshift experience.


问:
Rendering plain text via PHP after query from database
I have this dump raw plain text. I uploaded it into my site as is

```<code>➜  Desktop ping 198.54.120.122
PING 198.54.120.122 (198.54.120.122): 56 data bytes
64 bytes from 198.54.120.122: icmp_seq=0 ttl=35 time=85.655 ms
64 bytes from 198.54.120.122: icmp_seq=1 ttl=35 time=84.976 ms
64 bytes from 198.54.120.122: icmp_seq=2 ttl=35 time=85.856 ms
64 bytes from 198.54.120.122: icmp_seq=3 ttl=35 time=85.103 ms
^C
--- 198.54.120.122 ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 84.976/85.397/85.856/0.368 ms
</code>```

I query it back I got this

I dd() it out to test, meaning at this point, I didn't lost my new lines yet.

I've tried

str_replace('\r\n','
',$paste->raw); and hoping to see rendering better

```<code>public function raw($uuid)
{
    $paste  = Paste::where('uuid', base64_decode($uuid))->first();
    return str_replace('\r\n','<br>',$paste->raw);
}
</code>```

Result

It rendering like this without newlines

```<code>PING 198.54.120.235 (198.54.120.235): 56 data bytes 64 bytes from 198.54.120.235: icmp_seq=0 ttl=35 time=85.655 ms 64 bytes from 198.54.120.235: icmp_seq=1 ttl=35 time=84.976 ms 64 bytes from 198.54.120.235: icmp_seq=2 ttl=35 time=85.856 ms 64 bytes from 198.54.120.235: icmp_seq=3 ttl=35 time=85.103 ms ^C --- 198.54.120.235 ping statistics --- 4 packets transmitted, 4 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 84.976/85.397/85.856/0.368 ms
</code>```

You guys can even see it live : here

How would one achieve that? Should I use the front-end to style this?

Imagine, you view a raw file in GitHub or gist , I'm trying to build a mini version of that, an ability to display what I uploaded, and quickly share with others via a link.

The link suggested above, doesn't answer what I am looking for.

答:
To keep the line breaks (\n, \r\n) in html you could use the nl2br php function.

Your raw function would be something like this

```<code>public function raw($uuid)
{
    $paste  = Paste::where('uuid', base64_decode($uuid))->first();
    return nl2br($paste->raw);
}
</code>```

Or you could use the href="https://www.w3schools.com/tags/tag_pre.asp" rel="nofollow noreferrer">``` tag</a> to keep the original format.</p>
<p>Or you could serve the file as plain text using the <a href="https://www.w3schools.com/tags/tag_pre.asp" rel="nofollow noreferrer">header function</a>.</p>
<p>Add this to your code before any output, in a controller for example:</p>
```header('Content-Type: text/plain');
```
<p>One thing to note is that if you're using some framework it wil probably have some helper service to add headers. But adding this code above should work either way. And since you are serving plain text files, no html tag will work.</p>
<p>Adapting to your code:</p>
```class OutputController {
    public function output() {
        header('Content-Type: text/plain');

        echo Paste::where('uuid', base64_decode($uuid))->first();
    }
}
```

Body:
I have this dump raw plain text. I uploaded it into my site as is

➜  Desktop ping 198.54.120.122
PING 198.54.120.122 (198.54.120.122): 56 data bytes
64 bytes from 198.54.120.122: icmp_seq=0 ttl=35 time=85.655 ms
64 bytes from 198.54.120.122: icmp_seq=1 ttl=35 time=84.976 ms
64 bytes from 198.54.120.122: icmp_seq=2 ttl=35 time=85.856 ms
64 bytes from 198.54.120.122: icmp_seq=3 ttl=35 time=85.103 ms
^C
--- 198.54.120.122 ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 84.976/85.397/85.856/0.368 ms

I query it back I got this

I dd() it out to test, meaning at this point, I didn't lost my new lines yet.

I've tried

str_replace('\r\n','
',$paste->raw); and hoping to see rendering better

public function raw($uuid)
{
    $paste  = Paste::where('uuid', base64_decode($uuid))->first();
    return str_replace('\r\n','
',$paste->raw);
}

Result

It rendering like this without newlines

PING 198.54.120.235 (198.54.120.235): 56 data bytes 64 bytes from 198.54.120.235: icmp_seq=0 ttl=35 time=85.655 ms 64 bytes from 198.54.120.235: icmp_seq=1 ttl=35 time=84.976 ms 64 bytes from 198.54.120.235: icmp_seq=2 ttl=35 time=85.856 ms 64 bytes from 198.54.120.235: icmp_seq=3 ttl=35 time=85.103 ms ^C --- 198.54.120.235 ping statistics --- 4 packets transmitted, 4 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 84.976/85.397/85.856/0.368 ms

You guys can even see it live : here

How would one achieve that? Should I use the front-end to style this?

Imagine, you view a raw file in GitHub or gist , I'm trying to build a mini version of that, an ability to display what I uploaded, and quickly share with others via a link.

The link suggested above, doesn't answer what I am looking for.

Body:
To keep the line breaks (\n, \r\n) in html you could use the nl2br php function.

Your raw function would be something like this

public function raw($uuid)
{
    $paste  = Paste::where('uuid', base64_decode($uuid))->first();
    return nl2br($paste->raw);
}

Or you could use the <pre> tag to keep the original format.

Or you could serve the file as plain text using the header function.

Add this to your code before any output, in a controller for example:

header('Content-Type: text/plain');

One thing to note is that if you're using some framework it wil probably have some helper service to add headers. But adding this code above should work either way. And since you are serving plain text files, no html tag will work.

Adapting to your code:

class OutputController {
    public function output() {
        header('Content-Type: text/plain');

        echo Paste::where('uuid', base64_decode($uuid))->first();
    }
}


问:
Buttons under each other in div
i created div for some buttons in a kind of sidebar.
But I am not quite sure how do I get them under each other...

My previous solution were 2 divs under eachother but then it was not that could regarding the various display sizes that the buttons are directly under each other...

Any idea?

#sideBar {
  position: fixed;
  right: -29px;
  top: 52vh;
  display: inline-grid;
}

#feedbackBtn {
  z-index: 1000;
  transform: rotate(270deg);
}

#helpBtn {
  z-index: 1000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sideBar">
  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default"></Button>
</div></code>```

Image

答:
I think you only need the sideBar CSS,
Using the attribute below you could make it stick to the right and the button will behave like normal.

Note that

I move the z-index to sidebar because all the button inside of it should be on top of all element right? so you could put it on the sidebar, it doesn't have to be on the child

I move the transform to sidebar so you basically the thing that's rotating is the "container" of the sidebar, you can imagine it as a normal container with two button side by side, and then you rotate it, that's why the button is actually still side by side, not on top of each other

sorry for bad English

#sideBar {
  position: fixed;
  transform: rotate(270deg);
  z-index: 1000;
  right:-10px;
  top: 52vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sideBar">
  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default">Help</Button>
</div></code>```

Title: Buttons under each other in div

Body:
i created div for some buttons in a kind of sidebar.
But I am not quite sure how do I get them under each other...

My previous solution were 2 divs under eachother but then it was not that could regarding the various display sizes that the buttons are directly under each other...

Any idea?

#sideBar {
  position: fixed;
  right: -29px;
  top: 52vh;
  display: inline-grid;
}

#feedbackBtn {
  z-index: 1000;
  transform: rotate(270deg);
}

#helpBtn {
  z-index: 1000;
}

  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default"></Button>

Image

Body:
I think you only need the sideBar CSS,
Using the attribute below you could make it stick to the right and the button will behave like normal.

Note that

I move the z-index to sidebar because all the button inside of it should be on top of all element right? so you could put it on the sidebar, it doesn't have to be on the child

I move the transform to sidebar so you basically the thing that's rotating is the "container" of the sidebar, you can imagine it as a normal container with two button side by side, and then you rotate it, that's why the button is actually still side by side, not on top of each other

sorry for bad English

#sideBar {
  position: fixed;
  transform: rotate(270deg);
  z-index: 1000;
  right:-10px;
  top: 52vh;
}

<div id="sideBar">
  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default">Help</Button>
</div>


答:
Try to use the predefined constant PHP_EOL instead of \r\n(https://www.php.net/manual/en/reserved.constants.php#constant.php-eol)

```<code>return str_replace(PHP_EOL, '<br>', $paste->raw);
</code>```

If you want to do the same for whitespaces, you can use the built in html codes for whitespaces, for example:

```<code>str_replace(' ', '&nbsp', $string);
str_replace('\t', '&nbsp&nbsp&nbsp&nbsp', $string);
</code>```

So all together:

```<code>return str_replace('\t', '&nbsp&nbsp&nbsp&nbsp', str_replace(' ', '&nbsp', str_replace(PHP_EOL, '<br>', $paste->raw)));
</code>```

Or there is another way, using the html ```</code> and <code><code></code> tag. This tag makes is possible that the text will be displayed exactly as written in the HTML source code.</p>
```return '```'.str_replace('>', '>', str_replace('<', '<', $paste->raw)).'```';
```

Title: Rendering plain text via PHP after query from database

Body:
Try to use the predefined constant PHP_EOL instead of \r\n(https://www.php.net/manual/en/reserved.constants.php#constant.php-eol)

return str_replace(PHP_EOL, '<br>', $paste->raw);

If you want to do the same for whitespaces, you can use the built in html codes for whitespaces, for example:

str_replace(' ', '&nbsp', $string);
str_replace('\t', '&nbsp&nbsp&nbsp&nbsp', $string);

So all together:

return str_replace('\t', '&nbsp&nbsp&nbsp&nbsp', str_replace(' ', '&nbsp', str_replace(PHP_EOL, '<br>', $paste->raw)));

Or there is another way, using the html <pre> and <code> tag. This tag makes is possible that the text will be displayed exactly as written in the HTML source code.

return '<pre>'.str_replace('>', '&gt;', str_replace('<', '&lt;', $paste->raw)).'</pre>';


问:
Parse lines from messages in a Splunk query to be displayed as a chart on a dashboard
I generate events on multiple computers that list service names that aren't running. I want to make a chart that displays the top offending service names.

I can use the following to get a table for the dashboard:

```<code>ComputerName="*.ourDomain.com" sourcetype="WinEventLog:Application" EventCode=7223 SourceName="internalSystem"
| eval Date_Time=strftime(_time, "%Y-%m-%d %H:%M")
| table host, Date_Time, Message, EventCode
</code>```

Typical Message(s) will contain:

```<code>The following services were not running after 5603 seconds and a start command has been sent:
Service1
Service2
</code>```
```<code>The following services were not running after 985 seconds and a start command has been sent:
Service2
Service3
</code>```

Using regex I can make a named group of everything but the first line with (?<Services>((?<=\n)).*)
However, I don't think this is the right approach as I don't know how to do a valuation for the chart with this information.

So in essence, how do I grab and tally service names from messages in Splunk?

Edit 1:
Coming back to this after a few days.
I created a field extraction called "Services" with regex that grabs the contents of each message after the first line.
If I use | stats count BY Services it counts each message as a whole instead of the lines inside. The results look like this:

```<code>Service1 Service2 | Count: 1
Service2 Service3 | Count: 1
</code>```

My intention is to have it treat each line as its own value so the results would look like:

```<code>Service1 | Count: 1
Service2 | Count: 2
Service3 | Count: 1
</code>```

I tried | mvexpand Services but it didn't change the output so I assume I'm either using it improperly or it's not applicable here.

答:
I think you can do it with the stats command.

```<code>| stats count by service
</code>```

will give a number of appearances for each service.  You then can choose the bar chart visualization to create a graph.

Body:
I generate events on multiple computers that list service names that aren't running. I want to make a chart that displays the top offending service names.

I can use the following to get a table for the dashboard:

ComputerName="*.ourDomain.com" sourcetype="WinEventLog:Application" EventCode=7223 SourceName="internalSystem"
| eval Date_Time=strftime(_time, "%Y-%m-%d %H:%M")
| table host, Date_Time, Message, EventCode

Typical Message(s) will contain:

The following services were not running after 5603 seconds and a start command has been sent:
Service1
Service2

The following services were not running after 985 seconds and a start command has been sent:
Service2
Service3

Using regex I can make a named group of everything but the first line with (?<Services>((?<=\n)).*)
However, I don't think this is the right approach as I don't know how to do a valuation for the chart with this information.

So in essence, how do I grab and tally service names from messages in Splunk?

Edit 1:
Coming back to this after a few days.
I created a field extraction called "Services" with regex that grabs the contents of each message after the first line.
If I use | stats count BY Services it counts each message as a whole instead of the lines inside. The results look like this:

Service1 Service2 | Count: 1
Service2 Service3 | Count: 1

My intention is to have it treat each line as its own value so the results would look like:

Service1 | Count: 1
Service2 | Count: 2
Service3 | Count: 1

I tried | mvexpand Services but it didn't change the output so I assume I'm either using it improperly or it's not applicable here.

Body:
I think you can do it with the stats command.

| stats count by service

will give a number of appearances for each service.  You then can choose the bar chart visualization to create a graph.


问:
httpAccessor.HttpContext.SignInAsync User is empty

Context

I have one web application seperated in two "utilities".

Web API

Razor Pages

So my app is both an API and a ASP.NET Razor Pages app, to authenticate on the Web API side I use JWT Bearer and on Web App side a simple Cookie.

Problem

When using Cookie Authentication, I followed Microsoft's Use cookie authentication without ASP.NET Core Identity and it's absolutely not working AT ALL.

I use a custom AuthManager with a SignInAsync method. The cookie is indeed created BUT the ClaimsPrincipal in my HttpContext is empty

I didn't find ANY SOLUTION AT ALL on internet, the only solutions that seemed viable were by using custom Middlewares but I don't even know where to start.

If anybody encountered the same problem as me.

Thanks

public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            UserModel user = _userService.UserLogin(email, password).MapFromBLL();
            if (user is null) return false;

            user.Roles = _roleService.GetUserRoles(user.Id).Select(r => r.MapFromBLL());
            if (user.Roles is null || user.Roles.Count() == 0) return false;

            List<Claim> claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("Stamp", user.SecurityStamp.ToString())
            };

            IEnumerable<Claim> roleClaims = user.Roles.Select(ur => new Claim(ClaimTypes.Role, ur.Name));

            claims.AddRange(roleClaims);

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTime.Now.AddDays(_jwtModel.ExpirationInDays),
                IsPersistent = true,
                IssuedUtc = DateTime.Now,
            };

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            try
            {
                await _httpAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }

```
<p>Startup.cs</p>
<pre class="lang-cs prettyprint-override"><code>services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.SlidingExpiration = true;
                     options.Cookie.HttpOnly = true;
                     options.Cookie.SecurePolicy = CookieSecurePolicy.None;
                     options.Cookie.IsEssential = true;
                     options.Cookie.SameSite = SameSiteMode.Strict;
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";
                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = jwtModel.Issuer,
                        ValidAudience = jwtModel.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtModel.Secret)),
                        ClockSkew = TimeSpan.Zero
                    };
                });

</code>```

EDIT 10-02-2022

I seperated the post in two chapters : "Context" and "Problem"

答:
My solution

Ok, so I found a solution to my problem. It was, as usual after 10 hours of research, dumb. In my Startup.cs I used JwtBearerDefaults.AuthenticationScheme as DefaultAuthenticateScheme. So I changed it with CookieAuthenticationDefaults.AuthenticationScheme, and now by miracle IT WORKS. After logging in, my ClaimsPrincipal User is full and it retrieve correctly the cookie.

My new services.AddAuthentication() in Startup.cs

services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
```
<p>I don't really know if I should keep <code> options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;</code>. If anyone could enlight me.</p>
<p>I didn't change anything in my method <code>public async Task<bool> SignInAsync()</code> I just added <code>await _httpAccessor.HttpContext.SignOutAsync()</code> at the beginning just to be sure.</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            await LogOutAsync();

            // The same code as before
        }
</code>```

The LogOutAsync() method

public async Task LogOutAsync()
        {
            try
            {
                await _httpAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
```
<h1>Problems encountered</h1>
<h2>Authorization</h2>
<p>After fixing this problem, I had another one. Now that my default scheme is Cookie based, I can't just use <code>[Authorize]</code> and except it to work with both Cookie or Jwt. To fix that I just added this code in <strong>Startup.cs</strong> after <code>services.AddAuthentication()</code></p>
<pre class="lang-cs prettyprint-override"><code>AuthorizationPolicy multiSchemePolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = multiSchemePolicy;
            });
</code>```

Code that I found here

API Unauthorize return Login Page instead of 401 or 403 status codes

This one is kind of strange, now the cookie and the JwtBearer worked fine, when I tried to access an [Authorize] route, sometimes it returned me the HTML page to Login instead of 401 Status Code and sometimes not.

To avoid this problem, I found a solution here

using services.ConfigureApplicationCookie didn't work for me, instead I adapted my services.AddCookie().

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";

                     options.Events = new CookieAuthenticationEvents()
                     {
                         OnRedirectToLogin = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 401;
                             }

                             return Task.CompletedTask;
                         },
                         OnRedirectToAccessDenied = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 403;
                             }

                             return Task.CompletedTask;
                         }
                     };

                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 });
```
<p>Voilà, I hope I have helped at least one of you. If there is anything to change, just let me know !</p>
<h1>Complete code</h1>
<h2>Startup.cs</h2>
<pre class="lang-cs prettyprint-override"><code>services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = jwtModel.Issuer,
                        ValidAudience = jwtModel.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtModel.Secret)),
                        ClockSkew = TimeSpan.Zero
                    };
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";

                     options.Events = new CookieAuthenticationEvents()
                     {
                         OnRedirectToLogin = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 401;
                             }

                             return Task.CompletedTask;
                         },
                         OnRedirectToAccessDenied = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 403;
                             }

                             return Task.CompletedTask;
                         }
                     };

                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 });

            AuthorizationPolicy multiSchemePolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = multiSchemePolicy;
            });
</code>```

AuthManager.cs

 public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            await LogOutAsync();

            UserModel user = _userService.UserLogin(email, password).MapFromBLL();
            if (user is null) return false;

            user.Roles = _roleService.GetUserRoles(user.Id).Select(r => r.MapFromBLL());
            if (user.Roles is null || user.Roles.Count() == 0) return false;

            List<Claim> claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("Stamp", user.SecurityStamp.ToString())
            };

            IEnumerable<Claim> roleClaims = user.Roles.Select(ur => new Claim(ClaimTypes.Role, ur.Name));

            claims.AddRange(roleClaims);

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTime.Now.AddDays(_jwtModel.ExpirationInDays),
                IsPersistent = true,
                IssuedUtc = DateTime.Now,
            };

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            try
            {
                await _httpAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }

        public async Task LogOutAsync()
        {
            try
            {
                await _httpAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
```

Body:
Context

I have one web application seperated in two "utilities".

Web API

Razor Pages

So my app is both an API and a ASP.NET Razor Pages app, to authenticate on the Web API side I use JWT Bearer and on Web App side a simple Cookie.

Problem

When using Cookie Authentication, I followed Microsoft's Use cookie authentication without ASP.NET Core Identity and it's absolutely not working AT ALL.

I use a custom AuthManager with a SignInAsync method. The cookie is indeed created BUT the ClaimsPrincipal in my HttpContext is empty

I didn't find ANY SOLUTION AT ALL on internet, the only solutions that seemed viable were by using custom Middlewares but I don't even know where to start.

If anybody encountered the same problem as me.

Thanks

public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            UserModel user = _userService.UserLogin(email, password).MapFromBLL();
            if (user is null) return false;

            user.Roles = _roleService.GetUserRoles(user.Id).Select(r => r.MapFromBLL());
            if (user.Roles is null || user.Roles.Count() == 0) return false;

            List<Claim> claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("Stamp", user.SecurityStamp.ToString())
            };

            IEnumerable<Claim> roleClaims = user.Roles.Select(ur => new Claim(ClaimTypes.Role, ur.Name));

            claims.AddRange(roleClaims);

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTime.Now.AddDays(_jwtModel.ExpirationInDays),
                IsPersistent = true,
                IssuedUtc = DateTime.Now,
            };

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            try
            {
                await _httpAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }

Startup.cs

services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.SlidingExpiration = true;
                     options.Cookie.HttpOnly = true;
                     options.Cookie.SecurePolicy = CookieSecurePolicy.None;
                     options.Cookie.IsEssential = true;
                     options.Cookie.SameSite = SameSiteMode.Strict;
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";
                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = jwtModel.Issuer,
                        ValidAudience = jwtModel.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtModel.Secret)),
                        ClockSkew = TimeSpan.Zero
                    };
                });

EDIT 10-02-2022

I seperated the post in two chapters : "Context" and "Problem"

Body:
My solution

Ok, so I found a solution to my problem. It was, as usual after 10 hours of research, dumb. In my Startup.cs I used JwtBearerDefaults.AuthenticationScheme as DefaultAuthenticateScheme. So I changed it with CookieAuthenticationDefaults.AuthenticationScheme, and now by miracle IT WORKS. After logging in, my ClaimsPrincipal User is full and it retrieve correctly the cookie.

My new services.AddAuthentication() in Startup.cs

services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })

I don't really know if I should keep  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;. If anyone could enlight me.

I didn't change anything in my method public async Task<bool> SignInAsync() I just added await _httpAccessor.HttpContext.SignOutAsync() at the beginning just to be sure.

public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            await LogOutAsync();

            // The same code as before
        }

The LogOutAsync() method

public async Task LogOutAsync()
        {
            try
            {
                await _httpAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }

Problems encountered

Authorization

After fixing this problem, I had another one. Now that my default scheme is Cookie based, I can't just use [Authorize] and except it to work with both Cookie or Jwt. To fix that I just added this code in Startup.cs after services.AddAuthentication()

AuthorizationPolicy multiSchemePolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = multiSchemePolicy;
            });

Code that I found here

API Unauthorize return Login Page instead of 401 or 403 status codes

This one is kind of strange, now the cookie and the JwtBearer worked fine, when I tried to access an [Authorize] route, sometimes it returned me the HTML page to Login instead of 401 Status Code and sometimes not.

To avoid this problem, I found a solution here

using services.ConfigureApplicationCookie didn't work for me, instead I adapted my services.AddCookie().

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";

                     options.Events = new CookieAuthenticationEvents()
                     {
                         OnRedirectToLogin = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 401;
                             }

                             return Task.CompletedTask;
                         },
                         OnRedirectToAccessDenied = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 403;
                             }

                             return Task.CompletedTask;
                         }
                     };

                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 });

Voilà, I hope I have helped at least one of you. If there is anything to change, just let me know !

Complete code

Startup.cs

services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = jwtModel.Issuer,
                        ValidAudience = jwtModel.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtModel.Secret)),
                        ClockSkew = TimeSpan.Zero
                    };
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                 {
                     options.LoginPath = "/Account/Login";
                     options.AccessDeniedPath = "/Forbidden";

                     options.Events = new CookieAuthenticationEvents()
                     {
                         OnRedirectToLogin = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 401;
                             }

                             return Task.CompletedTask;
                         },
                         OnRedirectToAccessDenied = (ctx) =>
                         {
                             if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                             {
                                 ctx.Response.StatusCode = 403;
                             }

                             return Task.CompletedTask;
                         }
                     };

                     options.EventsType = typeof(SecurityStampUpdatedCookieAuthenticationEvent);
                 });

            AuthorizationPolicy multiSchemePolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = multiSchemePolicy;
            });

AuthManager.cs

 public async Task<bool> LogInAsync(string email, string password, bool rememberMe)
        {
            await LogOutAsync();

            UserModel user = _userService.UserLogin(email, password).MapFromBLL();
            if (user is null) return false;

            user.Roles = _roleService.GetUserRoles(user.Id).Select(r => r.MapFromBLL());
            if (user.Roles is null || user.Roles.Count() == 0) return false;

            List<Claim> claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("Stamp", user.SecurityStamp.ToString())
            };

            IEnumerable<Claim> roleClaims = user.Roles.Select(ur => new Claim(ClaimTypes.Role, ur.Name));

            claims.AddRange(roleClaims);

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTime.Now.AddDays(_jwtModel.ExpirationInDays),
                IsPersistent = true,
                IssuedUtc = DateTime.Now,
            };

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            try
            {
                await _httpAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }

        public async Task LogOutAsync()
        {
            try
            {
                await _httpAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }


问:
SwiftUI animation: Some implicit transition animations broken on iOS 13?
Tested on Xcode 11.3.1 and 11.4:

When attaching implicit animations to a transition, some transition types appear to be broken. Specifically, any position-related transitions do not apply the given implicit animation. .slide, .move, .offset are broken. .opacity and .scale seem ok. (See attachment)

Explicit animations seem to work fine in all cases.

Even with custom compound Transitions, the position-related sub-transitions do not respond to implicit animation.

Is this a bug, or expected behavior?

Seems like this would be a problem if you want to trigger multiple different animation curves for specific UI elements based on an implicit property change.

```<code>
struct MyExample: View {

    @State private var isShowing = true

    private let myAnimation = Animation.spring(response: 0.8, dampingFraction: 0.2, blendDuration: 3.0)
    var body: some View {
        VStack(spacing:20) {
            if self.isShowing {
                Text("Opacity").modifier(MyBigFont())
                    .transition(AnyTransition.opacity.animation(myAnimation))

                Text("Scale").modifier(MyBigFont())
                    .transition(AnyTransition.scale.animation(myAnimation))

                Text("Slide").modifier(MyBigFont())
                    .transition(AnyTransition.slide.animation(myAnimation))

                Text("Move").modifier(MyBigFont())
                    .transition(AnyTransition.move(edge: .trailing).animation(myAnimation))

                Text("Offset").modifier(MyBigFont())
                    .transition(AnyTransition.offset(x: 20, y: 0).animation(myAnimation))

                Text("Custom").modifier(MyBigFont())
                    .transition(AnyTransition.myCustomTransition.animation(myAnimation))
            }

            Spacer()

            Button(action: {
                self.isShowing.toggle()
            }) {
                Text("Implicit Toggle")
            }

            Button(action: {
                withAnimation(self.myAnimation) {
                    self.isShowing.toggle()
                }
            }) {
                Text("Explicit Toggle")
            }
        }
    }

}

struct MyBigFont: ViewModifier {
    func body(content: Content) -> some View {
        content
            .lineLimit(1)
            .padding()
            .background(Color.purple)
            .foregroundColor(.white)
            .cornerRadius(8)
            .font(Font.system(size: 21).bold())
    }
}

struct MyCustomTransition: ViewModifier {

    var isEnabled: Bool

    func body(content: Content) -> some View {

        if isEnabled {
            return content
                .offset(x: 20.0, y: 0.0)
                .opacity(0)
        } else {
            return content
                .offset(x: 0.0, y: 0.0)
                .opacity(1)
        }

    }
}

extension AnyTransition {
    static let myCustomTransition = AnyTransition.modifier(
        active: MyCustomTransition(isEnabled: true),
        identity: MyCustomTransition(isEnabled: false))
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            MyExample()
            Spacer()
        }
    }
}

</code>```

答:
Asperi's answer is totally right, just tested it with Xcode 13.2.1 and iOS 15.2 / macOS 12.2 with the following simple example:

```<code>struct ContentView: View {
    @State private var show = false

    var body: some View {
        VStack(spacing: 20) {
            roundedRect(color: .blue)
            if show {
                roundedRect(color: .red)
                    .transition(.opacity.animation(.easeInOut))
            }

            Spacer()

            Button(show ? "Hide" : "Show") {
                show.toggle()
            }
        }
        .animation(.easeInOut)
        .padding()
        .frame(width: 190, height: 420, alignment: .top)
    }
}
</code>```

Suprisingly, this worked:

Opacity transition with implicit animation

Then I tried the same setup, just with the .slide transition, and then it stopped working:

Slide transition with implicit animation

Then I tried moving the animation out to the next container (VStack) like Asperi suggested above:

```<code>struct ContentView: View {
    @State private var show = false

    var body: some View {
        VStack(spacing: 20) {
            roundedRect(color: .blue)
            if show {
                roundedRect(color: .red)
                    .transition(.slide)
            }

            Spacer()

            Button(show ? "Hide" : "Show") {
                show.toggle()
            }
        }
        .animation(.easeInOut)
        .padding()
        .frame(width: 190, height: 420, alignment: .top)
    }
}
</code>```

Lo and behold, the transition started animating again.

Slide transition with implicit animation on the containing VStack

Body:
Tested on Xcode 11.3.1 and 11.4:

When attaching implicit animations to a transition, some transition types appear to be broken. Specifically, any position-related transitions do not apply the given implicit animation. .slide, .move, .offset are broken. .opacity and .scale seem ok. (See attachment)

Explicit animations seem to work fine in all cases.

Even with custom compound Transitions, the position-related sub-transitions do not respond to implicit animation.

Is this a bug, or expected behavior?

Seems like this would be a problem if you want to trigger multiple different animation curves for specific UI elements based on an implicit property change.

struct MyExample: View {

    @State private var isShowing = true

    private let myAnimation = Animation.spring(response: 0.8, dampingFraction: 0.2, blendDuration: 3.0)
    var body: some View {
        VStack(spacing:20) {
            if self.isShowing {
                Text("Opacity").modifier(MyBigFont())
                    .transition(AnyTransition.opacity.animation(myAnimation))

                Text("Scale").modifier(MyBigFont())
                    .transition(AnyTransition.scale.animation(myAnimation))

                Text("Slide").modifier(MyBigFont())
                    .transition(AnyTransition.slide.animation(myAnimation))

                Text("Move").modifier(MyBigFont())
                    .transition(AnyTransition.move(edge: .trailing).animation(myAnimation))

                Text("Offset").modifier(MyBigFont())
                    .transition(AnyTransition.offset(x: 20, y: 0).animation(myAnimation))

                Text("Custom").modifier(MyBigFont())
                    .transition(AnyTransition.myCustomTransition.animation(myAnimation))
            }

            Spacer()

            Button(action: {
                self.isShowing.toggle()
            }) {
                Text("Implicit Toggle")
            }

            Button(action: {
                withAnimation(self.myAnimation) {
                    self.isShowing.toggle()
                }
            }) {
                Text("Explicit Toggle")
            }
        }
    }

}

struct MyBigFont: ViewModifier {
    func body(content: Content) -> some View {
        content
            .lineLimit(1)
            .padding()
            .background(Color.purple)
            .foregroundColor(.white)
            .cornerRadius(8)
            .font(Font.system(size: 21).bold())
    }
}

struct MyCustomTransition: ViewModifier {

    var isEnabled: Bool

    func body(content: Content) -> some View {

        if isEnabled {
            return content
                .offset(x: 20.0, y: 0.0)
                .opacity(0)
        } else {
            return content
                .offset(x: 0.0, y: 0.0)
                .opacity(1)
        }

    }
}

extension AnyTransition {
    static let myCustomTransition = AnyTransition.modifier(
        active: MyCustomTransition(isEnabled: true),
        identity: MyCustomTransition(isEnabled: false))
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            MyExample()
            Spacer()
        }
    }
}

Body:
Asperi's answer is totally right, just tested it with Xcode 13.2.1 and iOS 15.2 / macOS 12.2 with the following simple example:

struct ContentView: View {
    @State private var show = false

    var body: some View {
        VStack(spacing: 20) {
            roundedRect(color: .blue)
            if show {
                roundedRect(color: .red)
                    .transition(.opacity.animation(.easeInOut))
            }

            Spacer()

            Button(show ? "Hide" : "Show") {
                show.toggle()
            }
        }
        .animation(.easeInOut)
        .padding()
        .frame(width: 190, height: 420, alignment: .top)
    }
}

Suprisingly, this worked:

Opacity transition with implicit animation

Then I tried the same setup, just with the .slide transition, and then it stopped working:

Slide transition with implicit animation

Then I tried moving the animation out to the next container (VStack) like Asperi suggested above:

struct ContentView: View {
    @State private var show = false

    var body: some View {
        VStack(spacing: 20) {
            roundedRect(color: .blue)
            if show {
                roundedRect(color: .red)
                    .transition(.slide)
            }

            Spacer()

            Button(show ? "Hide" : "Show") {
                show.toggle()
            }
        }
        .animation(.easeInOut)
        .padding()
        .frame(width: 190, height: 420, alignment: .top)
    }
}

Lo and behold, the transition started animating again.

Slide transition with implicit animation on the containing VStack


问:
Use a Local Model file for Online Viewer
I would like to be able to use a local navisworks or revit file to be available when using an online viewer app on forge.

I have so far followed the tutorial here - https://learnforge.autodesk.io/#/datamanagement/oss/ that allows me to upload a file for viewing from the client side. I would like to remove the ability to upload from the client side and choose a local file to be viewed instead.

I would also like to know how to remove additional buckets / objects placed from the client side from the side menu (circled in the image)

Thank you in advance!

答:
All our sample apps work like this (e.g. https://github.com/Autodesk-Forge/learn.forge.viewmodels/tree/nodejs):

all the client-side content (html, js, css) is in a specific folder (in case of nodejs samples it's called public)

all the rest is part of the server-side

all the Forge related functionality is exposed to the client-side through server-side endpoints

When the page is opened then the browser fetches the client-side components (1) - i.e. html, css, js files

When needed, the client-side code calls an endpoint on the server (2) which in turn reaches out to Forge (3) and passes back the result to the client

The only client-side part that communicates directly with Forge is the Viewer (4)

If you want to remove some of the functionality presented to the user, you can just remove them from the client-side part (e.g. from the html file)

In the server-side code, you can also combine multiple Forge calls: e.g. create a bucket, upload model file into it from the server, translate the model to SVF

If there are operations you only want to do just once (e.g. delete a bucket), you can also use utilities like https://oss-manager.autodesk.io/ or use this Visual Studio Code Extension: https://forge.autodesk.com/blog/forge-visual-studio-code

If you want to add controls to the toolbar this should be of help: https://learnforge.autodesk.io/#/tutorials/extensions

If you want to add something custom then you can use HTML/CSS/JS in your client-side code to implement those