问:
Best Practices when Choosing SQL Keys Types
I am very new to the SQL database. I need to create a database for my internship as our DA resigned suddenly.

The data is available but it is not inputted into a database yet. I am trying to follow the tutorials online but got stuck on what to choose for the different key types.

I hope to get the feedback of more experienced folks to get your guidance.

Table columns:

```<code>entry id (unique)
entry timestamp
username (unique but can appear more than once if the same user input a new meal record)
email address
user first and last name
meals taken date
meal type
meal calories
meal duration
meal cost
meal location
user notes
</code>```

For primary key = entry id

For candidate key, I will pick username & and entry ID. Are there other columns that I should select as candidate keys? Would email make more sense? But a username can be repeated if they input another meal record. Does that matter?

```<code>For compound Key =
email address + user first and last name?
record date + user name?
</code>```

Are there other keys I need to classify?

Online tutorials these are the most basic keys I need to identify. But I am not sure if I am making the right choice. I appreciate any feedback.

答:
I don't know what database you're using, I'll use Postgres because it's free, follows the SQL standard, has good documentation, and is very powerful.

As Gordon said, you seem to have three things: users, meals, and locations. Three things means one table for each. This avoids storing redundant data. The whole topic is database normalization.

```<code>create table users (
    id bigserial primary key,
    username text not null unique,
    email text not null unique,
    first_name text not null,
    last_name text not null
);

create table meals (
    id bigserial primary key,
    type text not null unique,
    -- If calories vary by user, move this into user_meals.
    calories integer not null
);

create table locations (
    id bigserial primary key,
    -- The specific information you have about a location will vary,
    -- but this is a good start. I've allowed nulls because often
    -- people don't have full information about their location.
    name text,
    address text,
    city text,
    province text,
    country text,
    postal_code text
);
</code>```

You asked about compound keys. Don't bother. There's too many potential problems. Use a simple, unique, auto-incrementing big integer on every table.

Primary keys must be unique and unchanging. Usernames, names, email addresses... these can all change. Even if you think they won't, why bake the risk into your schema?

Foreign keys will be repeated all over the database and indexes many times. You want them to be small and simple and fixed size to not use up any more storage than necessary. Integers are small and simple and fixed size. Text is not.

Compound primary keys potentially leak information. A primary keys refer to a row, and those often show up in URLs and the like. If we were to use the user's email address or name that risks leaking personally identifiable information.

I've chosen bigserial for the primary key. serial types are auto-incrementing so the database will take care of assigning each new row a primary key. bigserial uses a 64 bit integer. A regular integer can only hold about 2 to 4 billion entries. That sounds like a lot, but it isn't, and you do not want to run out of primary keys. bigserial can handle 9 quintillion. An extra 32 bits per row is worth it.

Some more notes.

Everything is not null unless we have a good reason otherwise. This will catch data entry mistakes. It makes the database easier to work with because you know the data will be there.

Similarly, anything which is supposed to be unique is declared unique so it is guaranteed.

There are no arbitrary limits on column size. You might see other examples like email varchar(64) or the like. This doesn't actually save you any space, it just puts limits on what is allowed in the database. There's no fundamental limit on how long a username or email address can be, that's a business rule. Business rules change all the time; they should not be hard coded into the schema. Enforcing business rules is the job of the thing inputting the data, or possibly triggers.

Now that we have these three tables, we can use them to record people's meals. To do that we need a fourth table to record a user having a meal at a location: a join table. A join table is what allows us to keep information about users, meals, and locations each in one canonical place. The users, locations, and meals are referred to by their IDs known as a foreign key.

```<code>create table user_meals (
    id bigserial primary key,

    user_id bigint not null references users(id),
    meal_id bigint not null references meals(id),
    location_id bigint not null references locations(id),

    -- Using a time range is more flexible than start + duration.
    taken_at tstzrange not null,

    -- This can store up to 99999.99 which seems reasonable.
    cost numeric(7, 2) not null,

    notes text,

    -- When was this entry created?
    created_at timestamp not null default current_timestamp,
    -- When was it last updated?
    updated_at timestamp not null default current_timestamp
);
</code>```

Because we're using bigserial for everything's primary key, referring to other tables is simple: they're all bigint.

As before, everything is not null unless we have a good reason otherwise. Not every meal will have notes, for example.

Fairly standard created_at and updated_at fields are used to record when the entry was created or updated.

Imprecise numeric types such as float or double are avoided, especially for money. Instead the arbitrary precision type numeric is used to store money precisely.

numeric requires we give it a precision and scale; we must choose a limit, so I picked something unreasonably high in my currency. Your currency may vary.

Rather than storing a start time and meal duration, we take advantage of Postgres's range types to store a time range from when the meal started to when it ended. This allows us to use range functions and operators to make queries about the meal time much simpler. For example, where taken_at @> '2020-02-15 20:00' finds all meals which were being taken at 8pm on Feb 15th.

There's more to do, such as adding indexes for performance, hopefully this will get you started. If there's one take away it's this: don't try to cram everything into one table.

Try it out.

Body:
I am very new to the SQL database. I need to create a database for my internship as our DA resigned suddenly.

The data is available but it is not inputted into a database yet. I am trying to follow the tutorials online but got stuck on what to choose for the different key types.

I hope to get the feedback of more experienced folks to get your guidance.

Table columns:

entry id (unique)
entry timestamp
username (unique but can appear more than once if the same user input a new meal record)
email address
user first and last name
meals taken date
meal type
meal calories
meal duration
meal cost
meal location
user notes

For primary key = entry id

For candidate key, I will pick username & and entry ID. Are there other columns that I should select as candidate keys? Would email make more sense? But a username can be repeated if they input another meal record. Does that matter?

For compound Key =
email address + user first and last name?
record date + user name?

Are there other keys I need to classify?

Online tutorials these are the most basic keys I need to identify. But I am not sure if I am making the right choice. I appreciate any feedback.

Body:
I don't know what database you're using, I'll use Postgres because it's free, follows the SQL standard, has good documentation, and is very powerful.

As Gordon said, you seem to have three things: users, meals, and locations. Three things means one table for each. This avoids storing redundant data. The whole topic is database normalization.

create table users (
    id bigserial primary key,
    username text not null unique,
    email text not null unique,
    first_name text not null,
    last_name text not null
);

create table meals (
    id bigserial primary key,
    type text not null unique,
    -- If calories vary by user, move this into user_meals.
    calories integer not null
);

create table locations (
    id bigserial primary key,
    -- The specific information you have about a location will vary,
    -- but this is a good start. I've allowed nulls because often
    -- people don't have full information about their location.
    name text,
    address text,
    city text,
    province text,
    country text,
    postal_code text
);

You asked about compound keys. Don't bother. There's too many potential problems. Use a simple, unique, auto-incrementing big integer on every table.

Primary keys must be unique and unchanging. Usernames, names, email addresses... these can all change. Even if you think they won't, why bake the risk into your schema?

Foreign keys will be repeated all over the database and indexes many times. You want them to be small and simple and fixed size to not use up any more storage than necessary. Integers are small and simple and fixed size. Text is not.

Compound primary keys potentially leak information. A primary keys refer to a row, and those often show up in URLs and the like. If we were to use the user's email address or name that risks leaking personally identifiable information.

I've chosen bigserial for the primary key. serial types are auto-incrementing so the database will take care of assigning each new row a primary key. bigserial uses a 64 bit integer. A regular integer can only hold about 2 to 4 billion entries. That sounds like a lot, but it isn't, and you do not want to run out of primary keys. bigserial can handle 9 quintillion. An extra 32 bits per row is worth it.

Some more notes.

Everything is not null unless we have a good reason otherwise. This will catch data entry mistakes. It makes the database easier to work with because you know the data will be there.

Similarly, anything which is supposed to be unique is declared unique so it is guaranteed.

There are no arbitrary limits on column size. You might see other examples like email varchar(64) or the like. This doesn't actually save you any space, it just puts limits on what is allowed in the database. There's no fundamental limit on how long a username or email address can be, that's a business rule. Business rules change all the time; they should not be hard coded into the schema. Enforcing business rules is the job of the thing inputting the data, or possibly triggers.

Now that we have these three tables, we can use them to record people's meals. To do that we need a fourth table to record a user having a meal at a location: a join table. A join table is what allows us to keep information about users, meals, and locations each in one canonical place. The users, locations, and meals are referred to by their IDs known as a foreign key.

create table user_meals (
    id bigserial primary key,

    user_id bigint not null references users(id),
    meal_id bigint not null references meals(id),
    location_id bigint not null references locations(id),

    -- Using a time range is more flexible than start + duration.
    taken_at tstzrange not null,

    -- This can store up to 99999.99 which seems reasonable.
    cost numeric(7, 2) not null,

    notes text,

    -- When was this entry created?
    created_at timestamp not null default current_timestamp,
    -- When was it last updated?
    updated_at timestamp not null default current_timestamp
);

Because we're using bigserial for everything's primary key, referring to other tables is simple: they're all bigint.

As before, everything is not null unless we have a good reason otherwise. Not every meal will have notes, for example.

