问:
When I start the PowerShell script from the CMD this is not setting the variables well
If I start the command from PowerShell it works perfectly instead of CMD this happens:
Imgur Image</p>

```<code>PowerShell -NoLogo -NoProfile -Command "$MangaPage=Invoke-WebRequest -Uri %MangaLink%; $MangaName=$MangaPage.ParsedHtml.querySelector('#top-in > div.top-title > span.hideM0 > a').innerText; Write-Host $MangaName; $ChapterNumber=$MangaPage.ParsedHtml.querySelector('#combobox > option.selected').innerText; Write-Host $ChapterNumber; $PageNumber=$MangaPage.ParsedHtml.querySelector('#pageSelect > option.selected').innerText; Write-Host $PageNumber; $URLImage=$MangaPage.ParsedHtml.querySelector('#mainImg').src.replace('about:', 'https:'); Write-Host $URLImage; $FileExtension=$URLImage.SubString($URLImage.lastIndexOf('.')+1); Write-Host $FileExtension; $FileName='$.ChapterNumber'+'_'+'$PageNumber'+'_'+'$MangaName'+'.'+'$FileExtension'; $Folder=('$MangaName\$ChapterNumber'); If(!(Test-Path $Folder)) { New-Item -ItemType Directory -Force -Path $Folder }; Invoke-WebRequest $URLImage -OutFile $Folder\$FileName"
</code>```

答:
About PowerShell.exe

When the value of Command is a string, Command must be the last
  parameter specified because any characters typed after the command are
  interpreted as the command arguments.

The Command parameter only accepts a script block for execution when
  it can recognize the value passed to Command as a ScriptBlock type.
  This is only possible when running PowerShell.exe from another
  PowerShell host. The ScriptBlock type may be contained in an existing
  variable, returned from an expression, or parsed by the PowerShell
  host as a literal script block enclosed in curly braces {}, before
  being passed to PowerShell.exe.

In cmd.exe, there is no such thing as a script block (or ScriptBlock
  type), so the value passed to Command will always be a string. You can
  write a script block inside the string, but instead of being executed
  it will behave exactly as though you typed it at a typical PowerShell
  prompt, printing the contents of the script block back out to you.

A string passed to Command will still be executed as PowerShell, so
  the script block curly braces are often not required in the first
  place when running from cmd.exe. To execute an inline script block
  defined inside a string, the call operator & can be used:

console

"& {}"

```<code>PowerShell -NoLogo -NoProfile -Command  "&{ $MangaPage=Invoke-WebRequest -Uri %MangaLink%; $MangaName=$MangaPage.ParsedHtml.querySelector('#top-in > div.top-title > span.hideM0 > a').innerText; Write-Host $MangaName; $ChapterNumber=$MangaPage.ParsedHtml.querySelector('#combobox > option.selected').innerText; Write-Host $ChapterNumber; $PageNumber=$MangaPage.ParsedHtml.querySelector('#pageSelect > option.selected').innerText; Write-Host $PageNumber; $URLImage=$MangaPage.ParsedHtml.querySelector('#mainImg').src.replace('about:', 'https:'); Write-Host $URLImage; $FileExtension=$URLImage.SubString($URLImage.lastIndexOf('.')+1); Write-Host $FileExtension; $FileName='$.ChapterNumber'+'_'+'$PageNumber'+'_'+'$MangaName'+'.'+'$FileExtension'; $Folder=('$MangaName\$ChapterNumber'); If(!(Test-Path $Folder)) { New-Item -ItemType Directory -Force -Path $Folder }; Invoke-WebRequest $URLImage -OutFile $Folder\$FileName}"
</code>```

Body:
If I start the command from PowerShell it works perfectly instead of CMD this happens:
Imgur Image

PowerShell -NoLogo -NoProfile -Command "$MangaPage=Invoke-WebRequest -Uri %MangaLink%; $MangaName=$MangaPage.ParsedHtml.querySelector('#top-in > div.top-title > span.hideM0 > a').innerText; Write-Host $MangaName; $ChapterNumber=$MangaPage.ParsedHtml.querySelector('#combobox > option.selected').innerText; Write-Host $ChapterNumber; $PageNumber=$MangaPage.ParsedHtml.querySelector('#pageSelect > option.selected').innerText; Write-Host $PageNumber; $URLImage=$MangaPage.ParsedHtml.querySelector('#mainImg').src.replace('about:', 'https:'); Write-Host $URLImage; $FileExtension=$URLImage.SubString($URLImage.lastIndexOf('.')+1); Write-Host $FileExtension; $FileName='$.ChapterNumber'+'_'+'$PageNumber'+'_'+'$MangaName'+'.'+'$FileExtension'; $Folder=('$MangaName\$ChapterNumber'); If(!(Test-Path $Folder)) { New-Item -ItemType Directory -Force -Path $Folder }; Invoke-WebRequest $URLImage -OutFile $Folder\$FileName"

Body:
About PowerShell.exe

When the value of Command is a string, Command must be the last
  parameter specified because any characters typed after the command are
  interpreted as the command arguments.

The Command parameter only accepts a script block for execution when
  it can recognize the value passed to Command as a ScriptBlock type.
  This is only possible when running PowerShell.exe from another
  PowerShell host. The ScriptBlock type may be contained in an existing
  variable, returned from an expression, or parsed by the PowerShell
  host as a literal script block enclosed in curly braces {}, before
  being passed to PowerShell.exe.

In cmd.exe, there is no such thing as a script block (or ScriptBlock
  type), so the value passed to Command will always be a string. You can
  write a script block inside the string, but instead of being executed
  it will behave exactly as though you typed it at a typical PowerShell
  prompt, printing the contents of the script block back out to you.

A string passed to Command will still be executed as PowerShell, so
  the script block curly braces are often not required in the first
  place when running from cmd.exe. To execute an inline script block
  defined inside a string, the call operator & can be used:

console

"& {}"

PowerShell -NoLogo -NoProfile -Command  "&{ $MangaPage=Invoke-WebRequest -Uri %MangaLink%; $MangaName=$MangaPage.ParsedHtml.querySelector('#top-in > div.top-title > span.hideM0 > a').innerText; Write-Host $MangaName; $ChapterNumber=$MangaPage.ParsedHtml.querySelector('#combobox > option.selected').innerText; Write-Host $ChapterNumber; $PageNumber=$MangaPage.ParsedHtml.querySelector('#pageSelect > option.selected').innerText; Write-Host $PageNumber; $URLImage=$MangaPage.ParsedHtml.querySelector('#mainImg').src.replace('about:', 'https:'); Write-Host $URLImage; $FileExtension=$URLImage.SubString($URLImage.lastIndexOf('.')+1); Write-Host $FileExtension; $FileName='$.ChapterNumber'+'_'+'$PageNumber'+'_'+'$MangaName'+'.'+'$FileExtension'; $Folder=('$MangaName\$ChapterNumber'); If(!(Test-Path $Folder)) { New-Item -ItemType Directory -Force -Path $Folder }; Invoke-WebRequest $URLImage -OutFile $Folder\$FileName}"


来源: stackexchange

问:
'data-disable-with' triggering all the buttons on the form
I have two button in a multi-step form: CONTINUE and BACK.

```<code><%= f.button_tag "#{t :Back}", name: 'back_button', id: 'back_button', class: "btn btn-primary", style:"background: #d3f0fe !important; color: #44B5EB !important;", 'data-disable-with' =>"<i class='fa fa-spinner fa-spin'></i> #{t :processing}".html_safe unless @event.first_step? %>

<%= f.button_tag "#{t :Continue}", id: 'submit-all', class: "btn btn-primary", 'data-disable-with' =>"<i class='fa fa-spinner fa-spin'></i> #{t :processing}".html_safe %>
</code>```

I added the following JS to disable one button when the user click on the other one:

```<code>$('#back_button').click( function () {
    var buttons = $('#back_button').not($(this));
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});

$('#submit-all').click( function () {
    var buttons = $('#submit-all').not($(this));
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});
</code>```

but for some reason it does not work and both buttons turn into "Processing" when either one is clicked on.

Does anyone sees something wrong in the code please?

答:
I ended up doing: </p>

