问:
Finding minimum line without subqueries - SQL
I have a table that has 3 columns: date, id and stake.

What I'm trying to find it the stake for each id at the earliest date

```<code>SELECT min(date), stake, id
FROM table
GROUP BY stake, id
</code>```

However, this groups by stake as well as id before returning me the minimum dates. Hence, it doesn't work.

I'm currently doing an order by/partition + selecting the row number

```<code>SELECT *
FROM(
  SELECT date, stake, id, row_number OVER (PARTITION BY id ORDER BY date ASC) AS rown
  FROM table
  ) t
WHERE t.rown = 1
</code>```

However, I'm not really a fan of wrapping the tables multiple times so was just wondering if anyone had a more efficient workaround to this?

答:
There is no reason at all to try to avoid subqueries -- unless you are using one of the very few databases that tend to materialize them.

This is still a subquery, but in many databases has the best performance:

```<code>select t.*
from t
where t.date = (select min(t2.date) from table t2 where t2.id = t.id);
</code>```

It wants an index on (id, date).

Some databases extend the SQL standard to support a "first" aggregation function.  Some have other functionality for doing this.  A standard way that doesn't use a subquery is:

```<code>select distinct id,
       first_value(stake) over (partition by id order by date) as stake,
       min(date) as date
from t;
</code>```

Either your version or the previous version should have better performance.

Body:
I have a table that has 3 columns: date, id and stake.

What I'm trying to find it the stake for each id at the earliest date

SELECT min(date), stake, id
FROM table
GROUP BY stake, id

However, this groups by stake as well as id before returning me the minimum dates. Hence, it doesn't work.

I'm currently doing an order by/partition + selecting the row number

SELECT *
FROM(
  SELECT date, stake, id, row_number OVER (PARTITION BY id ORDER BY date ASC) AS rown
  FROM table
  ) t
WHERE t.rown = 1

However, I'm not really a fan of wrapping the tables multiple times so was just wondering if anyone had a more efficient workaround to this?

Body:
There is no reason at all to try to avoid subqueries -- unless you are using one of the very few databases that tend to materialize them.

This is still a subquery, but in many databases has the best performance:

select t.*
from t
where t.date = (select min(t2.date) from table t2 where t2.id = t.id);

It wants an index on (id, date).

Some databases extend the SQL standard to support a "first" aggregation function.  Some have other functionality for doing this.  A standard way that doesn't use a subquery is:

select distinct id,
       first_value(stake) over (partition by id order by date) as stake,
       min(date) as date
from t;

Either your version or the previous version should have better performance.


来源: stackexchange

问:
how I can do on release input if empty fill with value using javascript
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

```<code><input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />
</code>```

答:
Have you tried adding something of the form
... onblur="this.value=\"The value you want\"" ...
in your input field? The blur event is basically the "defocus" event so to speak.

ContentLicense: CC BY-SA 4.0

Body:
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

<input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />


问:
How to show the current date of the month in "MaterialDatePicker" in Android?
I've implemented MaterialDatePicker for the purpose of the date selection & also done it but in calendar header initially shows the First date of the current month

Example: Today date is May 30 2020 but in the calendar before select any date i.e initially it shows May 1 2020.

Here is the code & screenshot:

```<code> MaterialDatePicker.Builder startDateBuilder;
 MaterialDatePicker startDatePicker;

 startDateBuilder = MaterialDatePicker.Builder.datePicker();
 startDateBuilder.setTitleText("Starting date");

 long today = MaterialDatePicker.todayInUtcMilliseconds();

 CalendarConstraints.Builder con = new CalendarConstraints.Builder();

 CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.now();

 con.setValidator(dateValidator); // Previous dates hide

 con.setStart(today); // Calender start from set day of the month

 startDateBuilder.setSelection(today);

 startDateBuilder.setCalendarConstraints(con.build());
 startDateBuilder.setTheme(R.style.MaterialCalendarTheme); // Custom Theme

 startDatePicker = startDateBuilder.build();

 startDatePicker.show(getSupportFragmentManager(), startDatePicker.toString());
</code>```

答:
My code is correct it was dependencies version problem. Previously I used the old version, Now update the new version, it was working fine.

com.google.android.material:material:1.2.0-alpha02

after changing the implementation

com.google.android.material:material:1.2.0-beta01

In beta01 also have some bugs in shows the current date in the header of the calendar and also a picker.

It doesn't show the current date in beta01 version so I changed to the stable version Now it will work.

com.google.android.material:material:1.1.0

Body:
I've implemented MaterialDatePicker for the purpose of the date selection & also done it but in calendar header initially shows the First date of the current month

Example: Today date is May 30 2020 but in the calendar before select any date i.e initially it shows May 1 2020.

Here is the code & screenshot:

 MaterialDatePicker.Builder startDateBuilder;
 MaterialDatePicker startDatePicker;

 startDateBuilder = MaterialDatePicker.Builder.datePicker();
 startDateBuilder.setTitleText("Starting date");

 long today = MaterialDatePicker.todayInUtcMilliseconds();

 CalendarConstraints.Builder con = new CalendarConstraints.Builder();

 CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.now();

 con.setValidator(dateValidator); // Previous dates hide

 con.setStart(today); // Calender start from set day of the month

 startDateBuilder.setSelection(today);

 startDateBuilder.setCalendarConstraints(con.build());
 startDateBuilder.setTheme(R.style.MaterialCalendarTheme); // Custom Theme

 startDatePicker = startDateBuilder.build();

 startDatePicker.show(getSupportFragmentManager(), startDatePicker.toString());


问:
SSL certificate not working while making curl request - Sectigo AddTrust External CA Root expired
While I try to open some of domains like https://tracking.buyhatke.com , https://s1.ripple.com , they work perfectly fine, but when I try to make a curl request to these pages from terminal, it says the certificates have expired. In browser , the certificates show that there is long time to expiry.

```<code>curl "https://tracking.buyhatke.com"
curl "https://s1.ripple.com"
</code>```

Can anyone guide me what is wrong here ? And it started happening today, all of a sudden

答:
Same here for our domains, but they are expiring in a year. It's also the same for sonarcloud.io. All these domains have a common CA in their certificate chain which has expired.

```<code>openssl s_client -connect s1.ripple.com:443
CONNECTED(00000003)
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=10:certificate has expired
notAfter=May 30 10:48:38 2020 GMT
</code>```

I'm currently investigating on how to move on with this so I have no answer to give you, just the reason for why it fails at the moment.

Body:
While I try to open some of domains like https://tracking.buyhatke.com , https://s1.ripple.com , they work perfectly fine, but when I try to make a curl request to these pages from terminal, it says the certificates have expired. In browser , the certificates show that there is long time to expiry.

curl "https://tracking.buyhatke.com"
curl "https://s1.ripple.com"

Can anyone guide me what is wrong here ? And it started happening today, all of a sudden

Body:
Same here for our domains, but they are expiring in a year. It's also the same for sonarcloud.io. All these domains have a common CA in their certificate chain which has expired.

openssl s_client -connect s1.ripple.com:443
CONNECTED(00000003)
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=10:certificate has expired
notAfter=May 30 10:48:38 2020 GMT

I'm currently investigating on how to move on with this so I have no answer to give you, just the reason for why it fails at the moment.