Fairly standard created_at and updated_at fields are used to record when the entry was created or updated.

Imprecise numeric types such as float or double are avoided, especially for money. Instead the arbitrary precision type numeric is used to store money precisely.

numeric requires we give it a precision and scale; we must choose a limit, so I picked something unreasonably high in my currency. Your currency may vary.

Rather than storing a start time and meal duration, we take advantage of Postgres's range types to store a time range from when the meal started to when it ended. This allows us to use range functions and operators to make queries about the meal time much simpler. For example, where taken_at @> '2020-02-15 20:00' finds all meals which were being taken at 8pm on Feb 15th.

There's more to do, such as adding indexes for performance, hopefully this will get you started. If there's one take away it's this: don't try to cram everything into one table.

Try it out.


来源: stackexchange

问:
Can I use static class for my Logger?
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

```<code>class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}
</code>```

I can use whenever i want in my appliaction like this:

```<code>Logger::add('My log 1');
</code>```

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?

答:
While there is nothing wrong with that approach, I recently moved from a static logging class approach to log4php in one of my own projects myself.

log4php uses a separate instance of a logging class for each class in your project. When looking at that logging framework, the benefits become obvious.

Logged messages always have a context (the class through which the message was logged). That allows for easy filtering (and make the log slightly more helpful).

ContentLicense: CC BY-SA 3.0

Title: Can I use static class for my Logger?

Body:
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}

I can use whenever i want in my appliaction like this:

Logger::add('My log 1');

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?


问:
Laravel Import Issue
I have this issue when I import excel sheet to Laravel, I'm trying to create table instantly when I import it and creating fields dynamically:

Symfony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected 'if' (T_IF), expecting ']'

this is the import model for importing files

```<code> <?php

 namespace App\Imports;

 use DB;
 use App\People;
 use Maatwebsite\Excel\Concerns\ToModel;
 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;

 class PeopleImport implements ToModel
 {
        // importing excel sheet or creating new schema

        public function model(array $row)
        {
          return new People([
             if (!Schema::hasTable($table_name))
                {
                 Schema::connection('mysql')->create($table_name, function (Blueprint $table) use
                 ($ff, $table_name) {
                    if (count($ff) > 0) {
                           foreach ($ff as $field) {
                            $table->longText($field)->nullable();
                            $array[] = $field;
                          }
                      }
                });

                foreach($data->toArray() as $row2) {
                     $insert = DB::table($table_name)->insert($row2);

                }
            }
        ]);
        }
   }
</code>```

and this is the controller for the file import

```<code>   <?php

    namespace App\Http\Controllers;

    use App\People;
    use DB;
    use Illuminate\Http\Request;
    use App\Exports\PeopleExport;
    use App\Imports\PeopleImport;
    use Maatwebsite\Excel\Facades\Excel;
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;

     class PeopleController extends Controller
       {
       /**
       * @return \Illuminate\Support\Collection
       */
       public function view()
       {
         $tables = DB::select('SHOW TABLES');
         return view('view', [ 'tables' => $tables ]);
       }

        /**
        * @return \Illuminate\Support\Collection
        */
        public function export()
        {
          return Excel::download(new PeopleExport, 'people.xlsx');
         }

           /**
           * @return \Illuminate\Support\Collection
           */
           public function import()
           {
           $data = Excel::import(new PeopleImport,request()->file('file'));
           foreach($data->toArray() as $row) {
           $value[] = $row;
           foreach($row as $key => $val) {
                $fields[] = $key;
           }
           }
           $ff = array_unique($fields);

           return back()->withStatus(['تم الرفع']);
        }
   }
</code>```

by the way I'm using laravel 6 and maatwebsite 3.1