```<code>$('#back_button').click( function () {
    var buttons = $('#submit-all');
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});

$('#submit-all').click( function () {
    var buttons = $('#back_button');
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two button in a multi-step form: CONTINUE and BACK.

<%= f.button_tag "#{t :Back}", name: 'back_button', id: 'back_button', class: "btn btn-primary", style:"background: #d3f0fe !important; color: #44B5EB !important;", 'data-disable-with' =>" #{t :processing}".html_safe unless @event.first_step? %>

<%= f.button_tag "#{t :Continue}", id: 'submit-all', class: "btn btn-primary", 'data-disable-with' =>" #{t :processing}".html_safe %>

I added the following JS to disable one button when the user click on the other one:

$('#back_button').click( function () {
    var buttons = $('#back_button').not($(this));
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});

$('#submit-all').click( function () {
    var buttons = $('#submit-all').not($(this));
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});

but for some reason it does not work and both buttons turn into "Processing" when either one is clicked on.

Does anyone sees something wrong in the code please?

Body:
I ended up doing:

$('#back_button').click( function () {
    var buttons = $('#submit-all');
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});

$('#submit-all').click( function () {
    var buttons = $('#back_button');
    buttons.removeAttr('data-disable-with');
    buttons.attr('disabled', true);
});


问:
How to add a scroll view in storyboard visual studio 2019
I have looked everywhere on the internet and can't find the answer to how to add a scroll view in storyboard visual studio 2019. I know that there is a UI scroll view and that your suppose to put a view on top of that although I can't figure it out.</p>

答:
Why don't you use the Xcode to design? Just right click on story board and open with Xcode. And check this basic tutorial of UIscrollview.

https://youtu.be/_Qn3UGad3lg


问:
How do I use the toast feature?
I just started learning Android Studio. I want to display a toast notification by pressing a button on the widget. However, there is an error when using the getApplicationContext() function. Can you tell me how to fix it? Other things, including getBaseContext(), were the same..... The error message was "Cannot resolve method" getApplicationContext () ""  I didn't speak English, so I used Google Translator.... I'm so sorry if you can't understand...

```<code>package com.jhjsapp.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * Implementation of App Widget functionality.
 */
public class TestWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    public void butcli(View view){
        Toast.makeText(getApplicationContext(),"버튼 눌림", Toast.LENGTH_SHORT).show();
    }
}
</code>```

This is JAVA code

enter image description here

答:
You cannot show Toast message using getApplicationContext() because the Widget extends AppWidgetProvider. So you cannot get the current context.

You can try something like this :

```<code>public class testWidget extends AppWidgetProvider{

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

final int N = appWidgetIds.length;

for (int i=0; i<N; i++) {
    int appWidgetId = appWidgetIds[i];

    Intent intent = new Intent(context, MainPage.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
    views.setOnClickPendingIntent(R.id.button1, pendingIntent);

    appWidgetManager.updateAppWidget(appWidgetId, views);
   }
}

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
}
</code>```

Title: How do I use the toast feature?

Body:
I just started learning Android Studio. I want to display a toast notification by pressing a button on the widget. However, there is an error when using the getApplicationContext() function. Can you tell me how to fix it? Other things, including getBaseContext(), were the same..... The error message was "Cannot resolve method" getApplicationContext () ""  I didn't speak English, so I used Google Translator.... I'm so sorry if you can't understand...

package com.jhjsapp.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * Implementation of App Widget functionality.
 */
public class TestWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    public void butcli(View view){
        Toast.makeText(getApplicationContext(),"버튼 눌림", Toast.LENGTH_SHORT).show();
    }
}

This is JAVA code

enter image description here

Body:
You cannot show Toast message using getApplicationContext() because the Widget extends AppWidgetProvider. So you cannot get the current context.

You can try something like this :

public class testWidget extends AppWidgetProvider{

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

final int N = appWidgetIds.length;

for (int i=0; i<N; i++) {
    int appWidgetId = appWidgetIds[i];

    Intent intent = new Intent(context, MainPage.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
    views.setOnClickPendingIntent(R.id.button1, pendingIntent);

    appWidgetManager.updateAppWidget(appWidgetId, views);
   }
}

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
}


问:
how to efficiently find if a linux directory including sudirectories has at least 1 file
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

```<code>find $DIR -type f | head -n 1
</code>```

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file

答:
Try this

```<code>find -type f -printf '%h\n' | uniq
</code>```

The find part finds all files, but prints only the directory.  The uniq part eliminates duplicates.

Pitfall: It doesn't work (like your example) for files containing a NEWLINE in the directory path.

Body:
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

find $DIR -type f | head -n 1

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file

Body:
Try this

find -type f -printf '%h\n' | uniq

The find part finds all files, but prints only the directory.  The uniq part eliminates duplicates.

Pitfall: It doesn't work (like your example) for files containing a NEWLINE in the directory path.


问:
Java IF-ELSE IF-ELSE skipping the if and else if check and prints out else statement automatically
Java 11.6 In this BMI calculator that will take in Person's weight, height and calculate the BMI. The BMI is calculated properly however in the classify BMI method the program skips the if and else if check and just prints out the else statement which is "obese" for every test. Is the loop implemented incorrectly? or the value of BMI is not initiating in the loop. When I print out the BMI, I do see that for every test the BMI does change so that is not a problem.

The PersonWeight.java class

```<code>import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}
</code>```

The test class that has the main method

```<code>import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight PersonWeight = new PersonWeight();
        double bmi = PersonWeight.ComputeBMI();

        if(bmi<18.5) {
            System.out.printf("Underweight");

        }else if (bmi >= 18.5 && bmi<25) {
            System.out.printf("Normal Weight");
        }else if (bmi >=25 && bmi<30) {
            System.out.printf("Overweight");
        }else  {
            System.out.printf("Obese");

        }
    }

        public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

        PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
        classifyBMI();

    }
}
</code>```

答:
The error is here:

```<code>PersonWeight personWeight = new PersonWeight();
double bmi = personWeight.computeBMI();
</code>```

This always returns NaN (Not a number) because you compute on a fresh new object which has only zeroes in it. Division by zero is not allowed, hence the result is NaN. All if-comparisons fail because NaN cannot be compared to any number.

Solution 1: Move the ``classifyBMI()method inside thePersonWeight``` class and use the current class instance attributes (now a new class with zeroes) for the calculation.</p>

<p>Solution 2: Pass the filled <code>PersonWeight``` instance to theclassifyBMI()``` method as an argument and use that for the calculation.</p>

<p>Solution 3: Pass the <code>bmi</code> value to the ``classifyBMI()``` method as an argument and use that for the calculation.

The following code demonstrates all three solutions:

```<code>import java.util.Scanner;

public class Main
{

    public static class PersonWeight
    {
        private double height;
        private double weight;

        public PersonWeight()
        {
            height = 0;
            weight = 0;
        }

        public void setHeight(double h)
        {
            this.height = h;
        }

        public double getHeight()
        {
            return height;
        }

        public void setWeight(double w)
        {
            this.weight = w;
        }

        public double getWeight()
        {
            return weight;
        }

        public double computeBMI()
        {
            double bmi = ((weight) / (height * height));
            return bmi;
        }

        private void classifyBMI1()
        {
            double bmi = ((weight) / (height * height));

            if (bmi < 18.5)
            {
                System.out.println("Underweight");
            }
            else if (bmi >= 18.5 && bmi < 25)
            {
                System.out.println("Normal Weight");
            }
            else if (bmi >= 25 && bmi < 30)
            {
                System.out.println("Overweight");
            }
            else
            {
                System.out.println("Obese");
            }
        }
    }