问:
Add an empty div on a certain index of a v-for loop
I'm passing in an array of product items via a computed variable in to a collection item component on a collection page. After the third product I'd like there to be an empty collection item, ie. a collection item template but with no product content inside. If anyone would have any ideas how I could achieve this in Vue.js I'd be most grateful.</p>

```<code>collection page:

        <collection-item
          v-for="product in products"
          :collection-item="product"
        ></collection-item>
</code>```

答:
If you know it will always be the third product that you want this empty item after, then you could loop on an outer container (like template, which acts as an invisible wrapper element in Vue) instead of collection-item, and use a v-if in conjunction with the index property available from v-for (second example on the Vue docs at the link).

<template v-for="(product, index) in products">
    <collection-item :collection-item="product" />
    <collection-item v-if="index == 2" />
</template>
```

Alternatively, you could splice an empty product into your array at the third position programmatically, which would ultimately have the same result, but may not be as clear as adding it in the template if it's purely for visual reasons.

As a final note, whenever you use v-for on a custom component, you must (since Vue v2.2.0) include a key property to help Vue distinguish between the list elements it renders. This should be something unique to all elements, like a product.id, but the index can work as a last resort too, if it doesn't cause problems.

Body:
I'm passing in an array of product items via a computed variable in to a collection item component on a collection page. After the third product I'd like there to be an empty collection item, ie. a collection item template but with no product content inside. If anyone would have any ideas how I could achieve this in Vue.js I'd be most grateful.

collection page:

        <collection-item
          v-for="product in products"
          :collection-item="product"
        ></collection-item>

Body:
If you know it will always be the third product that you want this empty item after, then you could loop on an outer container (like template, which acts as an invisible wrapper element in Vue) instead of collection-item, and use a v-if in conjunction with the index property available from v-for (second example on the Vue docs at the link).

<template v-for="(product, index) in products">
    <collection-item :collection-item="product" />
    <collection-item v-if="index == 2" />
</template>

Alternatively, you could splice an empty product into your array at the third position programmatically, which would ultimately have the same result, but may not be as clear as adding it in the template if it's purely for visual reasons.

As a final note, whenever you use v-for on a custom component, you must (since Vue v2.2.0) include a key property to help Vue distinguish between the list elements it renders. This should be something unique to all elements, like a product.id, but the index can work as a last resort too, if it doesn't cause problems.


问:
how can I link a list to if else? Flutter
I don't understand exactly why I always get an error here. I have built a (if else) statement, in a short version. Whenever the function no longer finds a value, i.e. comes to 3 in the array, I get the error that there is no more data in the array / list. But I did install an (ELSE) and it should display the text ("HELLO"). I don't know exactly where the error is. Maybe someone can help me briefly, thank you.

```<code>import 'package:flutter/material.dart';
import 'package:tasktolean/body.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var bodyTextIndex = 0;
  var bodytext = [
    'Hello FIRST Text!',
    'Hello SECOND Text!',
    'Hello THIRD Text!',
  ];

  void buttonPress() {
    setState(() {
      bodyTextIndex = bodyTextIndex + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'TASK',
          ),
        ),
        body: bodyTextIndex <= bodytext.length
            ? Column(
                children: [
                  BodyTextChance(
                    bodytext[bodyTextIndex],
                  ),
                  FlatButton(
                    onPressed: buttonPress,
                    child: Text(
                      'CLICK ME',
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('HELLO'),
              ),
      ),
    );
  }
}
</code>```

```<code>> import 'package:flutter/material.dart';
>
>
> class BodyTextChance extends StatelessWidget {   String bodytext;
>
>   BodyTextChance(this.bodytext);
>
>   @override   Widget build(BuildContext context) {
>     return Text(bodytext);   } }
</code>```

答:
Short Answer

This line uses a wrong comparison operator:

```<code>body: bodyTextIndex <= bodytext.length
</code>```

It should use < operator like so:

```<code>body: bodyTextIndex < bodytext.length
</code>```

A Bit More Details

When bodyTextIndex becomes 3, the condition below is still met:

```<code>bodyTextIndex <= bodytext.length
</code>```

Then it refers to bodytext[3] but the element doesn't exist because it ranges from 0 to 2.

Body:
I don't understand exactly why I always get an error here. I have built a (if else) statement, in a short version. Whenever the function no longer finds a value, i.e. comes to 3 in the array, I get the error that there is no more data in the array / list. But I did install an (ELSE) and it should display the text ("HELLO"). I don't know exactly where the error is. Maybe someone can help me briefly, thank you.

import 'package:flutter/material.dart';
import 'package:tasktolean/body.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var bodyTextIndex = 0;
  var bodytext = [
    'Hello FIRST Text!',
    'Hello SECOND Text!',
    'Hello THIRD Text!',
  ];

  void buttonPress() {
    setState(() {
      bodyTextIndex = bodyTextIndex + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'TASK',
          ),
        ),
        body: bodyTextIndex <= bodytext.length
            ? Column(
                children: [
                  BodyTextChance(
                    bodytext[bodyTextIndex],
                  ),
                  FlatButton(
                    onPressed: buttonPress,
                    child: Text(
                      'CLICK ME',
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('HELLO'),
              ),
      ),
    );
  }
}

> import 'package:flutter/material.dart';
>
>
> class BodyTextChance extends StatelessWidget {   String bodytext;
>
>   BodyTextChance(this.bodytext);
>
>   @override   Widget build(BuildContext context) {
>     return Text(bodytext);   } }

Body:
Short Answer

This line uses a wrong comparison operator:

body: bodyTextIndex <= bodytext.length

It should use < operator like so:

body: bodyTextIndex < bodytext.length

A Bit More Details

When bodyTextIndex becomes 3, the condition below is still met:

bodyTextIndex <= bodytext.length

Then it refers to bodytext[3] but the element doesn't exist because it ranges from 0 to 2.


问:
How do you style autofill inputs in Firefox?
input:-webkit-autofill can be used for Chrome/Safari, but input:-moz-autofill does not appear to do anything. Is there a way to customize the autofill styles in Firefox?

答:
For Firefox you can do this:</p>

```<code>input {
  filter: none;
}
</code>```

Body:
For Firefox you can do this:

input {
  filter: none;
}


问:
Navigation with Material-UI Icons
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

```<code> <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>
</code>```

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

答:
Did you try this way? Material-UI now supports Icon Button components,

```<code><IconButton aria-label="vehicles" component={Link} to="/vehicles">
  <NavigateBeforeIcon />