答:
return new People([
     if (!Schema::hasTable($table_name))
```

You can't put if inside an array return new People([if hasTable($table_name))...,

place it elsewhere before.

ContentLicense: CC BY-SA 4.0

Title: Laravel Import Issue

Body:
I have this issue when I import excel sheet to Laravel, I'm trying to create table instantly when I import it and creating fields dynamically:

Symfony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected 'if' (T_IF), expecting ']'

this is the import model for importing files

 <?php

 namespace App\Imports;

 use DB;
 use App\People;
 use Maatwebsite\Excel\Concerns\ToModel;
 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;

 class PeopleImport implements ToModel
 {
        // importing excel sheet or creating new schema

        public function model(array $row)
        {
          return new People([
             if (!Schema::hasTable($table_name))
                {
                 Schema::connection('mysql')->create($table_name, function (Blueprint $table) use
                 ($ff, $table_name) {
                    if (count($ff) > 0) {
                           foreach ($ff as $field) {
                            $table->longText($field)->nullable();
                            $array[] = $field;
                          }
                      }
                });

                foreach($data->toArray() as $row2) {
                     $insert = DB::table($table_name)->insert($row2);

                }
            }
        ]);
        }
   }

and this is the controller for the file import

   <?php

    namespace App\Http\Controllers;

    use App\People;
    use DB;
    use Illuminate\Http\Request;
    use App\Exports\PeopleExport;
    use App\Imports\PeopleImport;
    use Maatwebsite\Excel\Facades\Excel;
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;

     class PeopleController extends Controller
       {
       /**
       * @return \Illuminate\Support\Collection
       */
       public function view()
       {
         $tables = DB::select('SHOW TABLES');
         return view('view', [ 'tables' => $tables ]);
       }

        /**
        * @return \Illuminate\Support\Collection
        */
        public function export()
        {
          return Excel::download(new PeopleExport, 'people.xlsx');
         }

           /**
           * @return \Illuminate\Support\Collection
           */
           public function import()
           {
           $data = Excel::import(new PeopleImport,request()->file('file'));
           foreach($data->toArray() as $row) {
           $value[] = $row;
           foreach($row as $key => $val) {
                $fields[] = $key;
           }
           }
           $ff = array_unique($fields);

           return back()->withStatus(['تم الرفع']);
        }
   }

by the way I'm using laravel 6 and maatwebsite 3.1

Body:
return new People([
     if (!Schema::hasTable($table_name))

You can't put if inside an array return new People([if hasTable($table_name))...,

place it elsewhere before.


问:
Recursive Function conversion
My def "gennums" first uses some random values (randomindices) generated by a separate Def, it returns a new set of indices which is then used by the next step, ... etc recursively.

these are the manual steps:

```<code>s1 = gennums(arr,randomindices,9)

s2 = gennums(arr,s1,8)

s3 = gennums(arr,s2,7)

s4 = gennums(arr,s3,6)

s5 = gennums(arr,s4,5)

s6 = gennums(arr,s5,4)

s7 = gennums(arr,s6,3)

s8 = gennums(arr,s7,2)

s9 = gennums(arr,s8,1)
</code>```

I want it to work recursively n number of times until the third argument reaches 1..

something like this..

```<code>def dorecusive(nums):

  count = nums:

  s1 = gennums(arr,randomindices,count)

  count-=1

  while count != 0:
    s2 =(genums,s1,count)
    s1=s2
    return (genums,s1,count)
</code>```

答:
I have no idea about python so please ignore my syntactic mistake.</p>

```<code>def gennums(arr, randomindices, count)
    if count === 1
        return;
    return gennums(arr, randomindices, count--)
</code>```

Title: Recursive Function conversion

Body:
My def "gennums" first uses some random values (randomindices) generated by a separate Def, it returns a new set of indices which is then used by the next step, ... etc recursively.

these are the manual steps:

s1 = gennums(arr,randomindices,9)

s2 = gennums(arr,s1,8)

s3 = gennums(arr,s2,7)

s4 = gennums(arr,s3,6)

s5 = gennums(arr,s4,5)

s6 = gennums(arr,s5,4)

s7 = gennums(arr,s6,3)

s8 = gennums(arr,s7,2)

s9 = gennums(arr,s8,1)

I want it to work recursively n number of times until the third argument reaches 1..

something like this..

def dorecusive(nums):

  count = nums:

  s1 = gennums(arr,randomindices,count)

  count-=1

  while count != 0:
    s2 =(genums,s1,count)
    s1=s2
    return (genums,s1,count)

Body:
I have no idea about python so please ignore my syntactic mistake.

def gennums(arr, randomindices, count)
    if count === 1
        return;
    return gennums(arr, randomindices, count--)


问:
I can not get it to display info by month. Is it the GROUP BY or my LOOP that's messed up?
I need to display the amount of money used by each PAYMENTMETHOD by MONTH.

EXAMPLE:

```<code>    JANUARY RENTALS
         CASH    $300
         VISA    $200
    TOTAL: $500
</code>```

I have tried many different GROUP BY statements and I have tried DISTINCT, but I keep getting the error "NOT A GROUP BY EXPRESSION".
The code (without a GROUP BY expression) displays a long list that repeats the same months. I do not know for sure if the problem is even the GROUP BY or if it's how I have the LOOP set up.

NOTE: All of the data is from the same year, but the date is in the format of 16-DEC-04
This is the code:

```<code>SET SERVEROUTPUT ON;

CREATE OR REPLACE FUNCTION NameMonth (MonthNum INT)
        RETURN VARCHAR2 AS
        Month_Name VARCHAR2(9) := 'Default';
    BEGIN
        CASE
        WHEN MonthNum = 1 THEN  Month_Name := 'January';
        WHEN MonthNum = 2 THEN  Month_Name := 'February';
        WHEN MonthNum = 3 THEN  Month_Name := 'March';
        WHEN MonthNum = 4 THEN  Month_Name := 'April';
        WHEN MonthNum = 5 THEN  Month_Name := 'May';
        WHEN MonthNum = 6 THEN  Month_Name := 'June';
        WHEN MonthNum = 7 THEN  Month_Name := 'July';
        WHEN MonthNum = 8 THEN  Month_Name := 'August';
        WHEN MonthNum = 9 THEN  Month_Name := 'September';
        WHEN MonthNum = 10 THEN  Month_Name := 'October';
        WHEN MonthNum = 11 THEN  Month_Name := 'November';
        WHEN MonthNum = 12 THEN  Month_Name := 'December';
        END CASE;

        RETURN Month_Name;
    END;
 /

 DECLARE
    CURSOR cNameOfMonth IS
        SELECT NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) AS RentMonth, RENTAL.PAYMENTMETHOD, RENTITEM.RENTFEE
        FROM ALLPOWDER.RENTAL, ALLPOWDER.RENTITEM
        WHERE RENTAL.RENTID = RENTITEM.RENTID
        GROUP BY EXTRACT(MONTH FROM RENTAL.RENTDATE)
   -- I've also tried NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) and just RENTAL.RENTDATE
        ORDER BY RentMonth;

    Rental_Rec cNameOfMonth%ROWTYPE;

BEGIN
    OPEN cNameOfMonth;
    LOOP
        FETCH cNameOfMonth INTO Rental_Rec;
        EXIT WHEN cNameOfMonth%NOTFOUND;

        DBMS_OUTPUT.NEW_LINE;
        DBMS_OUTPUT.PUT_LINE(Rental_Rec.RentMonth || ' Rentals ----------------');
    END LOOP;
    CLOSE cNameOfMonth;
END;
/
</code>```

答:
Your function to translate month number to month name is unnecessary, and you're not generating a total. I suspect you wanted something like:

```<code>SELECT INITCAP(TO_CHAR(TRUNC(r.RENTDATE, 'MONTH'), 'MONTH')) AS RENTMONTH,
       INITCAP(r.PAYMENTMETHOD) AS PAYMENTMETHOD,
       SUM(i.RENTFEE) AS TOTAL_RENTFEE
  FROM ALLPOWDER.RENTAL r
  INNER JOIN ALLPOWDER.RENTITEM i
    ON i.RENTID = r.RENTID
  GROUP BY TRUNC(r.RENTDATE, 'MONTH'),
           r.PAYMENTMETHOD
  ORDER BY TRUNC(r.RENTDATE, 'MONTH')
</code>```

db<>fiddle here

Body:
I need to display the amount of money used by each PAYMENTMETHOD by MONTH.

EXAMPLE:

    JANUARY RENTALS
         CASH    $300
         VISA    $200
    TOTAL: $500

I have tried many different GROUP BY statements and I have tried DISTINCT, but I keep getting the error "NOT A GROUP BY EXPRESSION".
The code (without a GROUP BY expression) displays a long list that repeats the same months. I do not know for sure if the problem is even the GROUP BY or if it's how I have the LOOP set up.

NOTE: All of the data is from the same year, but the date is in the format of 16-DEC-04
This is the code:

SET SERVEROUTPUT ON;

CREATE OR REPLACE FUNCTION NameMonth (MonthNum INT)
        RETURN VARCHAR2 AS
        Month_Name VARCHAR2(9) := 'Default';
    BEGIN
        CASE
        WHEN MonthNum = 1 THEN  Month_Name := 'January';
        WHEN MonthNum = 2 THEN  Month_Name := 'February';
        WHEN MonthNum = 3 THEN  Month_Name := 'March';
        WHEN MonthNum = 4 THEN  Month_Name := 'April';
        WHEN MonthNum = 5 THEN  Month_Name := 'May';
        WHEN MonthNum = 6 THEN  Month_Name := 'June';
        WHEN MonthNum = 7 THEN  Month_Name := 'July';
        WHEN MonthNum = 8 THEN  Month_Name := 'August';
        WHEN MonthNum = 9 THEN  Month_Name := 'September';
        WHEN MonthNum = 10 THEN  Month_Name := 'October';
        WHEN MonthNum = 11 THEN  Month_Name := 'November';
        WHEN MonthNum = 12 THEN  Month_Name := 'December';
        END CASE;

        RETURN Month_Name;
    END;
 /

 DECLARE
    CURSOR cNameOfMonth IS
        SELECT NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) AS RentMonth, RENTAL.PAYMENTMETHOD, RENTITEM.RENTFEE
        FROM ALLPOWDER.RENTAL, ALLPOWDER.RENTITEM
        WHERE RENTAL.RENTID = RENTITEM.RENTID
        GROUP BY EXTRACT(MONTH FROM RENTAL.RENTDATE)
   -- I've also tried NameMonth(EXTRACT(MONTH FROM RENTAL.RENTDATE)) and just RENTAL.RENTDATE
        ORDER BY RentMonth;

    Rental_Rec cNameOfMonth%ROWTYPE;

BEGIN
    OPEN cNameOfMonth;
    LOOP
        FETCH cNameOfMonth INTO Rental_Rec;
        EXIT WHEN cNameOfMonth%NOTFOUND;

        DBMS_OUTPUT.NEW_LINE;
        DBMS_OUTPUT.PUT_LINE(Rental_Rec.RentMonth || ' Rentals ----------------');
    END LOOP;
    CLOSE cNameOfMonth;
END;
/

Body:
Your function to translate month number to month name is unnecessary, and you're not generating a total. I suspect you wanted something like:

SELECT INITCAP(TO_CHAR(TRUNC(r.RENTDATE, 'MONTH'), 'MONTH')) AS RENTMONTH,
       INITCAP(r.PAYMENTMETHOD) AS PAYMENTMETHOD,
       SUM(i.RENTFEE) AS TOTAL_RENTFEE
  FROM ALLPOWDER.RENTAL r
  INNER JOIN ALLPOWDER.RENTITEM i
    ON i.RENTID = r.RENTID
  GROUP BY TRUNC(r.RENTDATE, 'MONTH'),
           r.PAYMENTMETHOD
  ORDER BY TRUNC(r.RENTDATE, 'MONTH')

db<>fiddle here


问:
Force locale with Asp.Net Core
I'm having some odd issues with a web application written using Asp.Net Core 1.1, using the full .Net Framework v4.6.2.

I want to force the application to use a swedish locale (sv-SE). This is working just fine on the development machine (of course...) but not on the server where it's supposed to run (running Windows Server 2012r2).

I've tried the following:

1) Putting "SiteLocale": "sv-SE" in the appsettings.json file.

2) Putting the following in the web.config

```<code><configuration>
    <system.web>
        <globalization culture="sv-SE" uiCulture="sv-SE" />
    </system.web>
    ...
</configuration
</code>```

3) In program.cs before initializing application setting the default locale

```<code>System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("sv-SE");
</code>```

4) Added RequestLocalization to Configure(...) in Startup.cs

```<code>var supportedCultures = new[]
{
    new CultureInfo("sv-SE")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("sv-SE"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});
</code>```

5) In my controller constructor setting the current threads culture

```<code>System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("sv-SE");
</code>```

6) In my controller actions setting the current threads culture

```<code>System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("sv-SE");
</code>```

7) Installed swedish language pack for the server (server was initially only english)

After doing all of the above any dates or numbers output in the views are still rendered using en-US locale.

Looking at current locale in the view I can see the following:

```<code>System.Globalization.CultureInfo.CurrentCulture.Name => "sv-SE"
System.Globalization.CultureInfo.CurrentUICulture.Name => "sv-SE"
System.Globalization.CultureInfo.InstalledUICulture => "en-US"
</code>```

Again, on my development machine this is working ok, numbers & dates are formatted according to swedish locale. But on the server they are not.

On the server the application is running under the ApplicationPoolIdentity. Which I'm assuming is configured to use "en-US" as locale since the OS was initially installed with english language only.

Perplexed as to why setting CurrentThread.CurrentCulture/CurrentUICulture has no effect.

答:
I had a similar issue with ASP Net Core 3.0. The site hosting was in a different country causing issues with formats.

I added the following to the startup:

```<code>using Microsoft.AspNetCore.Localization;
using System.Globalization;
</code>```

in ConfigureServices:

```<code>services.AddLocalization();
</code>```

in Configure:

```<code>var supportedCultures = new[]{
    new CultureInfo("en-US")
};
app.UseRequestLocalization(new RequestLocalizationOptions {
    DefaultRequestCulture = new RequestCulture("en-US"),
    SupportedCultures = supportedCultures,
    FallBackToParentCultures= false
});
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
</code>```

Title: Force locale with Asp.Net Core

Body:
I'm having some odd issues with a web application written using Asp.Net Core 1.1, using the full .Net Framework v4.6.2.

I want to force the application to use a swedish locale (sv-SE). This is working just fine on the development machine (of course...) but not on the server where it's supposed to run (running Windows Server 2012r2).

I've tried the following:

1) Putting "SiteLocale": "sv-SE" in the appsettings.json file.

2) Putting the following in the web.config

<configuration>
    <system.web>
        <globalization culture="sv-SE" uiCulture="sv-SE" />
    </system.web>
    ...
</configuration

3) In program.cs before initializing application setting the default locale

System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("sv-SE");

4) Added RequestLocalization to Configure(...) in Startup.cs

var supportedCultures = new[]
{
    new CultureInfo("sv-SE")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("sv-SE"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});

5) In my controller constructor setting the current threads culture

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("sv-SE");

6) In my controller actions setting the current threads culture

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("sv-SE");

7) Installed swedish language pack for the server (server was initially only english)

After doing all of the above any dates or numbers output in the views are still rendered using en-US locale.

Looking at current locale in the view I can see the following:

System.Globalization.CultureInfo.CurrentCulture.Name => "sv-SE"
System.Globalization.CultureInfo.CurrentUICulture.Name => "sv-SE"
System.Globalization.CultureInfo.InstalledUICulture => "en-US"

Again, on my development machine this is working ok, numbers & dates are formatted according to swedish locale. But on the server they are not.

On the server the application is running under the ApplicationPoolIdentity. Which I'm assuming is configured to use "en-US" as locale since the OS was initially installed with english language only.

Perplexed as to why setting CurrentThread.CurrentCulture/CurrentUICulture has no effect.

Body:
I had a similar issue with ASP Net Core 3.0. The site hosting was in a different country causing issues with formats.

I added the following to the startup:

using Microsoft.AspNetCore.Localization;
using System.Globalization;

in ConfigureServices:

services.AddLocalization();

in Configure:

var supportedCultures = new[]{
    new CultureInfo("en-US")
};
app.UseRequestLocalization(new RequestLocalizationOptions {
    DefaultRequestCulture = new RequestCulture("en-US"),
    SupportedCultures = supportedCultures,
    FallBackToParentCultures= false
});
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-US");


问:
Entity Framework Core Auto Increment not working correctly
While trying to insert data using my ASP.NET MVC API, the id being auto generated by Entity Framework seems to be out of bounds causing problems to insert into SQL Server. The object has all the data required to be passed in and the database and already been created using a migration. I'm unsure what is causing this error. Thanks in advance for the help

An example of the id generated:

This is how I insert the data into the database

```<code>_context.Triggers.Add(trigger);
_context.SaveChanges();
</code>```

The model class:

```<code> [Key]
 public int Id { get; set; }
 [Required]
 public int TriggerType { get; set; } //1 overload, 2 power off
 [Required]
 public string UserId { get; set; }
 [Required]
 public string Name { get; set; }
</code>```

答:
If you have anything like this,

```<code>private int _id = -1;
public int Id {get => _name; set => _name = value};
</code>```

Just remove it and try this,

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
</code>```

This solved my problem

Body:
While trying to insert data using my ASP.NET MVC API, the id being auto generated by Entity Framework seems to be out of bounds causing problems to insert into SQL Server. The object has all the data required to be passed in and the database and already been created using a migration. I'm unsure what is causing this error. Thanks in advance for the help

An example of the id generated:

This is how I insert the data into the database

_context.Triggers.Add(trigger);
_context.SaveChanges();

The model class:

 [Key]
 public int Id { get; set; }
 [Required]
 public int TriggerType { get; set; } //1 overload, 2 power off
 [Required]
 public string UserId { get; set; }
 [Required]
 public string Name { get; set; }

Body:
If you have anything like this,

private int _id = -1;
public int Id {get => _name; set => _name = value};

Just remove it and try this,

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

This solved my problem


问:
Android studio doesn't recognize the running emulator
When I run my app from AndroidStudio 0.4.3 using Run I see Choose Device which has two sections choose a running device or Launch Emulator. I don't have a running emulator at the moment so I click the ... to launch AVD manager and start an emulator. At this point I see that under choose a running device the emulator I just launched shows up but its listed as offline.

In the past the offline status went away when the emulator was fully up and running. However, now I've noticed that when the emulator is launched fully, it no longer appears in choose a running device.

I feel like I'm always playing cat and mouse game with android studio picking up the emulator. Is there a better way to do this? Am I missing something?

答: Wipe Data and restarting emulator helped me, hope this helps to someone.


问:
Kubernetes - What exactly is imperative Vs Declarative
I am seeing multiple and different explanations for imperative Vs Declarative for Kubernetes - something like Imperative means when we use yaml files to create the resources to describe the state and declarative vice versa.

what is the real and clear difference between these two. I would really appreciate if you can put the group of commands fall under the same - like Create under imperative way etc ..

答:
Imperative

Official docs on Managing Kubernetes Objects Using Imperative Commands.

Kubernetes objects can quickly be created, updated, and deleted directly using imperative commands built into the kubectl command-line tool.

```<code>kubectl run nginx  --generator=run-pod/v1 --image=nginx

kubectl create service nodeport <myservicename>

kubectl delete pod
</code>```

Declarartive

Kubernetes objects can be created, updated, and deleted by storing multiple object configuration files in a directory and using kubectl apply to recursively create and update those objects as needed. This method retains writes made to live objects without merging the changes back into the object configuration files. kubectl diff also gives you a preview of what changes apply will make.

Official docs on Declarative Management of Kubernetes Objects Using Configuration Files.

Official docs on Declarative Management of Kubernetes Objects Using Kustomize

Define what you want in an yaml file and use kubectl apply

```<code>kubectl apply -f app.yaml

kubectl apply -f <directory>/

kubectl apply -f https://k8s.io/examples/application/simple_deployment.yaml
</code>```

Body:
Imperative

Official docs on Managing Kubernetes Objects Using Imperative Commands.

Kubernetes objects can quickly be created, updated, and deleted directly using imperative commands built into the kubectl command-line tool.

kubectl run nginx  --generator=run-pod/v1 --image=nginx

kubectl create service nodeport <myservicename>

kubectl delete pod

Declarartive

Kubernetes objects can be created, updated, and deleted by storing multiple object configuration files in a directory and using kubectl apply to recursively create and update those objects as needed. This method retains writes made to live objects without merging the changes back into the object configuration files. kubectl diff also gives you a preview of what changes apply will make.

Official docs on Declarative Management of Kubernetes Objects Using Configuration Files.

Official docs on Declarative Management of Kubernetes Objects Using Kustomize

Define what you want in an yaml file and use kubectl apply

kubectl apply -f app.yaml

kubectl apply -f <directory>/

kubectl apply -f https://k8s.io/examples/application/simple_deployment.yaml


问:
String " vs char ' in TS, why is this an Issue again
My background is 30+ years, I'm used to using " for strings and ' for chars, it comes natural for me.

I stayed out of the PHP wars on " vs ' so, lets not raise that issue.

I'm using Typescript, and TS lint is insisting ' instead of ", sure, I can turn it off, but maybe there is a reason in TS compilation? Other than my co-workers env, will it cause problems? why is TSLint insisting?

答:
This is referring to the TSLint quotemark rule. You can configure it in your tslint.json to prefer whichever quote style you prefer.

There's no real language level benefit to using one quote style over the other, but having a single consistent choice in your project can be pretty useful to keep a consistent style.

By the way, TSLint is deprecated, and you'll be better off in the long run using typescript-eslint to lint your TypeScript code with ESLint.


问:
How to find out the password to a .p12 document made in openssl?
I'm trying to publish an iPhone game and I have downloaded everything I need to allow me to publish through flash.  I'm on a pc and I can't figure out what the password is of the .p12 certificate I made in openssl is.  Here are the steps I've used:

I create my key:

```<code>openssl genrsa -out mykey.key 2048
</code>```

I create a CSR with the correct info

```<code>openssl req -new -key mykey.key -out CertificateSigningRequest.certSigningRequest  -subj "/emailAddress=yourAddress@example.com, CN=John Doe, C=US"
</code>```

I upload this to apple and then download the certificate they send me, which I convert to a PEM with this code:

```<code>openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM
</code>```

For my final step, I generate the .p12 using this:

```<code>openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12
</code>```

Flash requires I enter the .p12, the .p12 password, and the provisioning profile I got from apple.  I have no idea what the password is.  I'm very new to openssl so sorry if the answer is obvious.

Here's a link to the tutorial I used if you want any more info:
http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-19aa73f128cc9f05e8-8000.html#WSfffb011ac560372f46768d8712cd1d13954-7ffd

Thanks for any and all help!

答: Normally that    openssl pkcs12 --export prompts for a password.  If not, then the PKCS12 file has a blank/no password. You can pass a password on the commandline if Flash is requiring one and the commandline isn't prompting you.</p>

Body:
I'm trying to publish an iPhone game and I have downloaded everything I need to allow me to publish through flash.  I'm on a pc and I can't figure out what the password is of the .p12 certificate I made in openssl is.  Here are the steps I've used:

I create my key:

openssl genrsa -out mykey.key 2048

I create a CSR with the correct info

openssl req -new -key mykey.key -out CertificateSigningRequest.certSigningRequest  -subj "/emailAddress=yourAddress@example.com, CN=John Doe, C=US"

I upload this to apple and then download the certificate they send me, which I convert to a PEM with this code:

openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM

For my final step, I generate the .p12 using this:

openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12

Flash requires I enter the .p12, the .p12 password, and the provisioning profile I got from apple.  I have no idea what the password is.  I'm very new to openssl so sorry if the answer is obvious.

Here's a link to the tutorial I used if you want any more info:
http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-19aa73f128cc9f05e8-8000.html#WSfffb011ac560372f46768d8712cd1d13954-7ffd

Thanks for any and all help!


问:
Install self-signed certificates no longer working in Android Q
I have generated a self-signed certificate which I tried to install on my phone running Android 10, but a snack appears telling me that Private key required to install certificate.

I have tried on a phone running Android 9 with the same certificate and it works as expected.

Any idea if there is any workaround to get the CA installed?

答:
Building on @ScottyB's answer:

```<code>openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -subj "/C=US/ST=Oklahoma/L=Stillwater/O=My Company/OU=Engineering/CN=test.com" -keyout ca.key -out ca.crt
openssl genrsa -out "test.key" 2048
openssl req -new -key test.key -out test.csr -config openssl.cnf
openssl x509 -req -days 3650 -in test.csr -CA ca.crt -CAkey ca.key -CAcreateserial -extensions v3_req -extfile openssl.cnf -out test.crt
</code>```

The error gives a hint on how to fix. If you combine the certificate and private key generated above into a single file, Android will accept it:

```<code>openssl pkcs12 -export -in test.crt -inkey test.key -out test-combined.p12
</code>```

Transfer the .p12 file to your Android phone, then use Install From Device Storage. Give it a nice human-readable name and the CA certificate can now be used with services like web servers that use the ca.key & ca.crt.

Here's an Nginx config snippet to refuse all connections except those that present a certificate signed by the above ca cert:

```<code># within server block, eg. under the ssl_certificate config
    ssl_client_certificate /etc/ssl/ca/ca.crt;
    ssl_trusted_certificate /etc/ssl/ca/ca.crt;
    ssl_verify_client optional_no_ca;
    if ($ssl_client_verify != SUCCESS) { return 403; }

</code>```

When your Android browser now visits this website, it will only let you in further if you present a signed certificate.

Body:
Building on @ScottyB's answer:

openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -subj "/C=US/ST=Oklahoma/L=Stillwater/O=My Company/OU=Engineering/CN=test.com" -keyout ca.key -out ca.crt
openssl genrsa -out "test.key" 2048
openssl req -new -key test.key -out test.csr -config openssl.cnf
openssl x509 -req -days 3650 -in test.csr -CA ca.crt -CAkey ca.key -CAcreateserial -extensions v3_req -extfile openssl.cnf -out test.crt

The error gives a hint on how to fix. If you combine the certificate and private key generated above into a single file, Android will accept it:

openssl pkcs12 -export -in test.crt -inkey test.key -out test-combined.p12

Transfer the .p12 file to your Android phone, then use Install From Device Storage. Give it a nice human-readable name and the CA certificate can now be used with services like web servers that use the ca.key & ca.crt.

Here's an Nginx config snippet to refuse all connections except those that present a certificate signed by the above ca cert:

# within server block, eg. under the ssl_certificate config
    ssl_client_certificate /etc/ssl/ca/ca.crt;
    ssl_trusted_certificate /etc/ssl/ca/ca.crt;
    ssl_verify_client optional_no_ca;
    if ($ssl_client_verify != SUCCESS) { return 403; }

When your Android browser now visits this website, it will only let you in further if you present a signed certificate.


问:
Turning Off Autocomplete for "password" input fields in Chrome
How can I turn Off Autocomplete for password input fields in a html form.

autocomplete="false"

or

autocomplete="off".

答:
to hide your saved password or any text input that is saved make your input "readonly" and change "onfocus" like this.

<input readonly onfocus="this.removeAttribute('readonly');" autocomplete="off" type="password">```


问:
How to mount a secret to kubernetes StatefulSet
So, looking at the Kubernetes API documentation: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#statefulsetspec-v1-apps it appears that I can indeed have a volume because it uses a podspec and the podspec does have a volume field, so I could list the secret and then mount it like in a deployment, or any other pod.

The problem is that kubernetes seems to think that volumes are not actually in the podspec for StatefulSet? Is this right? How do I mount in a secret to my statefulset if this is true.

error: error validating "mysql-stateful-set.yaml": error validating data: ValidationError(StatefulSet.spec.template.spec.containers[0]): unknown field "volumes" in io.k8s.api.core.v1.Container; if you choose to ignore these errors, turn validation off with --validate=false

StatefulSet:

```<code>apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - port: 3306
    name: database
  selector:
    app: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql # has to match .spec.template.metadata.labels
  serviceName: "mysql"
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: mysql
        image: mysql
        ports:
        - containerPort: 3306
          name: database
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
        - name: mysql
          mountPath: /run/secrets/mysql
        env:
        - name: MYSQL_ROOT_PASSWORD_FILE
          value: /run/secrets/mysql/root-pass
        volumes:
          - name: mysql
            secret:
              secretName: mysql
              items:
                - key: root-pass
                  path: root-pass
                  mode: 511
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: do-block-storage
      resources:
        requests:
          storage: 10Gi```
```

答:
The volume field should come inside template spec and not inside container (as done in your template). Refer this for the exact structure (https://godoc.org/k8s.io/api/apps/v1#StatefulSetSpec), go to PodTemplateSpec and you will find volumes field.

Below template should work for you:

```<code>apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - port: 3306
    name: database
  selector:
    app: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql # has to match .spec.template.metadata.labels
  serviceName: "mysql"
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: mysql
        image: mysql
        ports:
        - containerPort: 3306
          name: database
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
        - name: mysql
          mountPath: /run/secrets/mysql
        env:
        - name: MYSQL_ROOT_PASSWORD_FILE
          value: /run/secrets/mysql/root-pass
      volumes:
       - name: mysql
         secret:
           secretName: mysql
           items:
            - key: root-pass
              path: root-pass
               mode: 511
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: do-block-storage
      resources:
        requests:
          storage: 10Gi
</code>```

Body:
So, looking at the Kubernetes API documentation: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#statefulsetspec-v1-apps it appears that I can indeed have a volume because it uses a podspec and the podspec does have a volume field, so I could list the secret and then mount it like in a deployment, or any other pod.

The problem is that kubernetes seems to think that volumes are not actually in the podspec for StatefulSet? Is this right? How do I mount in a secret to my statefulset if this is true.

error: error validating "mysql-stateful-set.yaml": error validating data: ValidationError(StatefulSet.spec.template.spec.containers[0]): unknown field "volumes" in io.k8s.api.core.v1.Container; if you choose to ignore these errors, turn validation off with --validate=false

StatefulSet:

apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - port: 3306
    name: database
  selector:
    app: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql # has to match .spec.template.metadata.labels
  serviceName: "mysql"
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: mysql
        image: mysql
        ports:
        - containerPort: 3306
          name: database
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
        - name: mysql
          mountPath: /run/secrets/mysql
        env:
        - name: MYSQL_ROOT_PASSWORD_FILE
          value: /run/secrets/mysql/root-pass
        volumes:
          - name: mysql
            secret:
              secretName: mysql
              items:
                - key: root-pass
                  path: root-pass
                  mode: 511
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: do-block-storage
      resources:
        requests:
          storage: 10Gi```

Body:
The volume field should come inside template spec and not inside container (as done in your template). Refer this for the exact structure (https://godoc.org/k8s.io/api/apps/v1#StatefulSetSpec), go to PodTemplateSpec and you will find volumes field.

Below template should work for you:

apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - port: 3306
    name: database
  selector:
    app: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql # has to match .spec.template.metadata.labels
  serviceName: "mysql"
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: mysql
        image: mysql
        ports:
        - containerPort: 3306
          name: database
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
        - name: mysql
          mountPath: /run/secrets/mysql
        env:
        - name: MYSQL_ROOT_PASSWORD_FILE
          value: /run/secrets/mysql/root-pass
      volumes:
       - name: mysql
         secret:
           secretName: mysql
           items:
            - key: root-pass
              path: root-pass
               mode: 511
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: do-block-storage
      resources:
        requests:
          storage: 10Gi


问:
Xcode 4 fails to symbolicate debug builds
It is my understanding that Xcode should be able to automatically symbolicate debug builds so that I don't need to "build and archive" to preserve the .dSYM files. Is this correct? What could be the reason if it doesn't work?
Everything in the crashlog has a proper description except from my own calls:

```<code>9   CoreData     0x340dd340 -[NSManagedObjectContext save:] + 184
10  TodayDev     0x0000b670 0x1000 + 42608
11  TodayDev     0x00005922 0x1000 + 18722
12  UIKit        0x359f061e -[UIApplication significantTimeChange] + 38
</code>```

I have read this question and excluded the mentioned directories from Spotlight. Still no luck.

Thanks.

答: Try my patched version of symbolicatecrash, which should work for debug builds too, as long as you haven't deleted the build.</p>

Body:
It is my understanding that Xcode should be able to automatically symbolicate debug builds so that I don't need to "build and archive" to preserve the .dSYM files. Is this correct? What could be the reason if it doesn't work?
Everything in the crashlog has a proper description except from my own calls:

9   CoreData     0x340dd340 -[NSManagedObjectContext save:] + 184
10  TodayDev     0x0000b670 0x1000 + 42608
11  TodayDev     0x00005922 0x1000 + 18722
12  UIKit        0x359f061e -[UIApplication significantTimeChange] + 38

I have read this question and excluded the mentioned directories from Spotlight. Still no luck.

Thanks.


问:
doFilter method called multiple times when an error is throw in a custom Servlet Filter
I have implemented a filter to check an IP adresses white list with Spring Security.
It works, but if i throw an error in my doFilter method, the throw is called 3 times oO.

I found a solution with "return;", but i am not that happy with it.
It means i have to log my error without using throw...

What do you think, is there any better way ? a best practice ?

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
```

<p>Here is the web configuration</p>

<pre class="lang-java prettyprint-override"><code>    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                        .antMatchers("/**").permitAll().and()
                        .addFilterBefore(new CustomIpFilter(),
                                BasicAuthenticationFilter.class)
                        .csrf().disable()
                        .formLogin().disable();
        }
    }