    private static void classifyBMI2(PersonWeight personWeight)
    {
        double bmi = personWeight.computeBMI();
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    private static void classifyBMI3(double bmi)
    {
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    public static void main(String[] args) throws Exception
    {
        Scanner input = new Scanner(System.in);
        PersonWeight personWeight = new PersonWeight();

        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        personWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        personWeight.setWeight(w);

        System.out.printf("%nHeight: %f%n", personWeight.getHeight());
        System.out.printf("Weight: %f%n", personWeight.getWeight());
        System.out.printf("BMI: %f2%n", personWeight.computeBMI());

        personWeight.classifyBMI1();
        classifyBMI2(personWeight);
        classifyBMI3(personWeight.computeBMI());
    }
}
</code>```

I also fixed other things:

Variable names and method names should start with a small letter. Upper case beginnings are reserved for class name. To print simple strings use println() instead of printf() for better performance. When you use printf() to output variables, then use placeholders like %finstead of string concatenation. Again this provides better performance.

Body:
Java 11.6 In this BMI calculator that will take in Person's weight, height and calculate the BMI. The BMI is calculated properly however in the classify BMI method the program skips the if and else if check and just prints out the else statement which is "obese" for every test. Is the loop implemented incorrectly? or the value of BMI is not initiating in the loop. When I print out the BMI, I do see that for every test the BMI does change so that is not a problem.

The PersonWeight.java class

import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}

The test class that has the main method

import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight PersonWeight = new PersonWeight();
        double bmi = PersonWeight.ComputeBMI();

        if(bmi<18.5) {
            System.out.printf("Underweight");

        }else if (bmi >= 18.5 && bmi<25) {
            System.out.printf("Normal Weight");
        }else if (bmi >=25 && bmi<30) {
            System.out.printf("Overweight");
        }else  {
            System.out.printf("Obese");

        }
    }

        public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

        PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
        classifyBMI();

    }
}

Body:
The error is here:

PersonWeight personWeight = new PersonWeight();
double bmi = personWeight.computeBMI();

This always returns NaN (Not a number) because you compute on a fresh new object which has only zeroes in it. Division by zero is not allowed, hence the result is NaN. All if-comparisons fail because NaN cannot be compared to any number.

Solution 1: Move the ``classifyBMI()method inside thePersonWeight``` class and use the current class instance attributes (now a new class with zeroes) for the calculation.</p>

<p>Solution 2: Pass the filled <code>PersonWeight``` instance to theclassifyBMI()``` method as an argument and use that for the calculation.</p>

<p>Solution 3: Pass the <code>bmi</code> value to the ``classifyBMI()``` method as an argument and use that for the calculation.

The following code demonstrates all three solutions:

import java.util.Scanner;

public class Main
{

    public static class PersonWeight
    {
        private double height;
        private double weight;

        public PersonWeight()
        {
            height = 0;
            weight = 0;
        }

        public void setHeight(double h)
        {
            this.height = h;
        }

        public double getHeight()
        {
            return height;
        }

        public void setWeight(double w)
        {
            this.weight = w;
        }

        public double getWeight()
        {
            return weight;
        }

        public double computeBMI()
        {
            double bmi = ((weight) / (height * height));
            return bmi;
        }

        private void classifyBMI1()
        {
            double bmi = ((weight) / (height * height));

            if (bmi < 18.5)
            {
                System.out.println("Underweight");
            }
            else if (bmi >= 18.5 && bmi < 25)
            {
                System.out.println("Normal Weight");
            }
            else if (bmi >= 25 && bmi < 30)
            {
                System.out.println("Overweight");
            }
            else
            {
                System.out.println("Obese");
            }
        }
    }

    private static void classifyBMI2(PersonWeight personWeight)
    {
        double bmi = personWeight.computeBMI();
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    private static void classifyBMI3(double bmi)
    {
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    public static void main(String[] args) throws Exception
    {
        Scanner input = new Scanner(System.in);
        PersonWeight personWeight = new PersonWeight();

        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        personWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        personWeight.setWeight(w);

        System.out.printf("%nHeight: %f%n", personWeight.getHeight());
        System.out.printf("Weight: %f%n", personWeight.getWeight());
        System.out.printf("BMI: %f2%n", personWeight.computeBMI());

        personWeight.classifyBMI1();
        classifyBMI2(personWeight);
        classifyBMI3(personWeight.computeBMI());
    }
}

I also fixed other things:

Variable names and method names should start with a small letter. Upper case beginnings are reserved for class name. To print simple strings use println() instead of printf() for better performance. When you use printf() to output variables, then use placeholders like %finstead of string concatenation. Again this provides better performance.


问:
What is XV6 operating system used for?
I have been taking online courses on Operating systems, and I heard them say, that XV6 operating system can be used learn implementation of operating systems, thats all.But after I searched on the internet there aren't enough resources, which would get me started with it.
My question is, why should I use it,and how will it help me in understanding operating system.
(Please be gentle with information you throw at me, I am a newbie :( )

Any effort is appreciated

答:
There are only 2 possibilities:

too complex to be useful for teaching

too simple to be useful for teaching

Things like fancy features/enhanced functionality, mitigating security issues, dealing with hardware bugs/errata, performance, scalability and supporting a very wide range of different hardware all increase the complexity of the code; and if you look at a real commercial OS (e.g. Linux maybe) that has to care about all of these things it's hard to learn about one thing (e.g. memory management) without all the complexity getting in the way and making it significantly harder to learn.

If you have a simple OS that does none of those things (no fancy features, no mitigation of security issues, ...) then it's much much easier to learn basic principles from it; but it also becomes impossible to use it to learn about fancy features, mitigating security issues, dealing with hardware bugs/errata, ...

The solution is to start with a simple OS (e.g. XV6) to learn the basics, then switch to a real OS later to learn everything else.

However; most OS courses at Universities are not intended to teach you about writing an OS. Instead they're intended to give you basic information about operating systems so that you can use that knowledge when writing application programs for existing operating systems. For that reason (and because there's time constraints) they only do the first part (with a simple OS like XV6) and then the course finishes.

Title: What is XV6 operating system used for?


问:
Prometheus python client error Address already in use
I'm running a web app with address 127.0.0.1:5000 and am using the python client library for Prometheus. I use start_http_server(8000) from the example in their docs to expose the metrics on that port. The application runs, but I get [Errno 48] Address already in use and the localhost:8000 doesn't connect to anything when I try hitting it.

If I can't start two servers from one web app, then what port should I pass into start_http_server() in order to expose the metrics?

There is nothing already running on either port before I start the app.

答: Maybe your 8000 port is occupied. You can change it to another port, such as 8001</p>

ContentLicense: CC BY-SA 3.0


问:
How can I check if an element exists on a page using Selenium XPath?
I'm writing a script in to do some webscraping on my Firebase for a few select users. After accessing the events page for a user, I want to check for the condition that no events have been logged by that user first.

For this, I am using Selenium and Python. Using XPath seems to work fine for locating links and navigation in all other parts of the script, except for accessing elements in a table. At first, I thought I might have been using the wrong XPath expression, so I copied the path directly from Chrome's inspection window, but still no luck.

As an alternative, I have tried to copy the page source and pass it into Beautiful Soup, and then parse it there to check for the element. No luck there either.

Here's some of the code, and some of the HTML I'm trying to parse. Where am I going wrong?

```<code># Using WebDriver - always triggers an exception
def check_if_user_has_any_data():
try:
    time.sleep(10)
    element = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="event-table"]/div/div/div[2]/mobile-table/md-whiteframe/div[1]/ga-no-data-table/div')))
    print(type(element))
    if element == True:
        print("Found empty state by copying XPath expression directly. It is a bit risky, but it seems to have worked")
    else:
        print("didn’t find empty state")
except:
    print("could not find the empty state element", EC)

# Using Beautiful Soup
def check_if_user_has_any_data#2():
    time.sleep(10)
    html = driver.execute_script("return document.documentElement.outerHTML")
    soup = BeautifulSoup(html, 'html.parser')
    print(soup.text[:500])
    print(len(soup.findAll('div', {"class": "table-row-no-data ng-scope"})))
</code>```

HTML

```

The first version triggers the exception and is expected to evaluate 'element' as True. Actual, the element is not found.

The second version prints the first 500 characters (correctly, as far as I can tell), but it returns '0'. It is expected to return '1' after inspecting the page source.

答:
If you're using Python and Selenium, you can use this:</p>
```<code>try:
    driver.find_element_by_xpath("<Full XPath expression>") # Test the element if exist
    # <Other code>
except:
    # <Run these if element doesn't exist>
</code>```

Body:
I'm writing a script in to do some webscraping on my Firebase for a few select users. After accessing the events page for a user, I want to check for the condition that no events have been logged by that user first.

For this, I am using Selenium and Python. Using XPath seems to work fine for locating links and navigation in all other parts of the script, except for accessing elements in a table. At first, I thought I might have been using the wrong XPath expression, so I copied the path directly from Chrome's inspection window, but still no luck.

As an alternative, I have tried to copy the page source and pass it into Beautiful Soup, and then parse it there to check for the element. No luck there either.

Here's some of the code, and some of the HTML I'm trying to parse. Where am I going wrong?

# Using WebDriver - always triggers an exception
def check_if_user_has_any_data():
try:
    time.sleep(10)
    element = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="event-table"]/div/div/div[2]/mobile-table/md-whiteframe/div[1]/ga-no-data-table/div')))
    print(type(element))
    if element == True:
        print("Found empty state by copying XPath expression directly. It is a bit risky, but it seems to have worked")
    else:
        print("didn’t find empty state")