</IconButton>
</code>```

Here is a working example: https://codesandbox.io/s/material-demo-ifgg2

I found it weird that I couldn't find your exact icon from the Icon pack. I replaced that icon with a working sample icon. However, This could help you to identify and use as proof for my answer.

Refer to this: https://material-ui.com/components/buttons/#icon-buttons

I hope this will help you!

Title: Navigation with Material-UI Icons

Body:
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

 <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

Body:
Did you try this way? Material-UI now supports Icon Button components,

<IconButton aria-label="vehicles" component={Link} to="/vehicles">
  <NavigateBeforeIcon />
</IconButton>

Here is a working example: https://codesandbox.io/s/material-demo-ifgg2

I found it weird that I couldn't find your exact icon from the Icon pack. I replaced that icon with a working sample icon. However, This could help you to identify and use as proof for my answer.

Refer to this: https://material-ui.com/components/buttons/#icon-buttons

I hope this will help you!


问:
Referencing packages in java without using String
Is there a way to reference a package in java in code without using a String?

Let me explain myself:

I've a function that fetches all object contained in a package, but I've to reference that package using a String, lets say "com.google.guava". This works, however, If I change the package name, the IDE is not able to automatically refractor the references, or if the package is external and dissapears after a major version change it is not detected at compile time.

With classes, I'd use a Class object directly when possible or Class#getName if what I need is a String representing the FQDN of the class, but I don't know if there's a way to do so with packages.

Sometimes I just do

```<code>Class<?> clazz = Foo.class;
Package p = clazz.getPackage();
</code>```

This is more a curiosity than a real issue, I usually just reference by String and write a junit test in order to detect nom-existant packages used this way

答:
I can think of the following ways to get a Package object:

Call classLoader.getPackage(java.lang.String) or Package.getPackage(java.lang.String).  These methods are deprecated.

Call Package classLoader.getDefinedPackage(java.lang.String)

Call Package class.getPackage()

Call Package[] Package.getPackages() and then scan through the resulting array for the one that you want.

The last two approaches qualify as finding a Package with using a String.

There is no equivalent to a Java "class literal" (i.e. SomeClass.class) for packages.

Body:
Is there a way to reference a package in java in code without using a String?

Let me explain myself:

I've a function that fetches all object contained in a package, but I've to reference that package using a String, lets say "com.google.guava". This works, however, If I change the package name, the IDE is not able to automatically refractor the references, or if the package is external and dissapears after a major version change it is not detected at compile time.

With classes, I'd use a Class object directly when possible or Class#getName if what I need is a String representing the FQDN of the class, but I don't know if there's a way to do so with packages.

Sometimes I just do

Class<?> clazz = Foo.class;
Package p = clazz.getPackage();

This is more a curiosity than a real issue, I usually just reference by String and write a junit test in order to detect nom-existant packages used this way


问:
altair: change the position of a slider
Is it possible to change the position of a slider selection binding?

Couldn't find something in the altair documentation or in the vega-lite documentation (https://vega.github.io/vega-lite/docs/bind.html).

I want to move the year-slider up, closer to the main scatter plot:

https://vizsim.github.io/pkws_in_D/kba_neuzl_umwelt_fz14_v01.html

答:
The only way to adjust slider position in Altair/Vega-Lite output is to use CSS. If you're outputting HTML directly, you can add the CSS to the HTML file. If you're displaying an Altair chart within a Jupyter notebook, you can use the IPython.display module to add appropriate CSS.

For example, here is the US Population Over Time chart with the slider moved to the upper-right:

```<code>from IPython.display import display, HTML

display(HTML("""
<style>
form.vega-bindings {
  position: absolute;
  right: 0px;
  top: 0px;
}
</style>
"""))

import altair as alt
from vega_datasets import data

source = data.population.url

pink_blue = alt.Scale(domain=('Male', 'Female'),
                      range=["steelblue", "salmon"])

slider = alt.binding_range(min=1900, max=2000, step=10)
select_year = alt.selection_single(name="year", fields=['year'],
                                   bind=slider, init={'year': 2000})

alt.Chart(source).mark_bar().encode(
    x=alt.X('sex:N', title=None),
    y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
    color=alt.Color('sex:N', scale=pink_blue),
    column='age:O'
).properties(
    width=20
).add_selection(
    select_year
).transform_calculate(
    "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
    select_year
).configure_facet(
    spacing=8
)
</code>```

Title: altair: change the position of a slider

Body:
The only way to adjust slider position in Altair/Vega-Lite output is to use CSS. If you're outputting HTML directly, you can add the CSS to the HTML file. If you're displaying an Altair chart within a Jupyter notebook, you can use the IPython.display module to add appropriate CSS.

For example, here is the US Population Over Time chart with the slider moved to the upper-right:

from IPython.display import display, HTML

display(HTML("""
<style>
form.vega-bindings {
  position: absolute;
  right: 0px;
  top: 0px;
}
</style>
"""))

import altair as alt
from vega_datasets import data

source = data.population.url

pink_blue = alt.Scale(domain=('Male', 'Female'),
                      range=["steelblue", "salmon"])

slider = alt.binding_range(min=1900, max=2000, step=10)
select_year = alt.selection_single(name="year", fields=['year'],
                                   bind=slider, init={'year': 2000})

alt.Chart(source).mark_bar().encode(
    x=alt.X('sex:N', title=None),
    y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
    color=alt.Color('sex:N', scale=pink_blue),
    column='age:O'
).properties(
    width=20
).add_selection(
    select_year
).transform_calculate(
    "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
    select_year
).configure_facet(
    spacing=8
)


问:
AdMob MobileAds.initialize(this, "YOUR_ADMOB_APP_ID") deprecated alternative
I was following the firebase guide to enable ads in a android app.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
}
</code>```

The initialize method seems to be deprecated but the official guide recommends to use it.
Is there any alternative that I shall use to initialize Ads?

答:
Use this method instead: initialize(Context, OnInitializationCompleteListener)

```<code>MobileAds.initialize(this, new OnInitializationCompleteListener() {
     @Override
     public void onInitializationComplete(InitializationStatus initializationStatus) {

     }
});
</code>```

Body:
I was following the firebase guide to enable ads in a android app.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
}

The initialize method seems to be deprecated but the official guide recommends to use it.
Is there any alternative that I shall use to initialize Ads?

Body:
Use this method instead: initialize(Context, OnInitializationCompleteListener)

MobileAds.initialize(this, new OnInitializationCompleteListener() {
     @Override
     public void onInitializationComplete(InitializationStatus initializationStatus) {

     }
});


问:
Flutter error on updating Android Studio, Kotlin, Flutter, Dart plugins are incompatible with the new Android Studio version 4.0
I just updated the Android Studio to 4.0, and now I am getting the errors in my IDE that  Kotlin, Flutter, Dart plugins are incompatible with the new Android Studio version 4.0, what's the solution?</p>

答:
How i fixed this:

Locate and open the idea.properties file in your Android/bin folder

Add idea.plugins.host=https://plugins.jetbrains.com to the file.

Save and close file

Relaunch Android Studio


问:
Filtering and splicing an array in Twig
I have an array of user records (0 indexed, from a database query), each of which contains an array of fields (indexed by field name). For example:

```<code>Array
(
    [0] => Array
        (
            [name] => Fred
            [age] => 42
        )

    [1] => Array
        (
            [name] => Alice
            [age] => 42
        )

    [2] => Array
        (
            [name] => Eve
            [age] => 24
        )

)
</code>```

In my Twig template, I want to get all the users where the age field is 42 and then return the name field of those users as an array. I can then pass that array to join(
) to print one name per line.

For example, if the age was 42 I would expect Twig to output:

```<code>Fred<br>
Alice
</code>```

Is this possible to do in Twig out of the box, or would I need to write a custom filter? I'm not sure how to describe what I want in a couple of words so it may be that someone else has written a filter but I can't find it by searching.

答:
You can apply a filter on the array you apply for loop on, like this:</p>