</code>```

Here is my filter

    @Log4j2
    @WebFilter
    public class CustomIpFilter implements Filter {

        Set<String> whitelist = new HashSet<>();

        public CustomIpFilter() {
            whitelist.add("0:0:0:0:0:0:0:1"); //localhost
            whitelist.add("127.0.0.1");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            String ipAdress = request.getRemoteAddr();
            if (!whitelist.contains(ipAdress)) {
                log.error("Unknown IP adress");
                /* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
                throw new UnknownHostException("Unknown IP adress");*/
                return;
            }
            chain.doFilter(request, response); //Continue
        }

        @Override
        public void destroy() {

        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }
    }
```

<p>The controller used to test</p>

<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping(value = "test")
public class LoggerController {

    @GetMapping("/go")
    public String logsTest() {
        System.out.println("ok");
        return "Ok";
    }
}
</code>```

i have tried the same stuff with an interceptor removing Spring Security using "preHandle" method and i still have 3 times the Throw.
So i start to understand why, look at the logs:

1st Throw

java.net.UnknownHostException: Unknown IP adress
```

<p>2nd Throw</p>

<pre class="lang-java prettyprint-override"><code>[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor              : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception
</code>```

3rd Throw:

[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]
```

Thanks for your help !

答:
To answer my question, here is finally my filter working properly as explained by @rgoers

@Log4j2
@WebFilter
public class CustomIpFilter implements Filter {

    private final Set<String> whitelist = new HashSet<>();
    private final String unauthorizedIpAddressMessage = "CONNECTION REFUSED: Unauthorized IP address: ";

    public CustomIpFilter() {
        whitelist.add("0:0:0:0:0:0:0:1"); //localhost
        whitelist.add("127.0.0.1");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String ipAddress = request.getRemoteAddr();

        if (!isAuthorizedIpAdress(ipAddress)) {
            log.error(unauthorizedIpAddressMessage + ipAddress);
            setUnauthorizedHttpServletResponse(response, unauthorizedIpAddressMessage + ipAddress);
            return;
        }

        chain.doFilter(request, response); //Continue
    }

    public void setUnauthorizedHttpServletResponse(ServletResponse response, String message)
            throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write(message);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    public boolean isAuthorizedIpAdress(String ipAddress) {
        if (Utils.isElementInSetList(whitelist, ipAddress)) {
            return true;
        }
        return false;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
```

Body:
I have implemented a filter to check an IP adresses white list with Spring Security.
It works, but if i throw an error in my doFilter method, the throw is called 3 times oO.

I found a solution with "return;", but i am not that happy with it.
It means i have to log my error without using throw...

What do you think, is there any better way ? a best practice ?

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Here is the web configuration

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                        .antMatchers("/**").permitAll().and()
                        .addFilterBefore(new CustomIpFilter(),
                                BasicAuthenticationFilter.class)
                        .csrf().disable()
                        .formLogin().disable();
        }
    }

Here is my filter

    @Log4j2
    @WebFilter
    public class CustomIpFilter implements Filter {

        Set<String> whitelist = new HashSet<>();

        public CustomIpFilter() {
            whitelist.add("0:0:0:0:0:0:0:1"); //localhost
            whitelist.add("127.0.0.1");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            String ipAdress = request.getRemoteAddr();
            if (!whitelist.contains(ipAdress)) {
                log.error("Unknown IP adress");
                /* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
                throw new UnknownHostException("Unknown IP adress");*/
                return;
            }
            chain.doFilter(request, response); //Continue
        }

        @Override
        public void destroy() {

        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }
    }

The controller used to test

@RestController
@RequestMapping(value = "test")
public class LoggerController {

    @GetMapping("/go")
    public String logsTest() {
        System.out.println("ok");
        return "Ok";
    }
}

i have tried the same stuff with an interceptor removing Spring Security using "preHandle" method and i still have 3 times the Throw.
So i start to understand why, look at the logs:

1st Throw

java.net.UnknownHostException: Unknown IP adress

2nd Throw

[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor              : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

3rd Throw:

[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]

Thanks for your help !


问:
search in array for string match
What i have

```<code>var sentence = 'My country is India';
var array = ['Intel,' 'Goa', 'Green Day', 'India', 'Ice', 'India'];
</code>```

Result i need

```<code>  index = array.indexOf(sentence); // it should return 3
</code>```

And this is what i tried it works but its very slow and freezes and stop working when use big data

```<code>words = sentence.split(' ');
var i;
for (i = 0; i < words.length; i++) {
    w = words[i];
    a = array.indexOf(w);
    console.log(a);
}
</code>```

Update : i tried below solutions but still stop working i am working on google audio to speech so its run continually some one speeak so sentence array triggers again and again i think this is why its freezing after some point

Update 2: In above example i search for single word i.e. "India" but what if i its more than one word like if its a person name like "Neil Armstrong" then split method will not work.

答:
Array#indexOf is an O(n) operation - the interpreter has to iterate through the whole array, worst-case, to see if there's a match or not. When done in a loop, this increases the computational complexity to O(n ^ 2), which will be slow.

You can use a Set instead - Set#has has a complexity of O(1) (reducing the overall complexity to O(n)):

var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
console.log(
  array.findIndex(word => words.has(word))
);```
</div>
</div>
</p>

<p>Or an object (object key lookup is <code>O(1)</code> too):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = Object.fromEntries(
  sentence.split(' ').map(key => [key])
);
console.log(
  array.findIndex(word => words.hasOwnProperty(word))
);</code>```

See how you can also use findIndex to make the code much more concise.

If the item you're hoping to match is composed of two words, also match every occurrence of 2 words next to each other:

var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
const pattern = /(?=(\S+ \S+))/g;
while (true) {
  const match = pattern.exec(sentence);
  if (!match) {
    break;
  }
  words.add(match[1]);
  pattern.lastIndex++;
}
console.log(
  array.findIndex(word => words.has(word))
);```
</div>
</div>
</p>

<p>For a more general solution, you can check the input array to identify which number of words you need to collect, then for each number, iterate over the sentence words to add them to a Set:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const combinationsNeeded = new Set();
for (const substr of array) {
  combinationsNeeded.add(substr.split(' ').length);
}
const wordsSet = new Set();
const sentenceWords = sentence.split(' ');
for (const comb of combinationsNeeded) {
  let endIndex = comb;
  for (let i = 0; i + comb <= sentenceWords.length; i++) {
    // uncomment the below to see all the words wordsSet gets
    // console.log(sentenceWords.slice(i, i + comb).join(' '));
    wordsSet.add(sentenceWords.slice(i, i + comb).join(' '));
  }
}

console.log(
  array.findIndex(substr => wordsSet.has(substr))
);</code>```

Title: search in array for string match

Body:
What i have

var sentence = 'My country is India';
var array = ['Intel,' 'Goa', 'Green Day', 'India', 'Ice', 'India'];

Result i need

  index = array.indexOf(sentence); // it should return 3

And this is what i tried it works but its very slow and freezes and stop working when use big data

words = sentence.split(' ');
var i;
for (i = 0; i < words.length; i++) {
    w = words[i];
    a = array.indexOf(w);
    console.log(a);
}

Update : i tried below solutions but still stop working i am working on google audio to speech so its run continually some one speeak so sentence array triggers again and again i think this is why its freezing after some point

Update 2: In above example i search for single word i.e. "India" but what if i its more than one word like if its a person name like "Neil Armstrong" then split method will not work.

Body:
Array#indexOf is an O(n) operation - the interpreter has to iterate through the whole array, worst-case, to see if there's a match or not. When done in a loop, this increases the computational complexity to O(n ^ 2), which will be slow.

You can use a Set instead - Set#has has a complexity of O(1) (reducing the overall complexity to O(n)):

var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
console.log(
  array.findIndex(word => words.has(word))
);

Or an object (object key lookup is O(1) too):

var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = Object.fromEntries(
  sentence.split(' ').map(key => [key])
);
console.log(
  array.findIndex(word => words.hasOwnProperty(word))
);

See how you can also use findIndex to make the code much more concise.

If the item you're hoping to match is composed of two words, also match every occurrence of 2 words next to each other:

var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
const pattern = /(?=(\S+ \S+))/g;
while (true) {
  const match = pattern.exec(sentence);
  if (!match) {
    break;
  }
  words.add(match[1]);
  pattern.lastIndex++;
}
console.log(
  array.findIndex(word => words.has(word))
);

For a more general solution, you can check the input array to identify which number of words you need to collect, then for each number, iterate over the sentence words to add them to a Set:

var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const combinationsNeeded = new Set();
for (const substr of array) {
  combinationsNeeded.add(substr.split(' ').length);
}
const wordsSet = new Set();
const sentenceWords = sentence.split(' ');
for (const comb of combinationsNeeded) {
  let endIndex = comb;
  for (let i = 0; i + comb <= sentenceWords.length; i++) {
    // uncomment the below to see all the words wordsSet gets
    // console.log(sentenceWords.slice(i, i + comb).join(' '));
    wordsSet.add(sentenceWords.slice(i, i + comb).join(' '));
  }
}

console.log(
  array.findIndex(substr => wordsSet.has(substr))
);


问:
'int' object is not callable when called method of instance class
I don't know how to fix it but I think my code is clear. I am a beginner level python learner.

Here, I made a class Hero that has the method attack. However, when I called the method it says, there is an error 'int' object is not callable.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
      self.name = name
      self.health = hp
      self.attack = att_pwr
      self.defense = def_pwr

    def attack(self):
      print(self.name + ' is attacking')

Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()
```

答:
This is an object class and attack is a property so, you'll use -

Hero1.attack
```


问:
Why isn't this factorial finding algorithm O(n!) run-time complexity?
I discovered this issue by implemented the algorithm from this post: Example of O(n!)?

I tried counting the operations though, and the algorithm loops 64 times when calculating 4! (which is 24).

Is there something I'm missing? Or does this algorithm really just have a run-time complexity that is not O(n!)

var operations = 0;

function factorial(n) {
    for (let i = 0; i < n; i++) {
        operations++;
        factorial(n - 1);
    }
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 64 operations```

答:
You're counting loop operations on every recursion level (i.e. counting function calls except for the outermost one), instead of counting the innermost function calls. Therefore you're getting a much higher count than the plain factorial you were expecting:

```<code>1                         = 1
2 + 2*1                   = 4
3 + 3*2 + 3*2*1           = 15
4 + 4*3 + 4*3*2 + 4*3*2*1 = 64
…
</code>```

The expansions for arbitrary n can be found in https://oeis.org/A007526. These are still limited by O(n!) though - see the closed formulas in the link, e.g. floor(e*n! - 1) or n! * Sum_{k=0..n-1} 1/k!, which are clearly dominated by the n! term. (Counting all invocations gives you https://oeis.org/A000522, n! * Sum_{k=0..n} 1/k!).

To get exactly a factorial, you'd need to count only the innermost function calls:

var operations = 0;

function factorial(n) {
    if (n == 0) operations++;
    for (let i = 0; i < n; i++) {
        factorial(n - 1);
    }
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 64 operations```

Body:
You're counting loop operations on every recursion level (i.e. counting function calls except for the outermost one), instead of counting the innermost function calls. Therefore you're getting a much higher count than the plain factorial you were expecting:

1                         = 1
2 + 2*1                   = 4
3 + 3*2 + 3*2*1           = 15
4 + 4*3 + 4*3*2 + 4*3*2*1 = 64
…

The expansions for arbitrary n can be found in https://oeis.org/A007526. These are still limited by O(n!) though - see the closed formulas in the link, e.g. floor(e*n! - 1) or n! * Sum_{k=0..n-1} 1/k!, which are clearly dominated by the n! term. (Counting all invocations gives you https://oeis.org/A000522, n! * Sum_{k=0..n} 1/k!).

To get exactly a factorial, you'd need to count only the innermost function calls:

var operations = 0;

function factorial(n) {
    if (n == 0) operations++;
    for (let i = 0; i < n; i++) {
        factorial(n - 1);
    }
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 64 operations


问:
Retrieving data from Firebase Realtime Database in Android - recyclerview
I'm trying to retrieve data from Firebase Realtime Database and display this data inside recyclerview but I can't do it and I can't understand why because I tried everything(Google / StackOverflow etc) and nothing works.

The code seems to be ok but when I run the app it gives me these messages: No setter/field for Surname found on class com.example.ipill.Users

I checked how to solve the problem and nothing works, I deleted and create a couple of times the database and nothing.

I'm new to Android Studio and I can't understand what I'm doing wrong.

Below I will attach the code and the database. The thing that I don't understand is that when I add a new Object to the database with Name = Alex I can see the new recycler view containing a new item inside, that means that the apps understand that there are more objects with Name = Alex but can't I retrieve the of that object from the database.

Thank you in advance.

CODE ACTIVITY

```<code>package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;

private RecyclerView mResultList;

private DatabaseReference mUserDatabase;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = (EditText) findViewById(R.id.search_field);

    mSearchBtn = findViewById(R.id.search_btn);
    mResultList = (RecyclerView)findViewById(R.id.result_list);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String searchText = mSearchField.getText().toString();

            firebaseUserSearch(searchText);

        }
    });

}