except:
    print("could not find the empty state element", EC)

# Using Beautiful Soup
def check_if_user_has_any_data#2():
    time.sleep(10)
    html = driver.execute_script("return document.documentElement.outerHTML")
    soup = BeautifulSoup(html, 'html.parser')
    print(soup.text[:500])
    print(len(soup.findAll('div', {"class": "table-row-no-data ng-scope"})))

HTML

The first version triggers the exception and is expected to evaluate 'element' as True. Actual, the element is not found.

The second version prints the first 500 characters (correctly, as far as I can tell), but it returns '0'. It is expected to return '1' after inspecting the page source.

Body:
If you're using Python and Selenium, you can use this:

try:
    driver.find_element_by_xpath("<Full XPath expression>") # Test the element if exist
    # <Other code>
except:
    # <Run these if element doesn't exist>


问:
I can't compile opencv samples with VS2010 on vista
I am using visual studio 2010 on windows vista. I want to compile a sample file of OPENCV named "find_obj.cpp" created by liuliu.

Here is the address of source code.

https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/find_obj.cpp

Other opencv codes works well but I couldn't compile this. please help

I've installed all of the libraries needed and opencv. Other opencv projects of mine are working fine.

My error is "unresolved externals"
here it is,

Error  14  error LNK1120: 11 unresolved externals

  Error   4   error LNK2019: unresolved external symbol "class cvflann::Logger & __cdecl cvflann::logger(void)" (?logger@cvflann@@YAAAVLogger@1@XZ) referenced in function "public: virtual void __thiscall cvflann::KDTreeIndexParams::print(void)const " (?print@KDTreeIndexParams@cvflann@@UBEXXZ

答: What compiler errors do you get? Have you installed OpenCV and linked the appropriate libraries?</p>


问:
Unable to create requested service [org.hibernate.cache.spi.RegionFactory] - Hibernate 4.3.8
I have started using Hibernate 4.3.8 and was trying out a basic program to insert and retrieve a user. Below are my files.

hibernate.cfg.xml

```<code><?xml version='1.0' encoding='utf-8'?>
</code>```

```<code><session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/mywork</property>
    <property name="connection.username">****</property>
    <property name="connection.password">*****</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <property name="cache.use_query_cache">true</property>
    <property name="cache.use_second_level_cache">true</property>
    <property name="cache.use_structured_entries">true</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <mapping class="com.parvez.hibernate.model.User"/>

</session-factory>
</code>```

Java Code
HB2Test.java

```<code>package com.parvez.hibernate.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HB2Test {

    private static SessionFactory sessionFactory;
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        User myUser = new User();
        myUser.setUserId(1);
        myUser.setUserName("Superman");

        /*StandardServiceRegistryBuilder builder = new    StandardServiceRegistryBuilder();

        //create session factory
        Configuration configuration = new Configuration();
        SessionFactory sessionFactory = configuration.configure().
                    buildSessionFactory(builder.applySettings(configuration.getProperties()).build());

        Session session = sessionFactory.openSession();
     */

    Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();

        sessionFactory =     configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.save(myUser);

        session.getTransaction().commit();
        session.close();
    }

}
</code>```

The error that I get is

```<code>INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2444)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2440)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at com.parvez.hibernate.model.HB2Test.main(HB2Test.java:37)
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.EhCacheRegionFactory]
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251)
... 7 more
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.cache.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87)
... 10 more
</code>```

I have tried different ways of initializing the SessionFactory, but nothing seems to work. I am using Hibernate 4.3.8-Final

Thanks in advance

答:
Disable the caching as shown below by modifying the property in hibernate.cfg.xml:</p>

```<code><property name="hibernate.cache.use_query_cache">false</property>
</code>```

Body:
I have started using Hibernate 4.3.8 and was trying out a basic program to insert and retrieve a user. Below are my files.

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/mywork</property>
    <property name="connection.username">****</property>
    <property name="connection.password">*****</property>

    <property name="connection.pool_size">1</property>

    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>

    <property name="current_session_context_class">thread</property>

    <property name="cache.use_query_cache">true</property>
    <property name="cache.use_second_level_cache">true</property>
    <property name="cache.use_structured_entries">true</property>

    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <mapping class="com.parvez.hibernate.model.User"/>

</session-factory>

Java Code
HB2Test.java

package com.parvez.hibernate.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HB2Test {

    private static SessionFactory sessionFactory;
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        User myUser = new User();
        myUser.setUserId(1);
        myUser.setUserName("Superman");

        /*StandardServiceRegistryBuilder builder = new    StandardServiceRegistryBuilder();

        //create session factory
        Configuration configuration = new Configuration();
        SessionFactory sessionFactory = configuration.configure().
                    buildSessionFactory(builder.applySettings(configuration.getProperties()).build());

        Session session = sessionFactory.openSession();
     */

    Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();

        sessionFactory =     configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.save(myUser);

        session.getTransaction().commit();
        session.close();
    }

}

The error that I get is

INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2444)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2440)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at com.parvez.hibernate.model.HB2Test.main(HB2Test.java:37)
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.EhCacheRegionFactory]
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251)
... 7 more
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.cache.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87)
... 10 more

I have tried different ways of initializing the SessionFactory, but nothing seems to work. I am using Hibernate 4.3.8-Final

Thanks in advance

Body:
Disable the caching as shown below by modifying the property in hibernate.cfg.xml:

<property name="hibernate.cache.use_query_cache">false</property>


问:
How to delete a field from UI by clicking its respective delete icon - Angular
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

```<code><div  [formGroup]="parentForm">
  <mat-form-field >
    <div class="delete-icon" *ngIf="showDeleteIcon" (click)="removeIncomeField($event, i)">
      <img src="/assets/icons/delete_income.png"></div>

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>
</div>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>
</code>```

答:
You can add for each field specific id like this:

<mat-form-field id="name>...</mat-form-field>
and then delete the field with pure javascript with

document.getElementById('name').remove()

but IMO just add another variables to hidden the element then check the variables when the save function happen.

Body:
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

  <mat-form-field >

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>


问:
Font?) -> some View. But why when adding modifier at siwftUI we use in this way: ext("Hello, World!").font(.body)? Why we add dot ' . '?
In the Apple Developer documentation, the font modifier is said to be declared like this:

func font(_ font: Font?) -> some View
```

<p>But when calling it as a modifier in SwiftUI, we use in this way: </p>

<pre class="lang-swift prettyprint-override"><code>Text("Hello, World!").font(.body)
//                         ↑
//          Why do we add this dot?

</code>```

Why do we add that dot before body?

答:
Declaration

```<code>struct Font
</code>```

The system resolves a font’s value at the time it uses the font in a given environment because Font is a late-binding token.

you can get standard fonts via Font static properties

```<code>static let largeTitle: Font
static let title: Font
static var headline: Font
static var subheadline: Font
static var body: Font
static var callout: Font
static var caption: Font
static var footnote: Font
</code>```

Writing

```<code>Text("some text").font(.title)
</code>```

is the same as

```<code>Text("some text").font(Font.title)
</code>```

Body:
In the Apple Developer documentation, the font modifier is said to be declared like this:

func font(_ font: Font?) -> some View

But when calling it as a modifier in SwiftUI, we use in this way:

Text("Hello, World!").font(.body)
//                         ↑
//          Why do we add this dot?

Why do we add that dot before body?

Body:
Declaration

struct Font

The system resolves a font’s value at the time it uses the font in a given environment because Font is a late-binding token.

you can get standard fonts via Font static properties

static let largeTitle: Font
static let title: Font
static var headline: Font
static var subheadline: Font
static var body: Font
static var callout: Font
static var caption: Font
static var footnote: Font

Writing

Text("some text").font(.title)

is the same as

Text("some text").font(Font.title)


问:
Find object by match property in nested array
I'm not seeing a way to find objects when my condition would involve a nested array.