```<code>{% for u in user|filter((u) => u.age == 42) -%}
   <!-- do your stuff -->
{% endfor %}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Filtering and splicing an array in Twig

Body:
I have an array of user records (0 indexed, from a database query), each of which contains an array of fields (indexed by field name). For example:

Array
(
    [0] => Array
        (
            [name] => Fred
            [age] => 42
        )

    [1] => Array
        (
            [name] => Alice
            [age] => 42
        )

    [2] => Array
        (
            [name] => Eve
            [age] => 24
        )

)

In my Twig template, I want to get all the users where the age field is 42 and then return the name field of those users as an array. I can then pass that array to join(
) to print one name per line.

For example, if the age was 42 I would expect Twig to output:

Fred

Alice

Is this possible to do in Twig out of the box, or would I need to write a custom filter? I'm not sure how to describe what I want in a couple of words so it may be that someone else has written a filter but I can't find it by searching.

Body:
You can apply a filter on the array you apply for loop on, like this:

{% for u in user|filter((u) => u.age == 42) -%}
   <!-- do your stuff -->
{% endfor %}


问:
How to set selectedIndex of select element using display text?
How to set selectedIndex of select element using display text as reference?

Example:

```<code><input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

<script type="text/javascript">
    function SelectAnimal()
    {
        //Set selected option of Animals based on AnimalToFind value...
    }
 </script>
</code>```

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

答:
```<code><script type="text/javascript">
     function SelectAnimal(){
         //Set selected option of Animals based on AnimalToFind value...
         var animalTofind = document.getElementById('AnimalToFind');
         var selection = document.getElementById('Animals');

        // select element
        for(var i=0;i<selection.options.length;i++){
            if (selection.options[i].innerHTML == animalTofind.value) {
                selection.selectedIndex = i;
                break;
            }
        }
     }
</script>
</code>```

setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces

```<code>selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
</code>```

or using .match(/regular expression/)

Body:
How to set selectedIndex of select element using display text as reference?

Example:

<input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

Body:
<script type="text/javascript">
     function SelectAnimal(){
         //Set selected option of Animals based on AnimalToFind value...
         var animalTofind = document.getElementById('AnimalToFind');
         var selection = document.getElementById('Animals');

        // select element
        for(var i=0;i<selection.options.length;i++){
            if (selection.options[i].innerHTML == animalTofind.value) {
                selection.selectedIndex = i;
                break;
            }
        }
     }
</script>

setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces

selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;

or using .match(/regular expression/)


问:
Finding the sum of non-zero individual values in nested dictionaries
So I wrote this code, I am trying to find the sum of each non-zero rating of each book, in order to find the average of the ratings of each book, without including the zero ratings of each book.

This is what I have tried to do, it is working. But I couldn't figure out how to find the sum of each rating of each book and to find the average.

```<code>books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