private void firebaseUserSearch(String searchText) {

    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery

    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.setDetails(model.getName(), model.getSurname());

        }
    };

    mResultList.setAdapter(firebaseRecyclerAdapter);

}

// View Holder Class

public static class UsersViewHolder extends RecyclerView.ViewHolder {

    View mView;

    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

    }

    public void setDetails(String name, String surname) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

        user_name.setText(name);
        user_surname.setText(surname);

    }

}

}
</code>```

DATABASE:

The problem that I have:

```<code>W/PersistentConnection: pc_0 - Using an unspecified index. Your data will be downloaded and filtered
on the client. Consider adding '".indexOn": "Name"' at Users to your security and Firebase Database
rules for better performance
W/ClassMapper: No setter/field for Surname found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/ClassMapper: No setter/field for Name found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/m.example.ipil: Accessing hidden field Landroid/view/View;-
>mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (greylist, reflection, allowed)
</code>```

Model CLASS

```<code>package com.example.ipill;

public class Users {

public String name, surname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Users(String name, String surname, String status) {
    this.name = name;
    this.surname = surname;

}

public Users(){

}

}
</code>```

答: You need  create model class and inside getter setter</p>

Body:
I'm trying to retrieve data from Firebase Realtime Database and display this data inside recyclerview but I can't do it and I can't understand why because I tried everything(Google / StackOverflow etc) and nothing works.

The code seems to be ok but when I run the app it gives me these messages: No setter/field for Surname found on class com.example.ipill.Users

I checked how to solve the problem and nothing works, I deleted and create a couple of times the database and nothing.

I'm new to Android Studio and I can't understand what I'm doing wrong.

Below I will attach the code and the database. The thing that I don't understand is that when I add a new Object to the database with Name = Alex I can see the new recycler view containing a new item inside, that means that the apps understand that there are more objects with Name = Alex but can't I retrieve the of that object from the database.

Thank you in advance.

CODE ACTIVITY

package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;

private RecyclerView mResultList;

private DatabaseReference mUserDatabase;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = (EditText) findViewById(R.id.search_field);

    mSearchBtn = findViewById(R.id.search_btn);
    mResultList = (RecyclerView)findViewById(R.id.result_list);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String searchText = mSearchField.getText().toString();

            firebaseUserSearch(searchText);

        }
    });

}

private void firebaseUserSearch(String searchText) {

    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery

    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.setDetails(model.getName(), model.getSurname());

        }
    };

    mResultList.setAdapter(firebaseRecyclerAdapter);

}

// View Holder Class

public static class UsersViewHolder extends RecyclerView.ViewHolder {

    View mView;

    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

    }

    public void setDetails(String name, String surname) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

        user_name.setText(name);
        user_surname.setText(surname);

    }

}

}

DATABASE:

The problem that I have:

W/PersistentConnection: pc_0 - Using an unspecified index. Your data will be downloaded and filtered
on the client. Consider adding '".indexOn": "Name"' at Users to your security and Firebase Database
rules for better performance
W/ClassMapper: No setter/field for Surname found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/ClassMapper: No setter/field for Name found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/m.example.ipil: Accessing hidden field Landroid/view/View;-
>mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (greylist, reflection, allowed)

Model CLASS

package com.example.ipill;

public class Users {

public String name, surname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Users(String name, String surname, String status) {
    this.name = name;
    this.surname = surname;

}

public Users(){

}

}


问:
CSS: background image on background color
I have panel which I colored blue if this panel is being selected (clicked on it). Additionally, I add a small sign (.png image) to that panel, which indicates that the selected panel has been already selected before.

So if the user sees for example 10 panels and 4 of them have this small sign, he knows that he has already clicked on those panels before. This work fine so far. The problem is now that I can't display the small sign and make the panel blue at the same time.

I set the panel to blue with the css background: #6DB3F2; and the background image with background-image: url('images/checked.png'). But it seems that the background color is above the image so you cannot see the sign.

Is it therefore possible to set z-indexes for the background color and the background image?

答:
This actually works for me:

```<code>background-color: #6DB3F2;
background-image: url('images/checked.png');
</code>```

You can also drop a solid shadow and set the background image:

```<code>background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;
</code>```

If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:

```<code>.btn{
    position: relative;
    background-color: #6DB3F2;
}
.btn:before{
    content: "";
    display: block;
    width: 100%;
    height: 100%;
    position:absolute;
    top:0;
    left:0;
    background-image: url('images/checked.png');
}
</code>```

Body:
This actually works for me:

background-color: #6DB3F2;
background-image: url('images/checked.png');

You can also drop a solid shadow and set the background image:

background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;

If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:

.btn{
    position: relative;
    background-color: #6DB3F2;
}
.btn:before{
    content: "";
    display: block;
    width: 100%;
    height: 100%;
    position:absolute;
    top:0;
    left:0;
    background-image: url('images/checked.png');
}


问:
Converting from Ordinal Time to Date-Time in Python
I want to convert a precise ordinal time array (see below) to date-time format (YYYY-MM-DD hh:mm:ss.sss) in anaconda/python 3. I cannot find any solutions to this problem that considers the precision of the original data.

The ordinal time array looks like:

```<code>[[733414.07083333]
 [733414.07430556]
 [733414.07777778]
 ...
 [737654.10902778]
 [737654.1125    ]
 [737654.11597222]]