```<code>var modules = [{
    name: 'Module1',
    submodules: [{
        name: 'Submodule1',
        id: 1
      }, {
        name: 'Submodule2',
        id: 2
      }
    ]
  }, {
    name: 'Module2',
    submodules: [{
        name: 'Submodule1',
        id: 3
      }, {
        name: 'Submodule2',
        id: 4
      }
    ]
  }
];
</code>```

This won't work because submodules is an array, not an object. Is there any shorthand that would make this work? I'm trying to avoid iterating the array manually.

```<code>_.where(modules, {submodules:{id:3}});
</code>```

答:
I looked into this and I think the best option is to use Deepdash.  It's a collection of methods to do deeply filter, find etc.

Sure it would be possible with lodash alone but with Deepdash it's easier.

I tried to convert the previous answer to the latest Lodash version but that was not working. Every method was deprecated in v4 of Lodash. Possible replacements: select = map or filter, any = some, where = filter)

findDeep returns an object with some information to the found item (just some values, see the docs for more details):

value is the object found

key that's the index in the nested array

parent the parent of the value

So the code for the findDeep looks like:

const modules = [{
  name: 'Module1',
  submodules: [{
    name: 'Submodule1',
    id: 1
  }, {
    name: 'Submodule2',
    id: 2
  }]
}, {
  name: 'Module2',
  submodules: [{
    name: 'Submodule1',
    id: 3
  }, {
    name: 'Submodule2',
    id: 4
  }]
}];

const getModule = (modules, id) =>
  _.findDeep(modules, module => module.id === id, {
    childrenPath: "submodules"
  });

const resultEl = document.getElementById("result");
const foundModule = getModule(modules, 3).value;

resultEl.innerText = JSON.stringify(foundModule, null, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script>
  deepdash(_);
</script>

<h2>Example to get module with id = 3</h2>
<pre id="result">``````

Body:
I'm not seeing a way to find objects when my condition would involve a nested array.

var modules = [{
    name: 'Module1',
    submodules: [{
        name: 'Submodule1',
        id: 1
      }, {
        name: 'Submodule2',
        id: 2
      }
    ]
  }, {
    name: 'Module2',
    submodules: [{
        name: 'Submodule1',
        id: 3
      }, {
        name: 'Submodule2',
        id: 4
      }
    ]
  }
];

This won't work because submodules is an array, not an object. Is there any shorthand that would make this work? I'm trying to avoid iterating the array manually.

_.where(modules, {submodules:{id:3}});

Body:
I looked into this and I think the best option is to use Deepdash.  It's a collection of methods to do deeply filter, find etc.

Sure it would be possible with lodash alone but with Deepdash it's easier.

I tried to convert the previous answer to the latest Lodash version but that was not working. Every method was deprecated in v4 of Lodash. Possible replacements: select = map or filter, any = some, where = filter)

findDeep returns an object with some information to the found item (just some values, see the docs for more details):

value is the object found

key that's the index in the nested array

parent the parent of the value

So the code for the findDeep looks like:

const modules = [{
  name: 'Module1',
  submodules: [{
    name: 'Submodule1',
    id: 1
  }, {
    name: 'Submodule2',
    id: 2
  }]
}, {
  name: 'Module2',
  submodules: [{
    name: 'Submodule1',
    id: 3
  }, {
    name: 'Submodule2',
    id: 4
  }]
}];

const getModule = (modules, id) =>
  _.findDeep(modules, module => module.id === id, {
    childrenPath: "submodules"
  });

const resultEl = document.getElementById("result");
const foundModule = getModule(modules, 3).value;

resultEl.innerText = JSON.stringify(foundModule, null, 2);

<script src="https://cdn.jsdelivr.net/npm/deepdash/browser/deepdash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script>
  deepdash(_);
</script>

<h2>Example to get module with id = 3</h2>
<pre id="result"></pre>


问:
How to check if AlertDialog.builder is showing and cancelling it if its showing?
Here is my code -</p>

```<code>View layout = LayoutInflater.from(this).inflate(R.layout.dialog_loc_info, null);
final Button mButton_Mobile = (Button) layout.findViewById(R.id.button);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
mButton_Mobile.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        if(builder.)
            showDialog(); // this is another dialog, nothing to do with this code
        }
    });
builder.setNeutralButton(getString(android.R.string.ok),
                         new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
builder.show();
</code>```

答:
For fullscreen dialog, I check if an instance of it is already being shown at android.R.id.content and then replace() it:

```<code>public void showMyDialog(
        String someArgument1,
        String someArgument2
) {
    MyDialog dialog = MyDialog.newInstance(
            someArgument1,
            someArgument2
    );

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    Fragment content = getSupportFragmentManager().findFragmentById(android.R.id.content);
    if (content instanceof MyDialog) {
        // An instance of MyDialog is already displayed! Replace it
        t.replace(android.R.id.content, dialog).commitAllowingStateLoss();
    } else {
        t.add(android.R.id.content, dialog).commitAllowingStateLoss();
    }
}
</code>```

And here is my custom fullscreen dialog with no title bar:

```<code>public class MyDialog extends AppCompatDialogFragment {

    public static MyDialog newInstance(
            String someArgument1,
            String someArgument2) {
        MyDialog dialog = new MyDialog();
        Bundle args = new Bundle();
        args.putInt("arg1", someArgument1);
        args.putInt("arg2", someArgument2);
        dialog.setArguments(args);
        return dialog;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.my_dialog_layout, container, false);
        // do whatever you want with the strings
        // like displaying them in TextViews
        String arg1 = getArguments().getString("arg1");
        String arg2 = getArguments().getString("arg2");
        return v;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
</code>```

Body:
Here is my code -

View layout = LayoutInflater.from(this).inflate(R.layout.dialog_loc_info, null);
final Button mButton_Mobile = (Button) layout.findViewById(R.id.button);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
mButton_Mobile.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        if(builder.)
            showDialog(); // this is another dialog, nothing to do with this code
        }
    });