total = dict()
count = 0
for list_item in biglist:
    for key, value in list_item.items():
        for key2, value2 in value.items():
            total[key2] = value2 + total.get(key2,0)
            for book in books:
                if value2 != 0 and book == key2:
                        count += 1
                        print(f"Found non-zero value, [{key2} : {value2}]
</code>```

答:
Given that:

```<code>books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]
</code>```

Considering you want to calculate average and sum if ratings, here is a neat solution:

All ratings: ratings={book:[biglist[i]['user'+str(i+1)][book] for i, _ in enumerate(biglist)] for book in books}

This outputs: {'book1': [0, 5, 1], 'book2': [-2, 0, 5], 'book3': [3, -3, 3]}

.

Sum of ratings: sum_of_ratings = {book:sum(ratings[book]) for book in books}

This outputs: {'book1': 6, 'book2': 3, 'book3': 3}

.

Avg of ratings: avg_of_ratings =  {book:sum_of_ratings[book]/len(ratings[book]) for book in books}

This outputs: {'book1': 2.0, 'book2': 1.0, 'book3': 1.0}

.

Avg of non-zero ratings: avg_of_non_zero_ratings =  {book:sum_of_ratings[book]/sum([i!=0 for i in ratings[book]]) for book in books}

This outputs: {'book1': 3.0, 'book2': 1.5, 'book3': 1.0}

Body:
So I wrote this code, I am trying to find the sum of each non-zero rating of each book, in order to find the average of the ratings of each book, without including the zero ratings of each book.

This is what I have tried to do, it is working. But I couldn't figure out how to find the sum of each rating of each book and to find the average.

books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

total = dict()
count = 0
for list_item in biglist:
    for key, value in list_item.items():
        for key2, value2 in value.items():
            total[key2] = value2 + total.get(key2,0)
            for book in books:
                if value2 != 0 and book == key2:
                        count += 1
                        print(f"Found non-zero value, [{key2} : {value2}]

Body:
Given that:

books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

Considering you want to calculate average and sum if ratings, here is a neat solution:

All ratings: ratings={book:[biglist[i]['user'+str(i+1)][book] for i, _ in enumerate(biglist)] for book in books}

This outputs: {'book1': [0, 5, 1], 'book2': [-2, 0, 5], 'book3': [3, -3, 3]}

.

Sum of ratings: sum_of_ratings = {book:sum(ratings[book]) for book in books}

This outputs: {'book1': 6, 'book2': 3, 'book3': 3}

.

Avg of ratings: avg_of_ratings =  {book:sum_of_ratings[book]/len(ratings[book]) for book in books}

This outputs: {'book1': 2.0, 'book2': 1.0, 'book3': 1.0}

.

Avg of non-zero ratings: avg_of_non_zero_ratings =  {book:sum_of_ratings[book]/sum([i!=0 for i in ratings[book]]) for book in books}

This outputs: {'book1': 3.0, 'book2': 1.5, 'book3': 1.0}


问:
Trying to increment a MariaDB value
I am trying to increment value using a trigger in MariaDB. However, for some reason, the value does not increment each time the row is updated. I can confirm that the row is being updated every 1 minute via Cronjob.

The PMA trigger:

Essentially here is what I'm trying to accomplish:

I am trying to take the old playtime value and increment by 1 each time the the row is updated.

So for example, if a row has a playtime value of 200 and the row is updated, it'll now become 201.

Any ideas? I have been stuck on this for a long while. Thanks!

答:
Presumably you want:

```<code>new.playtime = new.playtime + 1;
</code>```

That seems really strange, though.  Why would you have a query that incremented an incoming value by 1?

Title: Trying to increment a MariaDB value

Body:
Presumably you want:

new.playtime = new.playtime + 1;

That seems really strange, though.  Why would you have a query that incremented an incoming value by 1?


问:
Destroying label frames
I am tinkering around with basic things in Tkinter/python. I am using the LabelFrame that corresponds with several buttons I click. I am struggling with trying to destroy the other frames and only displaying the frame I want visible when clicking on a certain button. When I run this code:

```<code>def lblframe1_view():
    lblframe3.destroy()
    lblframe2.destroy()
    lblframe1 = LabelFrame(root, text="This is Frame One", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn1 = Button(lblframe1, text="this is button one").pack()

def lblframe2_view():
    lblframe1.destroy()
    lblframe3.destroy()
    lblframe2 = LabelFrame(root, text="Frame Two", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn2 = Button(lblframe2, text="this is button two").pack()

def lblframe3_view():
    lblframe1.destroy()
    lblframe2.destroy
    lblframe3 = LabelFrame(root, text="this is frame 3", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)

def exit():
    root.destroy()

manbtn1 = Button(root, text="Frame 1", bg="white", height=4, width=25, command=lblframe1).place(x=10, y=20)
mainbtn2 = Button(root, text="Frame 2, bg="white", height=4, width=25, command=lblframe2).place(x=10, y=120)
mainbtn3 = Button(root, text="Frame 3", bg="white", height=4, width=25, command=lblframe3).place(x=10, y=220)
exitbtn = Button(root, text="Exit", bg="white", height=4, width=25, command=exit).place(x=10, y=320)
</code>```

When I run this I get the following error:

NameError: name 'lblframe3' is not defined

I have tried to put the functions after buttons and got the same error. I have done research on this
and haven't been able to figure out why this keeps happening. My hunch is python

答:
Im not a experienced python programmer myself but there are a few things i noticed that might help you out.

Please make sure the code you post here is tested, it is a bit annoying if i have to debug the code before i can help you in the first place. (referring to the " in third line from the bottom as well as the indentation).

Button(command) takes a function as a argument. You provided a Object. So try to switch the command to command = lblframe1_view instead of lblframe1.

Frames in tkinter are objects, therefore they can not be accessed from a function where they were not defined in, unless u declare them global or pass it in as a argument. What that  means is if lblframe1_view() is called, it does not know what lblframe3 or lblframe2 are.

I hope this helped you out.

EDIT:
I just realised that there might be one more problem with the structure of your programm that can not be solved by declaring the frames as globals.
In lblframe1_view u want to destroy an object that does not even exist yet, since it only will be created if lblframe2_view() and lblframe3_view() have been executed beforehand. But those two functions will also throw an error, since lblframe1 is not created yet.

Title: Destroying label frames

Body:
I am tinkering around with basic things in Tkinter/python. I am using the LabelFrame that corresponds with several buttons I click. I am struggling with trying to destroy the other frames and only displaying the frame I want visible when clicking on a certain button. When I run this code:

def lblframe1_view():
    lblframe3.destroy()
    lblframe2.destroy()
    lblframe1 = LabelFrame(root, text="This is Frame One", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn1 = Button(lblframe1, text="this is button one").pack()

def lblframe2_view():
    lblframe1.destroy()
    lblframe3.destroy()
    lblframe2 = LabelFrame(root, text="Frame Two", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn2 = Button(lblframe2, text="this is button two").pack()

def lblframe3_view():
    lblframe1.destroy()
    lblframe2.destroy
    lblframe3 = LabelFrame(root, text="this is frame 3", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)

def exit():
    root.destroy()

manbtn1 = Button(root, text="Frame 1", bg="white", height=4, width=25, command=lblframe1).place(x=10, y=20)
mainbtn2 = Button(root, text="Frame 2, bg="white", height=4, width=25, command=lblframe2).place(x=10, y=120)
mainbtn3 = Button(root, text="Frame 3", bg="white", height=4, width=25, command=lblframe3).place(x=10, y=220)
exitbtn = Button(root, text="Exit", bg="white", height=4, width=25, command=exit).place(x=10, y=320)

When I run this I get the following error:

NameError: name 'lblframe3' is not defined

I have tried to put the functions after buttons and got the same error. I have done research on this
and haven't been able to figure out why this keeps happening. My hunch is python


问:
Android searchview returns null
I am trying to use a SearchView in my actionbar (for only one fragment) but the SearchView keeps on returning null.

fragment

```<code>
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import com.StockMarketAlarms.StockAlarm.R
import com.google.firebase.auth.FirebaseAuth

class SearchFragment : Fragment() {
    private lateinit var auth: FirebaseAuth

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val root = inflater.inflate(R.layout.fragment_search, container, false)
        setHasOptionsMenu(true)
        return root
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.search_menu, menu)

        val searchView: SearchView = menu.findItem(R.id.menuitem_search) as SearchView
        searchView.setMaxWidth(Int.MAX_VALUE)
    }
}
</code>```

its loaded in a tabactivity that extends AppCompatActivity

The search menu looks like this
search_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <android.support.v7.widget.SearchView
        android:id="@+id/menuitem_search"
        android:icon="@drawable/search_black_48"
        app:actionViewClass="android.widget.SearchView"
        android:title="@string/title_search"
        app:searchIcon="@drawable/search_black_48"
        app:showAsAction="collapseActionView|ifRoom"
        app:queryBackground="@color/colorWhite"
        app:iconifiedByDefault="false" />
</menu>
</code>```

I dont understand why it returns null, I tried a lot.

```<code> Process: com.jfvh.stockalarm, PID: 1845
    kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.widget.SearchView
        at com.jfvh.stockalarm.activities.fragments.SearchFragment.onCreateOptionsMenu(SearchFragment.kt:48)
        at androidx.fragment.app.Fragment.performCreateOptionsMenu(Fragment.java:2711)
        at androidx.fragment.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManagerImpl.java:2711)
        at androidx.fragment.app.Fragment.performCreateOptionsMenu(Fragment.java:2713)
        at androidx.fragment.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManagerImpl.java:2711)
        at androidx.fragment.app.FragmentController.dispatchCreateOptionsMenu(FragmentController.java:386)
        at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:326)
        at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:2830)
        at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1746)
        at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:2026)
        at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:260)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
search_menu.xml has an error.

It should be:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- tag name should be <item> -->
    <item
        android:id="@+id/menuitem_search"
        android:icon="@drawable/search_black_48"
        app:actionViewClass="android.widget.SearchView"
        android:title="@string/title_search"
        app:searchIcon="@drawable/search_black_48"
        app:showAsAction="collapseActionView|ifRoom"
        app:queryBackground="@color/colorWhite"
        app:iconifiedByDefault="false"/>
</menu>
</code>```

Source: https://developer.android.com/training/search/setup#add-sv

Menus allow only two tags <group>, <item>:

And for action view class you can select basically anything. Note, that actionViewClass attribute uses app namespace prefix:

UPDATE

I noticed one more problem, that is in your fragment. When you find menu item by its id it does not return you an action view, instead what you get is MenuItem instance. It cannot be casted to any kind of View.

To fix this issue you should get the value of actionView attribute of MenuItem object.

```<code> override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.search_menu, menu)

        // `.actionView` was missing
        val searchView: SearchView = menu.findItem(R.id.menuitem_search).actionView as SearchView
        searchView.setMaxWidth(Int.MAX_VALUE)
    }
</code>```

Title: Android searchview returns null

Body:
I am trying to use a SearchView in my actionbar (for only one fragment) but the SearchView keeps on returning null.

fragment

import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import com.StockMarketAlarms.StockAlarm.R
import com.google.firebase.auth.FirebaseAuth

class SearchFragment : Fragment() {
    private lateinit var auth: FirebaseAuth

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val root = inflater.inflate(R.layout.fragment_search, container, false)
        setHasOptionsMenu(true)
        return root
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.search_menu, menu)

        val searchView: SearchView = menu.findItem(R.id.menuitem_search) as SearchView
        searchView.setMaxWidth(Int.MAX_VALUE)
    }
}

its loaded in a tabactivity that extends AppCompatActivity

The search menu looks like this
search_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <android.support.v7.widget.SearchView
        android:id="@+id/menuitem_search"
        android:icon="@drawable/search_black_48"
        app:actionViewClass="android.widget.SearchView"
        android:title="@string/title_search"
        app:searchIcon="@drawable/search_black_48"
        app:showAsAction="collapseActionView|ifRoom"
        app:queryBackground="@color/colorWhite"
        app:iconifiedByDefault="false" />
</menu>