</code>```

datetime.fromordinal only works for integer numbers and the decimals MUST be considered in order to obtain the time component to the decimal second.

答:
Thanks to a tip from a friend, who directed me to another website (https://www.programcreek.com/python/example/100062/datetime.datetime.fromordinal), I have found a solution to this challenge. This is the modified script that I used to convert ordinal time to date-time:

```<code>import numpy as _np
import datetime
from datetime import date

def _from_ordinal(x, tz=None) :
    ix = int(x)
    dt = date.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    # compensate for rounding errors
    if microsecond < 10 :
        microsecond = 0
    elif microsecond > 999990 :
        microsecond = _np.subtract(1000000,microsecond)
    dt = datetime.datetime(dt.year, dt.month, dt.day, int(hour), int(minute), int(second), microsecond)
    dt = dt.isoformat(timespec='microseconds')
    if tz is not None:
        dt = dt.astimezone(tz)
    return dt

arrayDateTime = []
for i in range(0,len(arrayOrdinalTime)) :
    dateTime = _from_ordinal(arrayOrdinalTime[i])
    dateTime = dateTime.replace('T', ' ')
    arrayDateTime = _np.append(arrayDateTime, dateTime)
</code>```

Please note, because of the for-loop in this script, processing can take a long time if teh data set is large. I tried to make this work directly with an array, but it failed.

Any tips to make this work directly with an array, therefore to save time, would be appreciated.

Body:
I want to convert a precise ordinal time array (see below) to date-time format (YYYY-MM-DD hh:mm:ss.sss) in anaconda/python 3. I cannot find any solutions to this problem that considers the precision of the original data.

The ordinal time array looks like:

[[733414.07083333]
 [733414.07430556]
 [733414.07777778]
 ...
 [737654.10902778]
 [737654.1125    ]
 [737654.11597222]]

datetime.fromordinal only works for integer numbers and the decimals MUST be considered in order to obtain the time component to the decimal second.

Body:
Thanks to a tip from a friend, who directed me to another website (https://www.programcreek.com/python/example/100062/datetime.datetime.fromordinal), I have found a solution to this challenge. This is the modified script that I used to convert ordinal time to date-time:

import numpy as _np
import datetime
from datetime import date

def _from_ordinal(x, tz=None) :
    ix = int(x)
    dt = date.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    # compensate for rounding errors
    if microsecond < 10 :
        microsecond = 0
    elif microsecond > 999990 :
        microsecond = _np.subtract(1000000,microsecond)
    dt = datetime.datetime(dt.year, dt.month, dt.day, int(hour), int(minute), int(second), microsecond)
    dt = dt.isoformat(timespec='microseconds')
    if tz is not None:
        dt = dt.astimezone(tz)
    return dt

arrayDateTime = []
for i in range(0,len(arrayOrdinalTime)) :
    dateTime = _from_ordinal(arrayOrdinalTime[i])
    dateTime = dateTime.replace('T', ' ')
    arrayDateTime = _np.append(arrayDateTime, dateTime)

Please note, because of the for-loop in this script, processing can take a long time if teh data set is large. I tried to make this work directly with an array, but it failed.

Any tips to make this work directly with an array, therefore to save time, would be appreciated.


问:
in node.js im unable to pass a variable to a member function of a class
I fixed this the right code is below

Im using mongodb and im trying to create a authentication function isAuthenticated that returns true or false if the user is in the database through a callback function. However I can't bring callback inside of client.connect . Im wondering why this is and what I could do to do this.

```<code>function isAuthenticated(username, password, callback1)
{

  //callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err, callback1) {      //client.connect is the mongodb client object

    //callback1(true); <<<<<<< THIS DOESNT WORK HERE SAYS callback is not a function

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});
</code>```

right code:

```<code>function isAuthenticated(username, password, callback1)
{

  return callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err) {      //client.connect is the mongodb client object

    return callback1(true); <<<<<<< WORKS NOW

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});
</code>```

答:
Turn isAuthenticated into a promise and resolve instead of using a callback is quick and (in my limited experience) better for controlling the flow. That's if you can use promises of course.</p>

```<code>function isAuthenticated(usename,pass){
return new Promise((resolve,reject)=>{
... insert code here...
})});
    isAuthenticated("user1", "pass1")