builder.setNeutralButton(getString(android.R.string.ok),
                         new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
builder.show();

Body:
For fullscreen dialog, I check if an instance of it is already being shown at android.R.id.content and then replace() it:

public void showMyDialog(
        String someArgument1,
        String someArgument2
) {
    MyDialog dialog = MyDialog.newInstance(
            someArgument1,
            someArgument2
    );

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    Fragment content = getSupportFragmentManager().findFragmentById(android.R.id.content);
    if (content instanceof MyDialog) {
        // An instance of MyDialog is already displayed! Replace it
        t.replace(android.R.id.content, dialog).commitAllowingStateLoss();
    } else {
        t.add(android.R.id.content, dialog).commitAllowingStateLoss();
    }
}

And here is my custom fullscreen dialog with no title bar:

public class MyDialog extends AppCompatDialogFragment {

    public static MyDialog newInstance(
            String someArgument1,
            String someArgument2) {
        MyDialog dialog = new MyDialog();
        Bundle args = new Bundle();
        args.putInt("arg1", someArgument1);
        args.putInt("arg2", someArgument2);
        dialog.setArguments(args);
        return dialog;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.my_dialog_layout, container, false);
        // do whatever you want with the strings
        // like displaying them in TextViews
        String arg1 = getArguments().getString("arg1");
        String arg2 = getArguments().getString("arg2");
        return v;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }


问:
make the first tab the active tab when open a bootstrap modal
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

```<code> // the button that will open the bootstrap modal
            <div>
            <a href="#"  class="popupLink" data-toggle="modal" data-target="#yDetailsModal">
            </a>
            </div>

// bootstrap modal

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true" >

 <div class="modal-dialog modal-details" role="document">

  <div class="modal-content modal-details">

   <div class="modal-header">

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

  </div>

 <div class="modal-body">
  <div class=" tabs-left" id= "modal-tabs">
   <ul class="nav nav-tabs">

   <li class="active">
   <a href="#personal"  data-toggle="tab"></a></li>

  <li>
   <a  href="#promotion" data-toggle="tab"> </a> </li>
    <li>
    <a  href="#vacation" data-toggle="tab"> </a> </li>

</ul>
 </div>

<div class="tab-content" id="tab-content">
 <div class="tab-pane active" id="personalInformation">
  <div>
   <ul>
     <li>

      <span> this is a personal information</span>
      </li>
</ul>
</div>
</div>

</code>```

答:
Just use the Bootstrap default methods modal and tab

$('#MyDetailsModal').on('show.bs.modal', function (event) {
    $(this).find('.nav a:first').tab('show');
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div>
    MyDetailsModal

</div>

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true">
    <div class="modal-dialog modal-details" role="document">
        <div class="modal-content modal-details">
            <div class="modal-header">
                <button type="button" class="close close-button" data-dismiss="modal" aria-label="Close" id="btnId"> </button>
            </div>

            <div class="modal-body">
                <div class=" tabs-left" id="modal-tabs">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            personal
                        </li>
                        <li>
                            promotion
                        </li>
                        <li>
                            vacation
                        </li>
                    </ul>
                </div>

                <div class="tab-content" id="tab-content">
                    <div class="tab-pane active" id="personal">
                        this is a personal information
                    </div>
                    <div class="tab-pane" id="promotion">
                        this is a promotion information
                    </div>
                    <div class="tab-pane" id="vacation">
                        this is a vacation information
                    </div>
                </div>
            </div>
        </div>
    </div>
</div></code>```

Body:
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

 // the button that will open the bootstrap modal

// bootstrap modal

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

       this is a personal information

Body:
Just use the Bootstrap default methods modal and tab

$('#MyDetailsModal').on('show.bs.modal', function (event) {
    $(this).find('.nav a:first').tab('show');
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div>
    <a href="#" class="popupLink btn btn-info btn-lg" data-toggle="modal" data-target="#MyDetailsModal">MyDetailsModal
    </a>
</div>

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true">
    <div class="modal-dialog modal-details" role="document">
        <div class="modal-content modal-details">
            <div class="modal-header">
                <button type="button" class="close close-button" data-dismiss="modal" aria-label="Close" id="btnId"> </button>
            </div>

            <div class="modal-body">
                <div class=" tabs-left" id="modal-tabs">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#personal" data-toggle="tab">personal</a>
                        </li>
                        <li>
                            <a href="#promotion" data-toggle="tab">promotion</a>
                        </li>
                        <li>
                            <a href="#vacation" data-toggle="tab">vacation</a>
                        </li>
                    </ul>
                </div>

                <div class="tab-content" id="tab-content">
                    <div class="tab-pane active" id="personal">
                        this is a personal information
                    </div>
                    <div class="tab-pane" id="promotion">
                        this is a promotion information
                    </div>
                    <div class="tab-pane" id="vacation">
                        this is a vacation information
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


问:
How to label or categorize git commits
I have a number of pieces of information that I would like to add to a commit. This information is for both automated and manual processes. Examples include a team's name, a status (generated, development, configuration, etc), or a ticket number.

Is there a way to add this information to the commits or do I have to tag akin to TICKET-1234:<HASH>?

答:
There are a number of available options:

If all you want is to short, memorable name for a commit, you can simply tag it using git tag. A tag object points to a commit and contains an additional message, and is itself named by a ref with a prefix of refs/tags/. By default, the fetch and push operations will not synchronise tags with a remote repository unless you pass --tags.

If you need to store information at commit creation time, you can include it at the bottom of the the commit message in RFC822-like header:

```<code>Fixes: ticket #1234
</code>```

The git commit command even provides a built-in --signoff option that adds one such header automatically.

If you need to store longer-form information that changes over time, take a look at git notes:

Adds, removes, or reads notes attached to objects, without touching the objects themselves.

By default, notes are saved to and read from refs/notes/commits, but this default can be overridden. See the OPTIONS, CONFIGURATION, and ENVIRONMENT sections below. If this ref does not exist, it will be quietly created when it is first needed to store a note.

A typical use of notes is to supplement a commit message without changing the commit itself. Notes can be shown by git log along with the original commit message. To distinguish these notes from the message stored in the commit object, the notes are indented like the message, after an unindented line saying "Notes (<refname>):" (or "Notes:" for refs/notes/commits).

Like tags, by default refs with the refs/notes/ prefix are not synchronised by fetch and push operations. You'd have to additionally configure git to keep track of them.

Title: How to label or categorize git commits

Body:
There are a number of available options:

If all you want is to short, memorable name for a commit, you can simply tag it using git tag. A tag object points to a commit and contains an additional message, and is itself named by a ref with a prefix of refs/tags/. By default, the fetch and push operations will not synchronise tags with a remote repository unless you pass --tags.

If you need to store information at commit creation time, you can include it at the bottom of the the commit message in RFC822-like header:

Fixes: ticket #1234

The git commit command even provides a built-in --signoff option that adds one such header automatically.

If you need to store longer-form information that changes over time, take a look at git notes:

Adds, removes, or reads notes attached to objects, without touching the objects themselves.

By default, notes are saved to and read from refs/notes/commits, but this default can be overridden. See the OPTIONS, CONFIGURATION, and ENVIRONMENT sections below. If this ref does not exist, it will be quietly created when it is first needed to store a note.

A typical use of notes is to supplement a commit message without changing the commit itself. Notes can be shown by git log along with the original commit message. To distinguish these notes from the message stored in the commit object, the notes are indented like the message, after an unindented line saying "Notes (<refname>):" (or "Notes:" for refs/notes/commits).

Like tags, by default refs with the refs/notes/ prefix are not synchronised by fetch and push operations. You'd have to additionally configure git to keep track of them.


问:
XMLHttpRequest | Sending a request by hand gets me a response of 2111 characters but using XMLHttpRequest the response has a lenght of 179
I basically copy-pasted the MDN code, and I triple checked the URL. I can't find the reason as to why the responses differ.
For reference, here is my code:
Edit: Didn't see cookies got sent, I'm sorry

function getUsernames(str) {
  console.log(str)
}
function reqListener() {
  alert(getUsernames(this.responseText));
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%2217199917378%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A24%7D");
oReq.responseType = "arraybuffer";
oReq.send();

oReq.onload = function(e) {
  var arraybuffer = oReq.response; // not responseText
  console.log(arraybuffer)
  /* ... */
}```

答:
Okay, so I just found out that in the headers cookies got send. After clearing my cookies, I got the same result as the program.
I thank you all for your participation!</p>


问:
Starting binary input with 0s in a cell
First up, I'm not sure if this is the right place to ask this or not, so if it's not please let me know.

Ok so,I'm working on a project that deals with numbers in the binary format as inputs, however, when the input let's say begins with "00" or any number of 0s, it discards it in Excel so I was wondering how to force excel to accept 0s at the beginning of a binary input

答:
An old post, still:

I was having the same issue (with IP numbers) and found a different solution:

In one cell you do the conversion: =DE2BIN(10)

In the other cell you format it with TEXT formula: =TEXT($A$1,"00000000").

Title: Starting binary input with 0s in a cell


问:
Unchecking Checkboxes in Google Sheets
For the life of me I can't figure out how set it up.  I would like the function to check the entire sheet... alternatively I do know which specific ranges (B5:B26; G5:G26...AF5:AF26) on a specific sheet, if i can't set it up for the entire sheet... </p>

```<code>function setFalse()
{
var sheet = SpreadsheetApp.getSheetByName("Test");
var dataRange = sheet.getRange('A:AN28');
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++)
{
  for (var j = 0; j < values[i].length; j++)
  {
    if (values[i][j] == true)
    {
      values[i][j] = false; // Modified
    }
  }
}
dataRange.setValues(values);

};
</code>```

答:
There's a built-in method to uncheck called uncheck(). You can effectively  apply it to the sheet by using getDataRange().

```<code>function setFalse() {
  SpreadsheetApp.getActive().getSheetByName("Test").getDataRange().uncheck();
};
</code>```

Lastly, looking at your original code, don't forget to get a spreadsheet file before selecting the sheet.

Title: Unchecking Checkboxes in Google Sheets

Body:
For the life of me I can't figure out how set it up.  I would like the function to check the entire sheet... alternatively I do know which specific ranges (B5:B26; G5:G26...AF5:AF26) on a specific sheet, if i can't set it up for the entire sheet...

function setFalse()
{
var sheet = SpreadsheetApp.getSheetByName("Test");
var dataRange = sheet.getRange('A:AN28');
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++)
{
  for (var j = 0; j < values[i].length; j++)
  {
    if (values[i][j] == true)
    {
      values[i][j] = false; // Modified
    }
  }
}
dataRange.setValues(values);

};

Body:
There's a built-in method to uncheck called uncheck(). You can effectively  apply it to the sheet by using getDataRange().

function setFalse() {
  SpreadsheetApp.getActive().getSheetByName("Test").getDataRange().uncheck();
};

Lastly, looking at your original code, don't forget to get a spreadsheet file before selecting the sheet.


Title: sort dataframe by other dataframe

Body:
Given a  df's
knn_df

           0          1         2          3
0  1.1565523   1.902790  1.927971  1.1530536
1   1.927971  1.1565523  1.815097  1.1530536
2   1.902790  1.1565523  1.815097   1.927971
3   1.815097   1.927971  1.902790  1.1530536
4   1.902790  1.1565523  1.815097  1.1530536

dates_df

    0   1   2   3
0   2011-11-14 02:30:00.601 2003-08-12 00:00:00.000 2003-11-30 23:00:00.000 2011-10-25 12:00:00.000
1   2003-11-30 23:00:00.000 2011-11-14 02:30:00.601 2002-08-06 00:00:00.000 2011-10-25 12:00:00.000
2   2003-08-12 00:00:00.000 2011-11-14 02:30:00.601 2002-08-06 00:00:00.000 2003-11-30 23:00:00.000
3   2002-08-06 00:00:00.000 2003-11-30 23:00:00.000 2003-08-12 00:00:00.000 2011-10-25 12:00:00.000
4   2003-08-12 00:00:00.000 2011-11-14 02:30:00.601 2002-08-06 00:00:00.000 2011-10-25 12:00:00.000

I have to sort the values of knn_df be the dates of the dates_df.

Every row in dates_df correspond to row in knn_df

I tried to sort like this.

np.argsort(dates_df.values,axis=1)[:,::-1]

array([[0, 3, 2, 1],
       [1, 3, 0, 2],
       [1, 3, 0, 2],
       [3, 1, 2, 0],
       [1, 3, 0, 2]])

Which give the right order of the values by columns, But when i tried to reorder

Sorted_knn = (knn_df.values[np.arange(len(knn_df)),
                        np.argsort(dates_df.values,axis=1)[:,::-1]])

I get an error

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (5,) (5,4)

I am missing something...

Body:
Add [:, None] for making two-dimensional 5x1 array for correct broadcasting:

a = np.argsort(dates_df.values,axis=1)[:,::-1]
b = knn_df.values[np.arange(len(knn_df))[:, None], a]
print (b)
[[1.1565523 1.1530536 1.927971  1.90279  ]
 [1.1565523 1.1530536 1.927971  1.815097 ]
 [1.1565523 1.927971  1.90279   1.815097 ]
 [1.1530536 1.927971  1.90279   1.815097 ]
 [1.1565523 1.1530536 1.90279   1.815097 ]]


问:
How to Customise default Alert in xamarin forms
I am trying to change the colour of Alert Buttons.

my alert like below.

```<code>await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");
</code>```

I need to make Yes button Red both Android and iOS.

I need to get default alert view for both platform rather than creating a custom pop up.

is there any way to write a renderer for this?

答: If you need exact visual effect on both platforms you must write custom renderer, because DisplayAlert is not rendered by XF.</p>

Body:
I am trying to change the colour of Alert Buttons.

my alert like below.

await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");

I need to make Yes button Red both Android and iOS.

I need to get default alert view for both platform rather than creating a custom pop up.

is there any way to write a renderer for this?


问:
Can I re-construct the original JavaScript source file from a minified version and the corresponding source-map file?
I am working on a project where I have to statically analyse JavaScript code. However, for a few libraries, I only have access to a minified version of the file and the corresponding source-map. Is there a method/technique with which I can generate the original file using these files?</p>

答:
If your objective is "just" to do a onetime re-construction of the original source code I did it using:

Online Source Visualization

use the "Custom" option

upload compiled file

upload source map file

Depending on filesize it may take a while to view the results.

The correspoding Repo is here


问:
ecto changeset add assoc for existing
Good morning! I've reached a moment where I'm struggling. To summarize, I'm trying to create a schema/model that has an association where the associated schema/model already exists. Every example I've found looks more like Rails nested attributes. Here is my various code thingses:

The schema (& its changeset function) with the associations:

```<code>schema "payor_procedure_mappings" do
  belongs_to :payor, Payor
  belongs_to :procedure, Procedure
  field :payor_procedure_name, :string
  field :payor_procedure_id, :string

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
  |> cast_assoc(:payor, params[:payor])  # <--- LINE 50 from stacktrace
end

defp required do
  :payor_procedure_name,
  :payor_procedure_id
]
</code>```

The pre-existing schema I want to associate with that:

```<code>schema "payors" do
  field :name, :string, null: :false
  field :polling_url, :string, null: :false

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end
</code>```

Here's the code where I'm attempting to set the association:

```<code>test "valid if all required params are present", %{procedure: procedure, payor: payor} do
  params = %{
    payor: payor,
    payor_procedure_name: "That one thing we do to patients",
    payor_procedure_id: "2342"
  }

changeset =
  %PayorProcedureMapping{}
  |> PayorProcedureMapping.changeset(params)   # THIS IS LINE 28 from stacktrace

  assert changeset.valid?
end
</code>```

(Please note that the payor in the second argument to the test function is an already loaded schema/model struct)

To be clear, my params being passed in look like this:

```<code>%{
  payor: %ReimbursementMonitor.Schemas.Payor{
    __meta__: #Ecto.Schema.Metadata<:loaded, "payors">,
    id: 12,
    inserted_at: ~N[2020-02-15 16:30:16],
    name: "test_name",
    polling_url: "www.example.com",
    updated_at: ~N[2020-02-15 16:30:16]
  },
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}
</code>```

The situation I've encountered is that if the payor exists already, my tests are really unhappy. I get this error when attempting to run that test:

```<code>** (FunctionClauseError) no function clause matching in Keyword.get_lazy/3

 The following arguments were given to Keyword.get_lazy/3:

     # 1
     nil

     # 2
     :with

     # 3
     #Function<5.89690842/0 in Ecto.Changeset.cast_relation/4>

 Attempted function clauses (showing 1 out of 1):

def get_lazy(keywords, key, fun) when is_list(keywords) and is_atom(key) and is_function(fun, 0)
  code: |> PayorProcedureMapping.changeset(params)
  stacktrace:
    (elixir) lib/keyword.ex:223: Keyword.get_lazy/3
    (ecto) lib/ecto/changeset.ex:778: Ecto.Changeset.cast_relation/4
    (reimbursement_monitor) lib/reimbursement_monitor/schemas/payor_procedure_mapping.ex:50: ReimbursementMonitor.Schemas.PayorProcedureMapping.changeset/2
    test/schemas/payor_procedure_mapping_test.exs:28: (test)
</code>```

Full disclosure, I've searched google a ton but the examples I've been able to find are creating or building the payor schema at the time the payor_procedure_mappings is inserted.

I feel like I'm off in the weeds. I'd love to get some pointers of where to go look, good examples of what I'm asking about.

Thanks for your help in advance!

答:
As it is stated in the documentation for  Ecto.Changeset.cast_assoc/3

cast_assoc/3 works matching the records extracted from the database (preload) and compares it with the parameters provided from an external source.

That said, the example in the link above is exactly what you need:

```<code>- |> cast_assoc(:payor, params[:payor])
+ |> cast_assoc(:payor, with: &Payor.changeset/2)
</code>```

The error message also hints there is somewhat with: keyword key expected.

Title: ecto changeset add assoc for existing

Body:
Good morning! I've reached a moment where I'm struggling. To summarize, I'm trying to create a schema/model that has an association where the associated schema/model already exists. Every example I've found looks more like Rails nested attributes. Here is my various code thingses:

The schema (& its changeset function) with the associations:

schema "payor_procedure_mappings" do
  belongs_to :payor, Payor
  belongs_to :procedure, Procedure
  field :payor_procedure_name, :string
  field :payor_procedure_id, :string

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
  |> cast_assoc(:payor, params[:payor])  # <--- LINE 50 from stacktrace
end

defp required do
  :payor_procedure_name,
  :payor_procedure_id
]

The pre-existing schema I want to associate with that:

schema "payors" do
  field :name, :string, null: :false
  field :polling_url, :string, null: :false

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end

Here's the code where I'm attempting to set the association:

test "valid if all required params are present", %{procedure: procedure, payor: payor} do
  params = %{
    payor: payor,
    payor_procedure_name: "That one thing we do to patients",
    payor_procedure_id: "2342"
  }

changeset =
  %PayorProcedureMapping{}
  |> PayorProcedureMapping.changeset(params)   # THIS IS LINE 28 from stacktrace

  assert changeset.valid?
end

(Please note that the payor in the second argument to the test function is an already loaded schema/model struct)

To be clear, my params being passed in look like this:

%{
  payor: %ReimbursementMonitor.Schemas.Payor{
    __meta__: #Ecto.Schema.Metadata<:loaded, "payors">,
    id: 12,
    inserted_at: ~N[2020-02-15 16:30:16],
    name: "test_name",
    polling_url: "www.example.com",
    updated_at: ~N[2020-02-15 16:30:16]
  },
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}

The situation I've encountered is that if the payor exists already, my tests are really unhappy. I get this error when attempting to run that test:

** (FunctionClauseError) no function clause matching in Keyword.get_lazy/3

 The following arguments were given to Keyword.get_lazy/3:

     # 1
     nil

     # 2
     :with

     # 3
     #Function<5.89690842/0 in Ecto.Changeset.cast_relation/4>

 Attempted function clauses (showing 1 out of 1):

def get_lazy(keywords, key, fun) when is_list(keywords) and is_atom(key) and is_function(fun, 0)
  code: |> PayorProcedureMapping.changeset(params)
  stacktrace:
    (elixir) lib/keyword.ex:223: Keyword.get_lazy/3
    (ecto) lib/ecto/changeset.ex:778: Ecto.Changeset.cast_relation/4
    (reimbursement_monitor) lib/reimbursement_monitor/schemas/payor_procedure_mapping.ex:50: ReimbursementMonitor.Schemas.PayorProcedureMapping.changeset/2
    test/schemas/payor_procedure_mapping_test.exs:28: (test)

Full disclosure, I've searched google a ton but the examples I've been able to find are creating or building the payor schema at the time the payor_procedure_mappings is inserted.

I feel like I'm off in the weeds. I'd love to get some pointers of where to go look, good examples of what I'm asking about.

Thanks for your help in advance!

Body:
As it is stated in the documentation for  Ecto.Changeset.cast_assoc/3

cast_assoc/3 works matching the records extracted from the database (preload) and compares it with the parameters provided from an external source.

That said, the example in the link above is exactly what you need:

- |> cast_assoc(:payor, params[:payor])
+ |> cast_assoc(:payor, with: &Payor.changeset/2)

The error message also hints there is somewhat with: keyword key expected.


问:
Tinting the background pinstripes of a grouped UITableView
How do I apply a tint to the background of a UITableView using the grouped style? The standard "color" used ([UIColor groupTableViewBackgroundColor]) is tinted blue; I want a green tint instead.

This uses a pattern rather than a true color. I just want to tint that pattern to match the colors I'm using elsewhere, not replace it with a solid color.

答:
The easiest way is to make a screenshot of the default grouped tableview background and crop it so that its size is 7x1 pixels (that's enough to tile it). Adjust the tint color (hue, saturation, brightness) in your favorite image editor and use the resulting image as a pattern color via +colorWithPatternImage:, e.g.:

```<code>myTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"GreenStripes.png"]];
</code>```

Body:
The easiest way is to make a screenshot of the default grouped tableview background and crop it so that its size is 7x1 pixels (that's enough to tile it). Adjust the tint color (hue, saturation, brightness) in your favorite image editor and use the resulting image as a pattern color via +colorWithPatternImage:, e.g.:

myTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"GreenStripes.png"]];


问:
how do i get text from QListWidgetItem
so basically i just started to learn PyQt and I want to get element's text in listWidget, but everytime i try self.listWidget.currentItem().text() it throws an error. Why? </p>

```<code>import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QApplication, QListWidget
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *

class MainPage(QDialog):
    def __init__(self):
        super(MainPage,self).__init__()
        loadUi("HomePage.ui",self)
        self.pushButton.clicked.connect(self.addToList)
        self.selectButton.clicked.connect(self.getText)

    def addToList(self):
        customername = self.plainTextEdit_16.toPlainText()
        self.listWidget.addItem(customername)

    def getText(self):
        item = self.listWidget.currentItem().text() ##error is here

        print(item)

app = QApplication(sys.argv)

widget = MainPage()
widget.show()

sys.exit(app.exec_())
</code>```

答:
Assuming that "addToList" runs correctly then the only error is that there is no item selected so the currentItem will return None. The solution is to verify that it is None:

def getText(self):
    item = self.listWidget.currentItem()
    if item is not None:
        print(it.text())
```

Title: how do i get text from QListWidgetItem

Body:
so basically i just started to learn PyQt and I want to get element's text in listWidget, but everytime i try self.listWidget.currentItem().text() it throws an error. Why?

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QApplication, QListWidget
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *

class MainPage(QDialog):
    def __init__(self):
        super(MainPage,self).__init__()
        loadUi("HomePage.ui",self)
        self.pushButton.clicked.connect(self.addToList)
        self.selectButton.clicked.connect(self.getText)

    def addToList(self):
        customername = self.plainTextEdit_16.toPlainText()
        self.listWidget.addItem(customername)

    def getText(self):
        item = self.listWidget.currentItem().text() ##error is here

        print(item)

app = QApplication(sys.argv)

widget = MainPage()
widget.show()

sys.exit(app.exec_())


问:
Azure Elastic Job Delete
How do i delete my Elastic Job Agent.
i do have made jobs at it, just create it.</p>

答:
the problem is not to delete the Elastic Pool Job, its to delete the SQL DB that have been connected to he job, the fault is
enter image description here</p>

Title: Azure Elastic Job Delete


问:
SystemC undefined Symbol for architecture x86_64
I'm trying to run SystemC on XCode on mac (using the standard Clang compiler). Depending on the language dialect, I get different error messages. If I use C++14, I get the error

No member named 'experimental' in namespace 'std'

If I use the standard c++17, I get the error message

```<code>Undefined symbols for architecture x86_64:
  "sc_core::sc_api_version_2_3_3_cxx201402L<&(sc_core::SC_DISABLE_VIRTUAL_BIND_UNDEFINED_)>::sc_api_version_2_3_3_cxx201402L(sc_core::sc_writer_policy)", referenced from:
      ___cxx_global_var_init in main.o
ld: symbol(s) not found for architecture x86_64
</code>```

A similar question has been answered, however, the answer was "One of the files didn't have cstdlib included as a header file", without specifying that file. Does anyone know why that error occurs or what the file with the missing header is?

答:
For SystemC, the kernel and the model need to be compiled with the same set of modern C++ features enabled, see the RELEASENOTES and INSTALL files in the package. By default, the currently selected C++ standard of the compiler is used by SystemC (i.e. from -std=c++17).

To build SystemC for use across different C++ standard settings, explicitly define the preprocessor flag SC_CPLUSPLUS to the minimum version you need when building both, the kernel and your models.

For example

build SystemC with -std=c++11 (aka SC_CPLUSPLUS=201103L)

build your model with a newer C++ standard as you like, but add -DSC_CPLUSPLUS=201103L to your compiler flags.

Supported values for SC_CPLUSPLUS are:

199711L (C++03, ISO/IEC 14882:1998, 14882:2003)

201103L (C++11, ISO/IEC 14882:2011)

201402L (C++14, ISO/IEC 14882:2014)

201703L (C++17, ISO/IEC 14882:2017)

If SystemC 2.3.3 does not work with some version/configuration of the Xcode Clang compiler, you can consider opening an issue at https://github.com/accellera-official/systemc.

Body:
I'm trying to run SystemC on XCode on mac (using the standard Clang compiler). Depending on the language dialect, I get different error messages. If I use C++14, I get the error

No member named 'experimental' in namespace 'std'

If I use the standard c++17, I get the error message

Undefined symbols for architecture x86_64:
  "sc_core::sc_api_version_2_3_3_cxx201402L<&(sc_core::SC_DISABLE_VIRTUAL_BIND_UNDEFINED_)>::sc_api_version_2_3_3_cxx201402L(sc_core::sc_writer_policy)", referenced from:
      ___cxx_global_var_init in main.o
ld: symbol(s) not found for architecture x86_64

A similar question has been answered, however, the answer was "One of the files didn't have cstdlib included as a header file", without specifying that file. Does anyone know why that error occurs or what the file with the missing header is?