I dont understand why it returns null, I tried a lot.

 Process: com.jfvh.stockalarm, PID: 1845
    kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.widget.SearchView
        at com.jfvh.stockalarm.activities.fragments.SearchFragment.onCreateOptionsMenu(SearchFragment.kt:48)
        at androidx.fragment.app.Fragment.performCreateOptionsMenu(Fragment.java:2711)
        at androidx.fragment.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManagerImpl.java:2711)
        at androidx.fragment.app.Fragment.performCreateOptionsMenu(Fragment.java:2713)
        at androidx.fragment.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManagerImpl.java:2711)
        at androidx.fragment.app.FragmentController.dispatchCreateOptionsMenu(FragmentController.java:386)
        at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:326)
        at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:2830)
        at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1746)
        at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:2026)
        at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:260)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
search_menu.xml has an error.

It should be:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- tag name should be <item> -->
    <item
        android:id="@+id/menuitem_search"
        android:icon="@drawable/search_black_48"
        app:actionViewClass="android.widget.SearchView"
        android:title="@string/title_search"
        app:searchIcon="@drawable/search_black_48"
        app:showAsAction="collapseActionView|ifRoom"
        app:queryBackground="@color/colorWhite"
        app:iconifiedByDefault="false"/>
</menu>

Source: https://developer.android.com/training/search/setup#add-sv

Menus allow only two tags <group>, <item>:

And for action view class you can select basically anything. Note, that actionViewClass attribute uses app namespace prefix:

UPDATE

I noticed one more problem, that is in your fragment. When you find menu item by its id it does not return you an action view, instead what you get is MenuItem instance. It cannot be casted to any kind of View.

To fix this issue you should get the value of actionView attribute of MenuItem object.

 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.search_menu, menu)

        // `.actionView` was missing
        val searchView: SearchView = menu.findItem(R.id.menuitem_search).actionView as SearchView
        searchView.setMaxWidth(Int.MAX_VALUE)
    }


问:
How to call function after routing in React?
Let's say there is a website with routes:
/routeA,
/routeB
...
/routeZ

Each of those routes render a ComponentA, ComponentB ... ComponentZ

How to run a particular piece of code no matter which route has been reached?

The piece of code is irrelevant. It could be console.log("Awesome stackoverflow")

Obviously, in each component I could call useEffect and call the piece of code there. However, this is repetitive since I would have to write Z useEffect for the Z components we have.
Instead, I am looking for a way to execute the piece of code without needing to repeate code through all components.

答:
```<code>//if you are using class
class YourComponent extends React.Component{
    componentDidMount = () => {
        //your logic here
    }
}

//if you are using hook
const YourComponent = () => {
    useEffect(() => {
       //your logic here
    },[])
}
</code>```


问:
How do i disable a function in a function?
I have a game over function here:

```<code>function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}
</code>```

I also have a score function here:

```<code>function Score() {
    ctx.fillStyle = "#000"
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}
</code>```

What i want is when i call the game over function then i want the score to not be visible. How can i do that???

I have tried:

```<code>function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
    Score() = "none";
}
</code>```

but it obviously didn't work, lol. Im kind of new to this, sorry.

答:
You had better use a variable to keep the current state of the game</p>

```<code>var state ="PLAYING";
function gameOver() {
    if(state!== "PLAYING") return;
    state = "GAME_OVER";
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}
function Score() {
    if(state!== "PLAYING") return;
    ctx.fillStyle = "#000";
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}

function playAgain() {
    state = "PLAYING";
}
</code>```

Body:
I have a game over function here:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}

I also have a score function here:

function Score() {
    ctx.fillStyle = "#000"
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}

What i want is when i call the game over function then i want the score to not be visible. How can i do that???

I have tried:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
    Score() = "none";
}

but it obviously didn't work, lol. Im kind of new to this, sorry.

Body:
You had better use a variable to keep the current state of the game

var state ="PLAYING";
function gameOver() {
    if(state!== "PLAYING") return;
    state = "GAME_OVER";
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}
function Score() {
    if(state!== "PLAYING") return;
    ctx.fillStyle = "#000";
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}

function playAgain() {
    state = "PLAYING";
}


问:
Is it possible to run two python scripts parallel and plotting real time?
I have two Python scripts: 1st is responsible for generating data and save them in .csv file and 2nd for plotting this data in real time. I have to run 1st script in console and then run 2nd script in new instance of console. I want to do all this things in one script but I can't do that. I tried to use mutliprocessing but I failed. I add my 2 scripts:

```<code>#THIS IS DATA GENERATING SCRIPT
import csv
import random
import time
import numpy as np

steps = 12000
shift = [-1, 0, 1]
start_corr_2D = [0, 0]
start_corr_3D = [0, 0, 0]

path_2D = np.zeros(shape=(steps,2))
path_3D = np.zeros(shape=(steps,3))

path_2D[0] = start_corr_2D
path_3D[0] = start_corr_3D

fieldnames = ["X", "Y"]

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

    info = {
        "X": start_corr_2D[0],
        "Y": start_corr_2D[1],
        }

    csv_writer.writerow(info)

for i in range(1, steps):

    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        shift_2D = [random.choice(shift), random.choice(shift)]
        shift_3D = [random.choice(shift), random.choice(shift), random.choice(shift)]

        next_corr_2D = list(map(sum, zip(start_corr_2D, shift_2D)))
        next_corr_3D = list(map(sum, zip(start_corr_3D, shift_3D)))
        print(next_corr_2D)

        path_2D[i] = next_corr_2D
        path_3D[i] = next_corr_3D

        start_corr_2D = next_corr_2D
        start_corr_3D = next_corr_3D

        info = {
        "X": next_corr_2D[0],
        "Y": next_corr_2D[1],
        }

        csv_writer.writerow(info)

    time.sleep(0.3)
</code>```

```<code>#THIS SCRIPT IS RESPONSIBLE FOR PLOTTING IN REAL TIME
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation

j = 0

def animate(i):
    data = pd.read_csv('data.csv')
    xs = data['X']
    ys = data['Y']

    global j
    j += 1
#    print(j)

    plt.cla()
#    plt.scatter(xs, ys, c='red', marker='*')

    if j < 10:
        plt.plot(xs, ys, c='blue', lw=0.6)
    elif j >= 10 and j < 50:
        plt.plot(xs, ys, c='red', lw=0.6)
    else:
        plt.plot(xs, ys, c='green', lw=0.6)

    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=300)

plt.tight_layout()
plt.show()
</code>```

I am doing this operations right now:

But I want to get results from running only 1 script.
I would be grateful for any help.

答:
Multiprocessing seems the right way to do what you are trying to achieve. However, using the csv file to communicate between the two process is pretty dangerous. This can be avoided by using a queue between the two processes to send the new data to the plot.

Here's a possible implementation (you could put animate in a different file):

import csv
import random
import time
from multiprocessing import Process, Queue

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def animate(q):
    xs = [0]
    ys = [1]
    def _animate(i):
        while not q.empty():
            x, y = q.get()
            xs.append(x)
            ys.append(y)
        plt.cla()
        #    plt.scatter(xs, ys, c='red', marker='*')

        if i < 10:
            plt.plot(xs, ys, c='blue', lw=0.6)
        elif 10 <= i < 50:
            plt.plot(xs, ys, c='red', lw=0.6)
        else:
            plt.plot(xs, ys, c='green', lw=0.6)

        plt.tight_layout()

    ani = FuncAnimation(plt.gcf(), _animate, interval=300)

    plt.tight_layout()
    plt.show()