.then((result)=>
{
    console.log("callback ran");
    console.log("result: " + result);
});
</code>```

Body:
I fixed this the right code is below

Im using mongodb and im trying to create a authentication function isAuthenticated that returns true or false if the user is in the database through a callback function. However I can't bring callback inside of client.connect . Im wondering why this is and what I could do to do this.

function isAuthenticated(username, password, callback1)
{

  //callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err, callback1) {      //client.connect is the mongodb client object

    //callback1(true); <<<<<<< THIS DOESNT WORK HERE SAYS callback is not a function

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});

right code:

function isAuthenticated(username, password, callback1)
{

  return callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err) {      //client.connect is the mongodb client object

    return callback1(true); <<<<<<< WORKS NOW

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});

Body:
Turn isAuthenticated into a promise and resolve instead of using a callback is quick and (in my limited experience) better for controlling the flow. That's if you can use promises of course.

function isAuthenticated(usename,pass){
return new Promise((resolve,reject)=>{
... insert code here...
})});
    isAuthenticated("user1", "pass1")
.then((result)=>
{
    console.log("callback ran");
    console.log("result: " + result);
});


问:
Identity auto increment not applied on column
After the DB Migration when the tables were created in the Database, the Identity Auto-increment was not applied to the 'Id' Column whereas the Primary Key constraint was applied to it.

    Following is the Model class code.

```<code>public class Subscription
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }
    public string domainName { get; set; }
    public string articleID { get; set; }
    public string tld { get; set; }
    public string customerID { get; set; }
    public string customerName { get; set; }
    public string price { get; set; }
    public string nextBillDate { get; set; }

}
</code>```

And following are the columns from the Table that was generated.

Can someone please help me with how to cleanly apply auto increment in 'Id' Column. I want it to have both the Primary key and the auto increment.

Edit:
I changed the type of Id to int but still the auto-increment is not applied to it.Here's a screenshot.

答:
If you have anything like this,

```<code>private int _id = -1;
public int Id {get => _name; set => _name = value};
</code>```

Just remove it and try this,

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
</code>```

This solved my problem

Body:
After the DB Migration when the tables were created in the Database, the Identity Auto-increment was not applied to the 'Id' Column whereas the Primary Key constraint was applied to it.

    Following is the Model class code.

public class Subscription
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }
    public string domainName { get; set; }
    public string articleID { get; set; }
    public string tld { get; set; }
    public string customerID { get; set; }
    public string customerName { get; set; }
    public string price { get; set; }
    public string nextBillDate { get; set; }

}

And following are the columns from the Table that was generated.

Can someone please help me with how to cleanly apply auto increment in 'Id' Column. I want it to have both the Primary key and the auto increment.

Edit:
I changed the type of Id to int but still the auto-increment is not applied to it.Here's a screenshot.

Body:
If you have anything like this,

private int _id = -1;
public int Id {get => _name; set => _name = value};

Just remove it and try this,

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

This solved my problem