def main():
    steps = 12000
    shift = [-1, 0, 1]
    start_corr_2D = [0, 0]
    start_corr_3D = [0, 0, 0]

    path_2D = np.zeros(shape=(steps,2))
    path_3D = np.zeros(shape=(steps,3))

    path_2D[0] = start_corr_2D
    path_3D[0] = start_corr_3D

    fieldnames = ["X", "Y"]
    data_queue = Queue()
    plot_process = Process(target=animate, args=(data_queue,))
    plot_process.start()

    with open('data.csv', 'w') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        csv_writer.writeheader()

        info = {
            "X": start_corr_2D[0],
            "Y": start_corr_2D[1],
            }

        csv_writer.writerow(info)

    for i in range(1, steps):

        with open('data.csv', 'a') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

            shift_2D = [random.choice(shift), random.choice(shift)]
            shift_3D = [random.choice(shift), random.choice(shift), random.choice(shift)]

            next_corr_2D = list(map(sum, zip(start_corr_2D, shift_2D)))
            next_corr_3D = list(map(sum, zip(start_corr_3D, shift_3D)))

            path_2D[i] = next_corr_2D
            path_3D[i] = next_corr_3D

            start_corr_2D = next_corr_2D
            start_corr_3D = next_corr_3D

            info = {
            "X": next_corr_2D[0],
            "Y": next_corr_2D[1],
            }
            data_queue.put((next_corr_2D[0], next_corr_2D[1]))
            csv_writer.writerow(info)

        time.sleep(0.3)

    plot_process.join()

if __name__ == '__main__':
    main()
```

Body:
I have two Python scripts: 1st is responsible for generating data and save them in .csv file and 2nd for plotting this data in real time. I have to run 1st script in console and then run 2nd script in new instance of console. I want to do all this things in one script but I can't do that. I tried to use mutliprocessing but I failed. I add my 2 scripts:

#THIS IS DATA GENERATING SCRIPT
import csv
import random
import time
import numpy as np

steps = 12000
shift = [-1, 0, 1]
start_corr_2D = [0, 0]
start_corr_3D = [0, 0, 0]

path_2D = np.zeros(shape=(steps,2))
path_3D = np.zeros(shape=(steps,3))

path_2D[0] = start_corr_2D
path_3D[0] = start_corr_3D

fieldnames = ["X", "Y"]

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

    info = {
        "X": start_corr_2D[0],
        "Y": start_corr_2D[1],
        }

    csv_writer.writerow(info)

for i in range(1, steps):

    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        shift_2D = [random.choice(shift), random.choice(shift)]
        shift_3D = [random.choice(shift), random.choice(shift), random.choice(shift)]

        next_corr_2D = list(map(sum, zip(start_corr_2D, shift_2D)))
        next_corr_3D = list(map(sum, zip(start_corr_3D, shift_3D)))
        print(next_corr_2D)

        path_2D[i] = next_corr_2D
        path_3D[i] = next_corr_3D

        start_corr_2D = next_corr_2D
        start_corr_3D = next_corr_3D

        info = {
        "X": next_corr_2D[0],
        "Y": next_corr_2D[1],
        }

        csv_writer.writerow(info)

    time.sleep(0.3)

#THIS SCRIPT IS RESPONSIBLE FOR PLOTTING IN REAL TIME
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation

j = 0

def animate(i):
    data = pd.read_csv('data.csv')
    xs = data['X']
    ys = data['Y']

    global j
    j += 1
#    print(j)

    plt.cla()
#    plt.scatter(xs, ys, c='red', marker='*')

    if j < 10:
        plt.plot(xs, ys, c='blue', lw=0.6)
    elif j >= 10 and j < 50:
        plt.plot(xs, ys, c='red', lw=0.6)
    else:
        plt.plot(xs, ys, c='green', lw=0.6)

    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=300)

plt.tight_layout()
plt.show()

I am doing this operations right now:

But I want to get results from running only 1 script.
I would be grateful for any help.


问:
how I can do on release input if empty fill with value using javascript
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

```<code><input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />
</code>```

答:
You need to have an onfocus which will save the value, and then an onblur which will restore the old value if the new is ''.</p>

```<code><input onfocus="this.oldvalue = this.value" value="abc" onblur="this.value = this.value || this.oldvalue" />
</code>```

Body:
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

<input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />

Body:
You need to have an onfocus which will save the value, and then an onblur which will restore the old value if the new is ''.

<input onfocus="this.oldvalue = this.value" value="abc" onblur="this.value = this.value || this.oldvalue" />


问:
Use dpl on GitHub Actions
I was used with dpl on gitlab ci. Our repo was using a specific version and the code was like that:

```<code>prod_deploy_api_developer:
  stage: deploy
  script:
    - echo "prod_deploy_api running"
    - apt-get update -qy
    - apt-get install -yqq ruby ruby-dev --silent
    - gem install dpl -v 1.8.47
    - cd ./api
    - dpl --provider=heroku --app=myapp --api-key=mycrazykey --skip-cleanup
</code>```

Now we migrated that codebase to GitHub, and I didn't found a GitHub Action ready to run.

答:
I just published Dpl Github Action.

It's a very simple implementation, and I just added heroku as provider, because is the one I needed to deploy my project like used to do on GitLab.

A use example with heroku:

Example

```<code>- name: Dpl to heroku
  uses: tiagogouvea/github-dpl-action@master
  with:
    provider: 'heroku'
    app: 'your-heroku-app-name'
    api-key: 'your-66a593c465c7ec9-heroku-api-key'
</code>```

Title: Use dpl on GitHub Actions

Body:
I was used with dpl on gitlab ci. Our repo was using a specific version and the code was like that:

prod_deploy_api_developer:
  stage: deploy
  script:
    - echo "prod_deploy_api running"
    - apt-get update -qy
    - apt-get install -yqq ruby ruby-dev --silent
    - gem install dpl -v 1.8.47
    - cd ./api
    - dpl --provider=heroku --app=myapp --api-key=mycrazykey --skip-cleanup

Now we migrated that codebase to GitHub, and I didn't found a GitHub Action ready to run.

Body:
I just published Dpl Github Action.

It's a very simple implementation, and I just added heroku as provider, because is the one I needed to deploy my project like used to do on GitLab.

A use example with heroku:

Example

- name: Dpl to heroku
  uses: tiagogouvea/github-dpl-action@master
  with:
    provider: 'heroku'
    app: 'your-heroku-app-name'
    api-key: 'your-66a593c465c7ec9-heroku-api-key'


问:
Using Template For Client Forms

My project is a desctop application with client and server side. Maybe later will be even web interface. Users can fill out different types of forms. I want use some kind of templates of this forms (on xml) and put data on client side in this templates subsequently to store user fills out a form in xml.

I'm on the right track?

1.Maybe i can use String Template or there are alternatives?

2.How can I attach a search on only some fields filled in forms, which will be stored in xml?

答:
You can have make a base form and use it as a template for other forms by inheriting it rather than inheriting Form.

Base form:

```<code>public partial class BaseForm : Form
{
    public BaseForm()
    {
        InitializeComponent();
    }
    protected virtual void closeButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}
</code>```

Form you want to be based on template:

```<code>public partial class MainForm : BaseForm
{
    public MainForm()
    {
        InitializeComponent();
    }
}
</code>```

Here's a larger example in VB http://www.java2s.com/Code/VB/GUI/InheritsfromBaseForm.htm

And some info about it from MS http://msdn.microsoft.com/en-us/library/aa983613(v=vs.71).aspx

Title: Using Template For Client Forms

Body:
You can have make a base form and use it as a template for other forms by inheriting it rather than inheriting Form.

Base form:

public partial class BaseForm : Form
{
    public BaseForm()
    {
        InitializeComponent();
    }
    protected virtual void closeButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

Form you want to be based on template:

public partial class MainForm : BaseForm
{
    public MainForm()
    {
        InitializeComponent();
    }
}

Here's a larger example in VB http://www.java2s.com/Code/VB/GUI/InheritsfromBaseForm.htm

And some info about it from MS http://msdn.microsoft.com/en-us/library/aa983613(v=vs.71).aspx


问:
Why do access tokens issued by AAD contain information about the user?
I read a lot about OAuth 2.0 and OpenId Connect and in theory I understand both concepts now.

But if I go into practice, some things are still confusing for me and I hope you can enlighten me in some way...

First thing is, that in all code samples how to secure a .net core API in an AAD-environment I find lines like this in the configure-section:

```<code>app.UseAuthentication()
</code>```

and lines like this in the ConfigureServices section:

```<code>        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/xxxxxxxx";
            options.Audience = "xxxx-xxx-xxx-xxx-xxxx";
        });
</code>```

However, to access my API I am not using an ID token, but an access token what is Authorization, not "Authentication" like in the code samples.

This works - but I do not understand it 100%.

So my first question is:

Is the access token also "authenticating" in some way?

The second thing:

I read that access tokens have no standardized format. They can be JWT or not, can have an audience or not etc. For this reason you could even put user information in the token like microsoft does. The access tokens contain claims like a "family name" or "given name" etc.

Id tokens in contrast have a standardized format to ensure that authentication is done in the same way by everyone.

If people are accessing my apis with an access token, I can read their name or e-mail address with "user.identity.name" for example. This value I can use to store the information who edited something or who inserted something.

So I am fetching information about the user with access tokens!

So my second question is:

Am I doing the right thing here? Or should this be done in another way.

and:

Should access tokens ever contain information about the user?

答:
if you check here: https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens
in the newer access tokens, by default it follows the standard of not having any personal information about the user. which is what the standards suggest, Access tokens should not contain much or any information About the user. rather just information for authorization (things that user can access).
However you can always add the optional claims (and azure lets you do it) for personal info, but best practice suggests you shouldn't.

in terms of the addauthentication: Authentication is basically proving who you say you are. addauthentication(), basically calls microsoft azure ad to perform this task, saying hey aad please ask this person who he is, azure then checks and says ya this is a real person, but i won't tell you anything about him other than an id, and they have access to your api/application. So from your snippit, it's fine.

at this point, your serverside shouldn't have any personal information about the user, just that they have access and what scopes/roles. If it wants info about the user, it should then take that authorization (access token) and request it from whatever endpoint that token has access to (graph)

here's a great read about it: https://auth0.com/blog/why-should-use-accesstokens-to-secure-an-api/

Hopefully this helped clarify somewhat, and not add more confusion to the issue.

Body:
I read a lot about OAuth 2.0 and OpenId Connect and in theory I understand both concepts now.

But if I go into practice, some things are still confusing for me and I hope you can enlighten me in some way...

First thing is, that in all code samples how to secure a .net core API in an AAD-environment I find lines like this in the configure-section:

app.UseAuthentication()

and lines like this in the ConfigureServices section:

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/xxxxxxxx";
            options.Audience = "xxxx-xxx-xxx-xxx-xxxx";
        });

However, to access my API I am not using an ID token, but an access token what is Authorization, not "Authentication" like in the code samples.

This works - but I do not understand it 100%.

So my first question is:

Is the access token also "authenticating" in some way?

The second thing:

I read that access tokens have no standardized format. They can be JWT or not, can have an audience or not etc. For this reason you could even put user information in the token like microsoft does. The access tokens contain claims like a "family name" or "given name" etc.

Id tokens in contrast have a standardized format to ensure that authentication is done in the same way by everyone.

If people are accessing my apis with an access token, I can read their name or e-mail address with "user.identity.name" for example. This value I can use to store the information who edited something or who inserted something.

So I am fetching information about the user with access tokens!

So my second question is:

Am I doing the right thing here? Or should this be done in another way.

and:

Should access tokens ever contain information about the user?


问:
Throwing own exceptions
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }
```

<p>Now I also have this exception that I wrote </p>

<pre class="lang-java prettyprint-override"><code>    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }
</code>```

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

```<code>class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}
</code>```

答: Create a method in account class which accepts account number and return true if account is present otherwise false. You can call this method from deposit or withdraw methods and proceed only when it returns true otherwise throw NoSuchAccountException.</p>

Title: Throwing own exceptions

Body:
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }

Now I also have this exception that I wrote

    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}


问:
Lossless manipulation of JPEG in C++
I have a JPEG file on disk which is not quite normal - this JPEG file has additional rubbish data appended behind End Of Image (FFD9). This JPEG file can still be opened by JPEG viewers though.

I wish to remove those additional information behind End Of Image (FFD9). The constraints are:

Must be done programatically

Must be lossless

Must use native code, e.g. C++

One way I've found out is to re-save the file using IrfanView command-line tool, using lossless JPG_TRANSFORM's command: /jpg_rotate. The additional data behind are automatically stripped off.

However, is there another way in which I can do it in C++ code, If possible, I do not wish to use exes like IrfanView to do it. I wish to do everything in code to keep things lean.

I am thinking of detecting the End Of File (FFD9), then save the buffer before EOF into another JPEG. But, how can I save the buffer losslessly?

答:
I guess this is a file handling question and NOT an Image Processing related.

All you need to do write all data till EOF in your Image file into the resultant Image file.

Title: Lossless manipulation of JPEG in C++


问:
How to give Flutter SDK Path in Android Studio on Mac os, How to update Flutter SDK path in MACOS?
I have installed the Android studio and the plugin's DART,FLUTTER to kickstart the flutter but as i am not able to give path of sdk while creating my very first project for flutter. </p>

答:
I asked the people that made the flutter plugin and they helped me out. For making flutter work with your IDE (haven't done this in Android but have in VScodium or Vscode).

In command line:
asdf where flutter

In a text document:

export FLUTTER_ROOT="$/asdf/where/flutter/answer/should/go/here"

Add that to your bash_profile above the asdf part. Or your asdf installation won't work.
With nano: ctrl+o, enter, ctrl+x.

Give your IDE the path to the installation, it should work. If not, the change needs to take effect, restart your computer.


问:
Fetch a specific file from a Git Repo into a fork
I have forked a git repo and then later deleted a file in the fork and committed changes to the fork. Is there a way to just get this one file back from the original repo? Is this possible without having to revert my delete commit in the fork?</p>

答: Certainly, you can get the file back even from your repo. Remember, your clone contains a copy of the entire history, meaning every commit — and every commit contains all your files at the time of the commit, and no commit is ever lost. You just need to know the SHA of the last commit before the commit that deleted it. Then git checkout <SHA-of-commit> -- <path-of-file>.