问:
Change another module state from one module in Vuex
I have two modules in my vuex store.

```<code>var store = new Vuex.Store({
    modules: {
        loading: loading
        posts: posts
    }
});
</code>```

In the module loading, I have a property saving which can be set either true or false and also have a mutation function named TOGGLE_SAVING to set this property.

In the module posts, before and after fetching posts, I want to change the property saving. I am doing it by calling commit('TOGGLE_SAVING') from one of the actions in the posts module.

```<code>var getPosts = function (context) {
    context.commit(TOGGLE_LOADING);
};
</code>```

When it tried to commit, I got following error in the console

```<code>[vuex] unknown local mutation type: TOGGLE_LOADING, global type: posts/TOGGLE_LOADING
</code>```

How can I mutate state in another module using commit?

答:
You can also import the store, as you normally do in any js file and use it. For example:

```<code>// src/state/modules/posts.js

import store from '@/state/store'
...
store.commit('posts/TOGGLE_LOADING')
...
</code>```

This works pretty well, the only donwside is that can difficult isolate tests or mock-up.

Edition: Recently I have eliminated all code using the technique I mention due the testing problems. Indeed you can always change the state of other modules following the recommended way, as in this example. Very useful if you manage auth and profile in distincts modules.

logout: context => {
  return new Promise((resolve) => {
    // Clear token in all axios requests
    axios.defaults.headers.common['Authorization'] = ''
    // Logout from firebase
    firebase
      .auth()
      .signOut()
      .then(() => {
        // Update state in profile module
        context.commit('profile/SET_USER', null, {
          root: true
        })
        resolve()
      })
      .catch(error => reject(error))
  })
}
```

Body:
I have two modules in my vuex store.

var store = new Vuex.Store({
    modules: {
        loading: loading
        posts: posts
    }
});

In the module loading, I have a property saving which can be set either true or false and also have a mutation function named TOGGLE_SAVING to set this property.

In the module posts, before and after fetching posts, I want to change the property saving. I am doing it by calling commit('TOGGLE_SAVING') from one of the actions in the posts module.

var getPosts = function (context) {
    context.commit(TOGGLE_LOADING);
};

When it tried to commit, I got following error in the console

[vuex] unknown local mutation type: TOGGLE_LOADING, global type: posts/TOGGLE_LOADING

How can I mutate state in another module using commit?

Body:
You can also import the store, as you normally do in any js file and use it. For example:

// src/state/modules/posts.js

import store from '@/state/store'
...
store.commit('posts/TOGGLE_LOADING')
...

This works pretty well, the only donwside is that can difficult isolate tests or mock-up.

Edition: Recently I have eliminated all code using the technique I mention due the testing problems. Indeed you can always change the state of other modules following the recommended way, as in this example. Very useful if you manage auth and profile in distincts modules.

logout: context => {
  return new Promise((resolve) => {
    // Clear token in all axios requests
    axios.defaults.headers.common['Authorization'] = ''
    // Logout from firebase
    firebase
      .auth()
      .signOut()
      .then(() => {
        // Update state in profile module
        context.commit('profile/SET_USER', null, {
          root: true
        })
        resolve()
      })
      .catch(error => reject(error))
  })
}


来源: stackexchange

问:
JAVA: What are the advantages of an InvocationHandler over an implementation of an Interface?
In class today, we were talking about reflection in Java programming. A part of the lesson today was about using InvocationHandlers in Java, rather than just implementing an interface.
When I asked the teacher what the advantages were of using an invocation handler, there wasn't a clear answer.
So let's say we have an interface Plugin

```<code>public interface Plugin {
    void calculate(double a, double b);
    String getCommand();
}
</code>```

you can easily implement this interface in a class Multiply

```<code>public class Multiply implements Plugin {
    @Override
    public void calculate(double a, double b){
         return a * b;
    }

    @Override
    public String getCommand(){
         return "*";
    }
}
</code>```

Then why would I prefer another implementation using an InvocationHandler?

```<code> public class MyMock {
     public static Object createMock(Class myClass) {
         InvocationHandler handler = new MyInvocationHandler();
         Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
         return result;
     }
 }
</code>```

Thanks in advance :)

答:
InvocationHandler together with Proxy allow implementation of an interface at runtime, without the faff of compiling interface-specfic code. It is often used to mediate access to an object of a class that implements the same interface. Proxy does not allow changing the behaviour of existing objects or classes.

For instance, it can be used in remote method calling on the client side, forwarding method call across a network to a server.

My first use of Proxy was for logging method calls to a wide interface that represented command received over a wire format. This easily produced very consistent debug output, but required little maintenance when the interface changed.

Java annotation interfaces may be represented by a Proxy proxy object at runtime, to prevent an explosion of classes.

java.beans.EventHandler was useful before lambdas and method references came along, to implement event listeners without bloating jars.

ContentLicense: CC BY-SA 3.0

Body:
In class today, we were talking about reflection in Java programming. A part of the lesson today was about using InvocationHandlers in Java, rather than just implementing an interface.
When I asked the teacher what the advantages were of using an invocation handler, there wasn't a clear answer.
So let's say we have an interface Plugin

public interface Plugin {
    void calculate(double a, double b);
    String getCommand();
}

you can easily implement this interface in a class Multiply

public class Multiply implements Plugin {
    @Override
    public void calculate(double a, double b){
         return a * b;
    }

    @Override
    public String getCommand(){
         return "*";
    }
}

Then why would I prefer another implementation using an InvocationHandler?

 public class MyMock {
     public static Object createMock(Class myClass) {
         InvocationHandler handler = new MyInvocationHandler();
         Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
         return result;
     }
 }

Thanks in advance :)

ContentLicense: CC BY-SA 4.0


问:
how to get first and last day of each month for past 4 years from current date in IBM DB2?
I have written the following code to get past 4 years every first and end of month dates from current date in db2.</p>

```<code>WITH tempdateseries (StartDate,EndDate) AS (
SELECT
    DATE(1) + (YEAR(CURRENT DATE)-5) YEARS AS StartDate,
    LAST_DAY(CURRENT DATE - 4 YEARS) AS EndDate
FROM
    sysibm.sysdummy1
UNION ALL
SELECT
    StartDate + 1 MONTH,
    EndDate
FROM
    tempdateseries
WHERE
    StartDate < LAST_DAY(CURRENT DATE - 1 MONTHS)
    AND EndDate < LAST_DAY(CURRENT DATE - 1 MONTHS))
    SELECT
    *
FROM
    tempdateseries

</code>```

答:
Nice one @Mark Barinstein...

Taking a ride in your approach, but intrudocing two new useful functions from recent releases..

DATE_TRUNC and LAST_DAY

```<code>WITH T (STARTDATE) AS
(
VALUES DATE(DATE_TRUNC('MONTH', CURRENT DATE ) )
  UNION ALL
SELECT STARTDATE - 1 MONTH
FROM T
WHERE CURRENT DATE < STARTDATE - 1 MONTH + 4 YEAR
)
SELECT STARTDATE, LAST_DAY(STARTDATE) ENDDATE
FROM T
ORDER BY STARTDATE DESC
FETCH FIRST 5 ROWS ONLY
</code>```

Body:
I have written the following code to get past 4 years every first and end of month dates from current date in db2.

WITH tempdateseries (StartDate,EndDate) AS (
SELECT
    DATE(1) + (YEAR(CURRENT DATE)-5) YEARS AS StartDate,
    LAST_DAY(CURRENT DATE - 4 YEARS) AS EndDate
FROM
    sysibm.sysdummy1
UNION ALL
SELECT
    StartDate + 1 MONTH,
    EndDate
FROM
    tempdateseries
WHERE
    StartDate < LAST_DAY(CURRENT DATE - 1 MONTHS)
    AND EndDate < LAST_DAY(CURRENT DATE - 1 MONTHS))
    SELECT
    *
FROM
    tempdateseries

Body:
Nice one @Mark Barinstein...

Taking a ride in your approach, but intrudocing two new useful functions from recent releases..

DATE_TRUNC and LAST_DAY

WITH T (STARTDATE) AS
(
VALUES DATE(DATE_TRUNC('MONTH', CURRENT DATE ) )
  UNION ALL
SELECT STARTDATE - 1 MONTH
FROM T
WHERE CURRENT DATE < STARTDATE - 1 MONTH + 4 YEAR
)
SELECT STARTDATE, LAST_DAY(STARTDATE) ENDDATE
FROM T
ORDER BY STARTDATE DESC
FETCH FIRST 5 ROWS ONLY


问:
Print in one line dynamically
I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

```<code>for item in range(1,100):
    print item
</code>```

The result is:

```<code>1
2
3
4
.
.
.
</code>```

How get this to instead look like:

```<code>1 2 3 4 5 ...
</code>```

Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time?

答:
Or even simpler:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)
```

end="\r" will overwrite from the beginning [0:] of the first print.

Title: Print in one line dynamically

Body:
I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for item in range(1,100):
    print item

The result is:

1
2
3
4
.
.
.

How get this to instead look like:

1 2 3 4 5 ...

Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time?

Body:
Or even simpler:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r" will overwrite from the beginning [0:] of the first print.


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
You want something like this:

```<code>int factorial(int n) {
    //calculate the factorial
    return result;
}

int main() {
    int result = factorial(10);  // Calculate 10!
    printf("10! is %d", result);
}
</code>```

P.S. Thanks for being honest about it being homework!

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}

Body:
You want something like this:

int factorial(int n) {
    //calculate the factorial
    return result;
}

int main() {
    int result = factorial(10);  // Calculate 10!
    printf("10! is %d", result);
}

P.S. Thanks for being honest about it being homework!


问:
Why does a CSS svg <rect /> have a thicker stroke on the right and bottom sides?
I've created a few svg-based icons for a small website I'm working on but I'm having trouble getting the stroke to look how I'd like. If you look at this jsfiddle you can see my issue. The stroke for the outer <rect> is 1px all the way around but for some reason the right and bottom sides of that outer square seem to have a thicker stroke than the top and left sides, sort of like a drop shadow effect.

I was thinking that maybe the browser renderer was maybe evaluating the stroke as not being a whole number and was rounding down for the left and top edges and rounding up for the right and bottom edges (like happens in a lot of rasterization problems) but no matter where I move it around the page, it is only ever the right and bottom edges.

Can somebody tell me what is going on here and how to fix it?

Thanks in advance.

答:
What you encounter is indeed a case of surprising sub-pixel rendering. You see, SVG strokes are applied exactly on the path where they are specified. Example: If a path runs from the point (0,0) to (0,5) and is assigned a 1px wide stroke, the stroke covers the rectangle (-0.5,0), (0.5,0), (0.5,5), (-0.5,5). The first one of these images illustrates this:

Your rectangle is drawn from (0,0) (the default position) to (36,36). Therefore the stroke is placed in such a way, that it lies exactly between the screen pixels. That’s the reason for the right and bottom edges to look blurry.

What’s up with the top and left edges? Well, since you didn’t define a size for your SVG image, the browser determined one for you. The default is to start at (0,0) (top-left corner) and make the SVG 300x150 pixels wide.

Since the top and left edges of the rectangle outline are directly on the edge of the image, they still are drawn blurry, but you don’t see the part outside the image. Hence it appears to be a sharp line, but if you look closely, you notice, that it is not fully black, but half transparent.

How to fix this? There are two options. Option 1 is to place the rectangular on half pixels:

```<code><rect x="0.5" y="0.5" .../>
</code>```

The other option is to move the viewport of your image around, so that the image as a whole is shifted for half a pixel:

```<code><svg viewBox="-0.5 -0.5 37 37">
</code>```

Note, that I’ve set width and height of the viewport to 37px. That’s because your rectangle will have a final size of 37px: 36px for the outline, and then 0.5px on every side, where the outer half of the 1px stroke rests.

For a general overview on scaling SVGs I suggest this post on CSS Tricks.

Body:
What you encounter is indeed a case of surprising sub-pixel rendering. You see, SVG strokes are applied exactly on the path where they are specified. Example: If a path runs from the point (0,0) to (0,5) and is assigned a 1px wide stroke, the stroke covers the rectangle (-0.5,0), (0.5,0), (0.5,5), (-0.5,5). The first one of these images illustrates this:

Your rectangle is drawn from (0,0) (the default position) to (36,36). Therefore the stroke is placed in such a way, that it lies exactly between the screen pixels. That’s the reason for the right and bottom edges to look blurry.

What’s up with the top and left edges? Well, since you didn’t define a size for your SVG image, the browser determined one for you. The default is to start at (0,0) (top-left corner) and make the SVG 300x150 pixels wide.

Since the top and left edges of the rectangle outline are directly on the edge of the image, they still are drawn blurry, but you don’t see the part outside the image. Hence it appears to be a sharp line, but if you look closely, you notice, that it is not fully black, but half transparent.

How to fix this? There are two options. Option 1 is to place the rectangular on half pixels:

<rect x="0.5" y="0.5" .../>

The other option is to move the viewport of your image around, so that the image as a whole is shifted for half a pixel:

<svg viewBox="-0.5 -0.5 37 37">

Note, that I’ve set width and height of the viewport to 37px. That’s because your rectangle will have a final size of 37px: 36px for the outline, and then 0.5px on every side, where the outer half of the 1px stroke rests.

For a general overview on scaling SVGs I suggest this post on CSS Tricks.


问:
Filtering Dataframe based on many conditions
here is my problem:

I have a dataFrame that look like this :

```<code>Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

```<code>df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})
</code>```

And then I made the filter by Date and by Score :

```<code>df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))
</code>```

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

```<code>Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

Filter two people by date, best score and from a different country

答:
You can group by a list use the code below:

```<code>df1 = df.set_index('Name').groupby(['Date', 'Country'])['Score'].apply(lambda grp: grp.nlargest(1))
</code>```

It will put out this:

```<code>Date  Country  Name     Score
2012  Mexico   Paul      45
      Sweden   Mike      38
      USA      Hilary    80
2013  France   Ashley    42
      Italy    Silvia    55
      UK       Harry     78
</code>```

EDIT:

Based on new information here is a solution. It might be able to be improved a bit but it works.

```<code>df.sort_values(['Score'],ascending=False, inplace=True)
df.sort_values(['Date'], inplace=True)
df.drop_duplicates(['Date', 'Country'], keep='first', inplace=True)
df1 = df.groupby('Date').head(2).reset_index(drop=True)
</code>```

This outputs

```<code>   Date    Name  Score Country
0  2012  Hilary     80     USA
1  2012    Paul     45  Mexico
2  2013   Harry     78      UK
3  2013  Silvia     55   Italy
</code>```

Body:
here is my problem:

I have a dataFrame that look like this :

Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})

And then I made the filter by Date and by Score :

df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy

Filter two people by date, best score and from a different country

Body:
You can group by a list use the code below:

df1 = df.set_index('Name').groupby(['Date', 'Country'])['Score'].apply(lambda grp: grp.nlargest(1))

It will put out this:

Date  Country  Name     Score
2012  Mexico   Paul      45
      Sweden   Mike      38
      USA      Hilary    80
2013  France   Ashley    42
      Italy    Silvia    55
      UK       Harry     78

EDIT:

Based on new information here is a solution. It might be able to be improved a bit but it works.

df.sort_values(['Score'],ascending=False, inplace=True)
df.sort_values(['Date'], inplace=True)
df.drop_duplicates(['Date', 'Country'], keep='first', inplace=True)
df1 = df.groupby('Date').head(2).reset_index(drop=True)

This outputs

   Date    Name  Score Country
0  2012  Hilary     80     USA
1  2012    Paul     45  Mexico
2  2013   Harry     78      UK
3  2013  Silvia     55   Italy


问:
PostgreSQL table join
I have a lecture attendance database as an uni project.
As one of views, i came up with idea that I could make missed_lectures view with all records of Not attended or Sick attendance types. When I am making this query, it returns 2,5k rows, which is not correct.

Query looks like this

```<code>CREATE OR REPLACE VIEW missed_lectures AS
SELECT CONCAT(s.student_name, ' ', s.student_surname) AS "Student", sc.course_title AS "Study course", atp.attendance_type AS "Attendance type", a.record_date AS "Date"
FROM students AS s, study_courses AS sc, attendance_type AS atp, attendance AS a
WHERE
s.student_id=a.student_id AND
sc.course_id=a.course_id AND
a.attendance_type_id=atp.attendance_type_id AND
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendacne_type='Sick') OR
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendance_type='Not attended')
GROUP BY s.student_name, s.student_surname, sc.course_title, atp.attendance_type, a.record_date;
</code>```

This is the last query I came up with, but as I mentioned earlier, it returns 2,5k rows with incorrect data.
Can anybody spot the issue here?

EDIT:
 table students is

```<code>CREATE TABLE students(
student_id serial PRIMARY KEY NOT NULL,
student_name VARCHAR(30) NOT NULL,
student_surname VARCHAR(35) NOT NULL,
matriculation_number VARCHAR(7) NOT NULL CHECK(matriculation_number ~ '[A-Z]{2}[0-9]{5}'),
faculty_id INT NOT NULL,
course INT NOT NULL,
phone_number CHAR(8) CHECK(phone_number ~ '^2{1}[0-9]{7}'),
email VARCHAR(35),
gender VARCHAR(10)
);
</code>```

sample data:

```<code>INSERT INTO students (student_name, student_surname, matriculation_number, faculty_id, course, phone_number, email, gender)
VALUES
('Sandis','Bērziņš','IT19047',7,1,'25404213','sandis.berzins@gmail.com','man'),
('Einārs','Kļaviņš','IT19045',7,1,'24354654','einars.klavins@gmail.com','man'),
('Jana','Lapa','EF18034',8,2,'26224941','lapajana@inbox.lv','woman'),
('Sanija','Bērza','EF18034',8,2,'24543433','berzasanija@inbox.lv','woman'),
('Valdis','Sijāts','TF19034',4,1,'25456545','valdis.sijats@gmail.com','man'),
('Jānis','Bānis','IT17034',7,3,'24658595','banis.janis@inbox.lv','man');
</code>```

table study_courses is

```<code>CREATE TABLE study_courses(
course_id serial PRIMARY KEY NOT NULL,
course_title VARCHAR(55) NOT NULL,
course_code VARCHAR(8) NOT NULL CHECK(course_code ~ '[a-zA-Z]{4}[0-9]{4}'),
credit_points INT
);
</code>```

sample data:

```<code>INSERT INTO study_courses (course_title, course_code, credit_points)
VALUES
('Fundamentals of Law','JurZ2005',2),
('Database technologies II','DatZ2005',2),
('Product processing','PārZ3049',4),
('Arhitecture','Arhi3063',3),
('Forest soils','LauZ1015',4);
</code>```

Table attendance_type is:

```<code>CREATE TABLE attendance_type(
attendance_type_id serial PRIMARY KEY NOT NULL,
attendance_type VARCHAR(15) NOT NULL
);
</code>```

sample data:

```<code>INSERT INTO attendance_type (attendance_type)
VALUES
('Attended'),
('Not attended'),
('Late'),
('Sick');
</code>```

table attendance is:

```<code>CREATE TABLE attendance(
record_id serial PRIMARY KEY NOT NULL,
student_id INT NOT NULL,
course_id INT NOT NULL,
attendance_type_id INT NOT NULL,
lecturer_id INT,
lecture_type_id INT NOT NULL,
audience_id INT NOT NULL,
record_date DATE NOT NULL
);
</code>```

sample data:

```<code>INSERT INTO attendance (student_id, course_id, attendance_type_id, lecturer_id, lecture_type_id, audience_id, record_date)
VALUES
(1,2,1,1,1,14,'20-05-2020'),
(2,2,1,1,1,14,'20-05-2020'),
(6,9,1,13,2,2,'20-05-2020'),
(22,9,2,13,2,2,'20-05-2020'),
(24,9,3,13,2,2,'20-05-2020');
</code>```

Hoping this will help.

答:
The problem is that OR condition in your WHERE clause.

You have to surround it by parentheses if you're going to do it that way.

However, you're already querying the attendance_type table so you can just use it to filter for those two attendance type conditions.

```<code>SELECT
    CONCAT(s.student_name, ' ', s.student_surname) AS "Student",
    sc.course_title AS "Study course",
    atp.attendance_type AS "Attendance type",
    a.record_date AS "Date"
FROM
    students AS s, study_courses AS sc,
    attendance_type AS atp, attendance AS a
WHERE
    s.student_id=a.student_id AND
    sc.course_id=a.course_id AND
    a.attendance_type_id=atp.attendance_type_id AND
    -- filter for these two conditions without subqueries
    atp.attendance_type in ('Sick','Not attended')
GROUP BY
    CONCAT(s.student_name, ' ', s.student_surname), sc.course_title,
    atp.attendance_type, a.record_date;
</code>```

Title: PostgreSQL table join

Body:
I have a lecture attendance database as an uni project.
As one of views, i came up with idea that I could make missed_lectures view with all records of Not attended or Sick attendance types. When I am making this query, it returns 2,5k rows, which is not correct.

Query looks like this

CREATE OR REPLACE VIEW missed_lectures AS
SELECT CONCAT(s.student_name, ' ', s.student_surname) AS "Student", sc.course_title AS "Study course", atp.attendance_type AS "Attendance type", a.record_date AS "Date"
FROM students AS s, study_courses AS sc, attendance_type AS atp, attendance AS a
WHERE
s.student_id=a.student_id AND
sc.course_id=a.course_id AND
a.attendance_type_id=atp.attendance_type_id AND
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendacne_type='Sick') OR
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendance_type='Not attended')
GROUP BY s.student_name, s.student_surname, sc.course_title, atp.attendance_type, a.record_date;

This is the last query I came up with, but as I mentioned earlier, it returns 2,5k rows with incorrect data.
Can anybody spot the issue here?

EDIT:
 table students is

CREATE TABLE students(
student_id serial PRIMARY KEY NOT NULL,
student_name VARCHAR(30) NOT NULL,
student_surname VARCHAR(35) NOT NULL,
matriculation_number VARCHAR(7) NOT NULL CHECK(matriculation_number ~ '[A-Z]{2}[0-9]{5}'),
faculty_id INT NOT NULL,
course INT NOT NULL,
phone_number CHAR(8) CHECK(phone_number ~ '^2{1}[0-9]{7}'),
email VARCHAR(35),
gender VARCHAR(10)
);

sample data:

INSERT INTO students (student_name, student_surname, matriculation_number, faculty_id, course, phone_number, email, gender)
VALUES
('Sandis','Bērziņš','IT19047',7,1,'25404213','sandis.berzins@gmail.com','man'),
('Einārs','Kļaviņš','IT19045',7,1,'24354654','einars.klavins@gmail.com','man'),
('Jana','Lapa','EF18034',8,2,'26224941','lapajana@inbox.lv','woman'),
('Sanija','Bērza','EF18034',8,2,'24543433','berzasanija@inbox.lv','woman'),
('Valdis','Sijāts','TF19034',4,1,'25456545','valdis.sijats@gmail.com','man'),
('Jānis','Bānis','IT17034',7,3,'24658595','banis.janis@inbox.lv','man');

table study_courses is

CREATE TABLE study_courses(
course_id serial PRIMARY KEY NOT NULL,
course_title VARCHAR(55) NOT NULL,
course_code VARCHAR(8) NOT NULL CHECK(course_code ~ '[a-zA-Z]{4}[0-9]{4}'),
credit_points INT
);

sample data:

INSERT INTO study_courses (course_title, course_code, credit_points)
VALUES
('Fundamentals of Law','JurZ2005',2),
('Database technologies II','DatZ2005',2),
('Product processing','PārZ3049',4),
('Arhitecture','Arhi3063',3),
('Forest soils','LauZ1015',4);

Table attendance_type is:

CREATE TABLE attendance_type(
attendance_type_id serial PRIMARY KEY NOT NULL,
attendance_type VARCHAR(15) NOT NULL
);

sample data:

INSERT INTO attendance_type (attendance_type)
VALUES
('Attended'),
('Not attended'),
('Late'),
('Sick');

table attendance is:

CREATE TABLE attendance(
record_id serial PRIMARY KEY NOT NULL,
student_id INT NOT NULL,
course_id INT NOT NULL,
attendance_type_id INT NOT NULL,
lecturer_id INT,
lecture_type_id INT NOT NULL,
audience_id INT NOT NULL,
record_date DATE NOT NULL
);

sample data:

INSERT INTO attendance (student_id, course_id, attendance_type_id, lecturer_id, lecture_type_id, audience_id, record_date)
VALUES
(1,2,1,1,1,14,'20-05-2020'),
(2,2,1,1,1,14,'20-05-2020'),
(6,9,1,13,2,2,'20-05-2020'),
(22,9,2,13,2,2,'20-05-2020'),
(24,9,3,13,2,2,'20-05-2020');

Hoping this will help.

Body:
The problem is that OR condition in your WHERE clause.

You have to surround it by parentheses if you're going to do it that way.

However, you're already querying the attendance_type table so you can just use it to filter for those two attendance type conditions.

SELECT
    CONCAT(s.student_name, ' ', s.student_surname) AS "Student",
    sc.course_title AS "Study course",
    atp.attendance_type AS "Attendance type",
    a.record_date AS "Date"
FROM
    students AS s, study_courses AS sc,
    attendance_type AS atp, attendance AS a
WHERE
    s.student_id=a.student_id AND
    sc.course_id=a.course_id AND
    a.attendance_type_id=atp.attendance_type_id AND
    -- filter for these two conditions without subqueries
    atp.attendance_type in ('Sick','Not attended')
GROUP BY
    CONCAT(s.student_name, ' ', s.student_surname), sc.course_title,
    atp.attendance_type, a.record_date;


问:
Why is SpringBoot upgrade from 2.3.0 to 2.5.0 failing to start tomcat with Prometheus exceptions?
Previous SpringBoot upgrades have been painless, but our upgrade to 2.5.0 doesn't start.  Here's the sort version of the exception:

```<code>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcMetricsFilter' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'webMvcMetricsFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prometheusMeterRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.class]: Unsatisfied dependency expressed through method 'prometheusMeterRegistry' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prometheusConfig' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.class]: Unsatisfied dependency expressed through method 'prometheusConfig' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'management.metrics.export.prometheus-org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties] from ClassLoader [org.springframework.boot.loader.LaunchedURLClassLoader@7c0e2abd]
</code>```

and the very last exception that seems to be causing this whole mess:

```<code>Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties] from ClassLoader [org.springframework.boot.loader.LaunchedURLClassLoader@7c0e2abd]
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481)
        at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:267)
        ... 103 common frames omitted
Caused by: java.lang.NoClassDefFoundError: io/micrometer/prometheus/HistogramFlavor
        at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
        at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3244)
        at java.base/java.lang.Class.getDeclaredMethods(Class.java:2387)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463)
        ... 105 common frames omitted
Caused by: java.lang.ClassNotFoundException: io.micrometer.prometheus.HistogramFlavor
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:435)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:590)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:129)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:523)
        ... 109 common frames omitted
</code>```

I found this reference: https://github.com/prometheus/client_java/issues/452, and in fact the project includes the dependencies for actuator and micrometer mentioned in that answer. I didn't set this up originally so the interplay between components or how one normally troubleshoots and repairs this kind of thing isn't really clear to me.

答:
From the caused by it looks like Micrometer dependecny is missing or not the correct version, you need to add it to pom.xml of your project. Micrometer is a dimensional-first metrics collection facade whose aim is to allow you to time, count, and gauge your code with a vendor neutral AP.

```<code><dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-spring-legacy</artifactId>
    <version>1.5.1</version>
</dependency>
</code>```

Body:
Previous SpringBoot upgrades have been painless, but our upgrade to 2.5.0 doesn't start.  Here's the sort version of the exception:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcMetricsFilter' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'webMvcMetricsFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prometheusMeterRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.class]: Unsatisfied dependency expressed through method 'prometheusMeterRegistry' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prometheusConfig' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.class]: Unsatisfied dependency expressed through method 'prometheusConfig' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'management.metrics.export.prometheus-org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties] from ClassLoader [org.springframework.boot.loader.LaunchedURLClassLoader@7c0e2abd]

and the very last exception that seems to be causing this whole mess:

Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties] from ClassLoader [org.springframework.boot.loader.LaunchedURLClassLoader@7c0e2abd]
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481)
        at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:267)
        ... 103 common frames omitted
Caused by: java.lang.NoClassDefFoundError: io/micrometer/prometheus/HistogramFlavor
        at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
        at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3244)
        at java.base/java.lang.Class.getDeclaredMethods(Class.java:2387)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463)
        ... 105 common frames omitted
Caused by: java.lang.ClassNotFoundException: io.micrometer.prometheus.HistogramFlavor
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:435)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:590)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:129)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:523)
        ... 109 common frames omitted

I found this reference: https://github.com/prometheus/client_java/issues/452, and in fact the project includes the dependencies for actuator and micrometer mentioned in that answer. I didn't set this up originally so the interplay between components or how one normally troubleshoots and repairs this kind of thing isn't really clear to me.

Body:
From the caused by it looks like Micrometer dependecny is missing or not the correct version, you need to add it to pom.xml of your project. Micrometer is a dimensional-first metrics collection facade whose aim is to allow you to time, count, and gauge your code with a vendor neutral AP.

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-spring-legacy</artifactId>
    <version>1.5.1</version>
</dependency>


Title: Filtering Dataframe based on many conditions

Body:
df.groupby(['Country','Name','Date'])['Score'].agg(Score=('Score','first')).reset_index().drop_duplicates(subset='Country', keep='first')

result


问:
Optimizing MySQL query for the Tatoeba project
I've downloaded the Tatoeba project databases and I'm trying to query them but queries with a subquery are taking way too long.

```<code>-- 800.000 rows approx.
CREATE TABLE `sentences` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `language` char(3) DEFAULT NULL,
  `text` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=912551 DEFAULT CHARSET=utf8

-- 1.5 million rows approx.
CREATE TABLE `links` (
  `sentenceId` int(10) unsigned NOT NULL,
  `translatedId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`sentenceId`,`translatedId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
</code>```

Basically the links table joins two sentences in the sentences table together (the original sentence and one  translation). A sentence can have zero or more translations. So I have an id of a sentence I want to work with and want to grab ALL the translations available.

This query gets me what I want but takes almost 18 seconds to complete.

```<code>SELECT * FROM `sentences` WHERE `id` IN (SELECT `translatedId` FROM `links` WHERE `sentenceId` = 157967);
</code>```

Running both queries by themselves just takes an instant.

What am I doing wrong?

答:
```<code>SELECT `sentences`.* FROM
  `sentences` JOIN
  `links` ON `id` = `translatedId`
WHERE `sentenceId` = 157967;
</code>```

Some versions of MySQL are known not to use indexes in sub-queries.

Body:
I've downloaded the Tatoeba project databases and I'm trying to query them but queries with a subquery are taking way too long.

-- 800.000 rows approx.
CREATE TABLE `sentences` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `language` char(3) DEFAULT NULL,
  `text` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=912551 DEFAULT CHARSET=utf8

-- 1.5 million rows approx.
CREATE TABLE `links` (
  `sentenceId` int(10) unsigned NOT NULL,
  `translatedId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`sentenceId`,`translatedId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Basically the links table joins two sentences in the sentences table together (the original sentence and one  translation). A sentence can have zero or more translations. So I have an id of a sentence I want to work with and want to grab ALL the translations available.

This query gets me what I want but takes almost 18 seconds to complete.

SELECT * FROM `sentences` WHERE `id` IN (SELECT `translatedId` FROM `links` WHERE `sentenceId` = 157967);

Running both queries by themselves just takes an instant.

What am I doing wrong?

Body:
SELECT `sentences`.* FROM
  `sentences` JOIN
  `links` ON `id` = `translatedId`
WHERE `sentenceId` = 157967;

Some versions of MySQL are known not to use indexes in sub-queries.


问:
keypress, ctrl+c (or some combo like that)
I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

```<code>if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}
</code>```

But the example below is easier and less code, but it's not a combo keypress event:

```<code>$(document).keypress("c",function() {
  alert("Just C was pressed..");
});
</code>```

So I want to know if by using this second example, I could do something like:

```<code>$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});
</code>```

is this possible? I've tried it and it didn't work, what am I doing wrong?

答:
Simple way to do it in jQuery  : </p>

```<code>/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});
</code>```

Body:
I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}

But the example below is easier and less code, but it's not a combo keypress event:

$(document).keypress("c",function() {
  alert("Just C was pressed..");
});

So I want to know if by using this second example, I could do something like:

$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});

is this possible? I've tried it and it didn't work, what am I doing wrong?

Body:
Simple way to do it in jQuery  :

/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});


问:
Delete an attachement (an avatar) with Devise
In my registrations/edit.html.erb view file I'd like to add a link to delete a current avatar (if it's attached). I've ended up with something like this:

```<code><% if current_user.avatar.attached? %>
    <%= link_to "Remove avatar", { action: :remove_avatar }, method: :put %>
<% end %>
</code>```

In custom registrations_controller (inherited from Devise::RegistrationsController) I defined a method :remove_avatar:

```<code>def remove_avatar
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    resource.avatar.purge_later
end
</code>```

But I've got this error, which is probably caused by a lack of routes settings.

No route matches {:action=>"remove_avatar", :controller=>"registrations", :locale=>:ru}

What can I do to be able to link_to this method? Thank you.

答:
Probably you would need something like this

```<code>put "remove_avatar", to: "registrations#remove_avatar"
</code>```

in your routes.rb file.

Maybe it can get messier than this because of your directory structure, but it should work

Body:
In my registrations/edit.html.erb view file I'd like to add a link to delete a current avatar (if it's attached). I've ended up with something like this:

<% if current_user.avatar.attached? %>
    <%= link_to "Remove avatar", { action: :remove_avatar }, method: :put %>
<% end %>

In custom registrations_controller (inherited from Devise::RegistrationsController) I defined a method :remove_avatar:

def remove_avatar
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    resource.avatar.purge_later
end

But I've got this error, which is probably caused by a lack of routes settings.

No route matches {:action=>"remove_avatar", :controller=>"registrations", :locale=>:ru}

What can I do to be able to link_to this method? Thank you.

Body:
Probably you would need something like this

put "remove_avatar", to: "registrations#remove_avatar"

in your routes.rb file.

Maybe it can get messier than this because of your directory structure, but it should work


问:
Swift - Process and notification at a certain time
I need an indication of how to do the following process. I already looked for some ways but I didn't find any that worked as I want.

I have an application with a local database. I want once a day at a certain time for the application to read the clients and send a local notification informing who is going to have a birthday.

How do I make this process work both in the background and foreground? I also need it to run at a certain time.

I need to create a process that runs in the background and is scheduled to run at a certain time regardless of the state of the application.

答:
First, import UserNotifications

```<code>import UserNotifications
</code>```

then add the following function that defines what the notification is:

```<code>func notification(month: Int, day: Int, hour: Int, minute: Int, text: String){

    let content = UNMutableNotificationContent()
    content.title = "Put your title Here (birthday)"

//or you can assign it a parameter like text so you can have a different title for each notification
    content.body = text
    content.sound = UNNotificationSound.default

    let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(month: month, day: day, hour: hour, minute: minute), repeats: true)

    let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}
</code>```

in view did load- request using the following code:

```<code>let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in

    }
</code>```

then you can create notifications for very day of the year (that repeat)
I would suggest to make a for..in loop like I do below

Here's a template of the loop you can make to loop through all days

```<code>for x in 1...12 {
    for y in 0...30 {
//(you can find a way to check if 30, 31, or 28 based on x, but for now I'll just do 30)

        notification(month: x, day: y, hour: 10, minute: 00, text: "here you read birthdays from your source and put them in text, you can use x and y to access current month and day")

}
}
</code>```

by the way these notifications will run regardless state of the app

Body:
First, import UserNotifications

import UserNotifications

then add the following function that defines what the notification is:

func notification(month: Int, day: Int, hour: Int, minute: Int, text: String){

    let content = UNMutableNotificationContent()
    content.title = "Put your title Here (birthday)"

//or you can assign it a parameter like text so you can have a different title for each notification
    content.body = text
    content.sound = UNNotificationSound.default

    let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(month: month, day: day, hour: hour, minute: minute), repeats: true)

    let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}

in view did load- request using the following code:

let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in

    }

then you can create notifications for very day of the year (that repeat)
I would suggest to make a for..in loop like I do below

Here's a template of the loop you can make to loop through all days

for x in 1...12 {
    for y in 0...30 {
//(you can find a way to check if 30, 31, or 28 based on x, but for now I'll just do 30)

        notification(month: x, day: y, hour: 10, minute: 00, text: "here you read birthdays from your source and put them in text, you can use x and y to access current month and day")

}
}

by the way these notifications will run regardless state of the app


问:
Microsoft Access Query Results are Empty
I don't understand why I'm getting empty results for my query (company name from Companies table and Shares Outstanding from Shares Outstanding table). Fields are linked (see below).

If I run the query using fields from one table only, I see results; just not when I'm pulling data from several tables.

See the below screenshots for the relationships, query setup and query results.

答:
Those 3 Shares tables should be 1 table with another field for share type (outstanding, short, floating)

Companies table not linking to dependent tables on key fields. Companies table ID field is designated as primary key and should be saved as foreign key in number (long integer) field in dependent table. Just as was done with Sources and Exchanges tables.

Advise not to use exact same field name in multiple tables. Also, should not use spaces nor punctuation/special characters (underscore is only exception) in naming convention.


问:
Golang communicate with LDAP
I'm trying to connect and authenticate a user to ldap with golang.

I'm using the go-ldap-client with the following example code:

```<code>package main

import (
    "log"
    "github.com/jtblin/go-ldap-client"
)

func main() {
    client := &ldap.LDAPClient{
        Base:         "dc=example,dc=com",
        Host:         "ldap.example.com",
        Port:         389,
        UseSSL:       false,
        BindDN:       "uid=readonlysuer,ou=People,dc=example,dc=com",
        BindPassword: "readonlypassword",
        UserFilter:   "(uid=%s)",
        GroupFilter: "(memberUid=%s)",
        Attributes:   []string{"givenName", "sn", "mail", "uid"},
    }
    # It is the responsibility of the caller to close the connection
    defer client.Close()

    ok, user, err := client.Authenticate("username", "password")
    if err != nil {
        log.Fatalf("Error authenticating user %s: %+v", "username", err)
    }
    if !ok {
        log.Fatalf("Authenticating failed for user %s", "username")
    }
    log.Printf("User: %+v", user)

    groups, err := client.GetGroupsOfUser("username")
    if err != nil {
        log.Fatalf("Error getting groups for user %s: %+v", "username", err)
    }
    log.Printf("Groups: %+v", groups)
}
</code>```

The dependency to gopkg.in/ldap.v2 is installed.

The problem is that I'm getting the following error:

```<code>2016/01/15 17:34:55 Error authenticating user username: LDAP Result Code 2 "Protocol Error": ldap: cannot StartTLS (unsupported extended operation)
exit status 1
</code>```

Any hint about this error?

答:
Another possible solution to use go-guardian LDAP strategy

A working example based on Online LDAP Test Server

package main

import (
    "fmt"
    "github.com/shaj13/go-guardian/auth/strategies/ldap"
    "net/http"
)

func main() {
    cfg := ldap.Config{
        BaseDN:       "dc=example,dc=com",
        BindDN:       "cn=read-only-admin,dc=example,dc=com",
        Port:         "389",
        Host:         "ldap.forumsys.com",
        BindPassword: "password",
        Filter:       "(uid=%s)",
    }

    r, _ := http.NewRequest("GET", "/", nil)
    r.SetBasicAuth("tesla", "password")

    user, err := ldap.New(&cfg).Authenticate(r.Context(), r)
    fmt.Println(user, err)
}
```

Title: Golang communicate with LDAP

Body:
I'm trying to connect and authenticate a user to ldap with golang.

I'm using the go-ldap-client with the following example code:

package main

import (
    "log"
    "github.com/jtblin/go-ldap-client"
)

func main() {
    client := &ldap.LDAPClient{
        Base:         "dc=example,dc=com",
        Host:         "ldap.example.com",
        Port:         389,
        UseSSL:       false,
        BindDN:       "uid=readonlysuer,ou=People,dc=example,dc=com",
        BindPassword: "readonlypassword",
        UserFilter:   "(uid=%s)",
        GroupFilter: "(memberUid=%s)",
        Attributes:   []string{"givenName", "sn", "mail", "uid"},
    }
    # It is the responsibility of the caller to close the connection
    defer client.Close()

    ok, user, err := client.Authenticate("username", "password")
    if err != nil {
        log.Fatalf("Error authenticating user %s: %+v", "username", err)
    }
    if !ok {
        log.Fatalf("Authenticating failed for user %s", "username")
    }
    log.Printf("User: %+v", user)

    groups, err := client.GetGroupsOfUser("username")
    if err != nil {
        log.Fatalf("Error getting groups for user %s: %+v", "username", err)
    }
    log.Printf("Groups: %+v", groups)
}

The dependency to gopkg.in/ldap.v2 is installed.

The problem is that I'm getting the following error:

2016/01/15 17:34:55 Error authenticating user username: LDAP Result Code 2 "Protocol Error": ldap: cannot StartTLS (unsupported extended operation)
exit status 1

Any hint about this error?


问:
Why are these two values different when I assign one to the other?
The code below gives different values for c and d when I print them

```<code>import csv

datafile = open('test1.csv', 'r')
datareader = csv.reader(datafile)
c = []
for row in datareader:
    c.append(row)

d = [[0]*2]*2
i=0

while i < 2:

    j=0

    while j < 2:

        d[i][j] = float(c[i][j])

        j=j+1
    i=i+1

print(c)
print(d)
</code>```

答: Lists are mutable elements. You're not creating multiple lists when you do things like [[0]]*10 but creates 10 references to the same object.

Body:
The code below gives different values for c and d when I print them

import csv

datafile = open('test1.csv', 'r')
datareader = csv.reader(datafile)
c = []
for row in datareader:
    c.append(row)

d = [[0]*2]*2
i=0

while i < 2:

    j=0

    while j < 2:

        d[i][j] = float(c[i][j])

        j=j+1
    i=i+1

print(c)
print(d)


问:
react pwa firebase notification not working in android
i'm using firebase for my react PWA push notification , I've got everything setup for web app firebase push notification. when I try requesting a notification to desktop it works perfectly but on android devices when I send notification, event hough Postman gives success and message ID and etc but nothing shows on the screen neither in use, nor in background.</p>

答:
Not saying this is the answer in your case but, I had the same problem (notifications worked on desktop and IOS devices but not on Android). My problem was that I had notifications turned off. On your Android phone or tablet, open the Chrome app and try this.

To the right of the address bar, tap More. Settings. List item

Tap SiteSettings. Notifications.

At the top, turn the setting on or off.


问:
Set width and height for Cupertino Picker
Cupertino Picker in flutter takes 100% width.

How do we give it custom styling? Height, Width, Borders?

I tried putting it inside a container with width and all, didn't work.Instead there was a weird soft edged background when I gave container a color.

答:
you can try wrapping it up with a container and setting width or height</p>

```<code>        Container(
              height: 250,
              child: CupertinoPicker(
                itemExtent: 32,
                onSelectedItemChanged: (value) {
                  setState(() {});
                },
              children:
                        ...
        }),
</code>```

Body:
you can try wrapping it up with a container and setting width or height

        Container(
              height: 250,
              child: CupertinoPicker(
                itemExtent: 32,
                onSelectedItemChanged: (value) {
                  setState(() {});
                },
              children:
                        ...
        }),


问:
I have two git commits that appear the same after a pushed amend
I have a git branch that I am working on locally.  After editing some code and doing a commit and a push to a remote repo, I noticed that I had an error in my commit message.  I used amend to correct this.  First I tried to push, but this was not allowed,  So I did a pull and then a push.  Everything appeared to work.  When I look at the repo, I can see two commits, one for each message (both correct and incorrect, so I guess my correction was useless lol.)  Then I noticed that both commits contained the same code changes.  This seems strange, because I don't think that both should contain code changes.  Does this mean that the changes are applied twice?  Is this a problem that could cause issues later?  Does this need to be fixed?  If so, how do I fix this?

=====

commands

(IDE) Changes made, added and committed

git push -u origin BRANCH_NAME

(IDE) Amend performed

git push (error: failed to push some refs)

git pull

git push

答:
Instead of amend probably you just made another one commit.

Your situation probably looks like this: c1 -> c2 -> c3 (where c2 is incorrect commit, c3 is not needed commit)

You need -f option, open terminal and try this:

1) git checkout my_branch

2) git reset --hard c2

3) change source code

4) git add .

5) git commit --amned

6) now your wim editor will open, and you can change commit msg

7) save changes in your vim editor and exit

8) git log (make sure that there are c1 -> c2 nothing more)

9) git push origin my_branch -f

In future amends do like this:

1) git checkout my_branch

2) git fetch

3) git pull

4) change source code

5) git add .

6) git commit --amend

7) now your vim editor will open, and you can change commit msg

8) save changes in your vim editor and exit

9) git push origin my_branch -f

Be careful "force" option is risky. When You use it, it means You are 100% sure You know what You are doing.


问:
How to Play RAW Audio Files?
I am currently working on a project that consists of a chart that shows audio levels picked up by another device. The charts are made through the flot API and I have zooming and selecting capabilities in order to select a time range on the chart and zoom into that selected region. My next step is to allow the user to listen to the audio that corresponds to that region of the chart. I have the audio files stored on a shared server and all of the files are in individual, minute by minute, RAW data files. I have no experience with using audio in a webpage and am currently struggling on how to complete this task. As far as I have found, the <audio> HTML tag is incapable of processing RAW data files for playback. I have been looking into the Web Audio API but am confused about how it works and how to implement it.

My first question is how do I go about decoding RAW audio files from a server and displaying them on an HTML page for a client to listen to?

My second task is to grab all of the audio files corresponding to the selected range and combine them into one audio output. For example, if the client selected a time range of 1:00pm - 1:50pm, I would need to access 50 RAW data audio files each a minute in length. I would then want to combine them together to produce one single playback sound. Therefore, my second question is if anyone knows a way to accomplish this smoothly.

Thank you for any help anyone has to offer!

答:
RAW files are already decoded PCM audio, but Audio elements can't play PCM directly.  You'll need to append a RIFF/WAV header to the PCM bytes first.  Multiple RAW files could be combined, setting the total sample/frame length in the header.  50 minutes of decoded audio will take up a lot of memory in the browser, so keep an eye on that and measure/optimize accordingly.

initAudio()

async function initAudio() {
  // specify your file and its audio properties
  const url = 'https://dev.anthum.com/audio-worklet/audio/decoded-left.raw'
  const sampleRate = 48000
  const numChannels = 1 // mono or stereo
  const isFloat = true  // integer or floating point

  const buffer = await (await fetch(url)).arrayBuffer()

  // create WAV header
  const [type, format] = isFloat ? [Float32Array, 3] : [Uint8Array, 1]
  const wavHeader = new Uint8Array(buildWaveHeader({
    numFrames: buffer.byteLength / type.BYTES_PER_ELEMENT,
    bytesPerSample: type.BYTES_PER_ELEMENT,
    sampleRate,
    numChannels,
    format
  }))

  // create WAV file with header and downloaded PCM audio
  const wavBytes = new Uint8Array(wavHeader.length + buffer.byteLength)
  wavBytes.set(wavHeader, 0)
  wavBytes.set(new Uint8Array(buffer), wavHeader.length)

  // show audio player
  const audio = document.querySelector('audio')
  const blob = new Blob([wavBytes], { type: 'audio/wav' })
  audio.src = URL.createObjectURL(blob)

  document.querySelector('#loading').hidden = true
  audio.hidden = false
}

// adapted from https://gist.github.com/also/900023
function buildWaveHeader(opts) {
  const numFrames =      opts.numFrames;
  const numChannels =    opts.numChannels || 2;
  const sampleRate =     opts.sampleRate || 44100;
  const bytesPerSample = opts.bytesPerSample || 2;
  const format =         opts.format

  const blockAlign = numChannels * bytesPerSample;
  const byteRate = sampleRate * blockAlign;
  const dataSize = numFrames * blockAlign;

  const buffer = new ArrayBuffer(44);
  const dv = new DataView(buffer);

  let p = 0;

  function writeString(s) {
    for (let i = 0; i < s.length; i++) {
      dv.setUint8(p + i, s.charCodeAt(i));
    }
    p += s.length;
}

  function writeUint32(d) {
    dv.setUint32(p, d, true);
    p += 4;
  }

  function writeUint16(d) {
    dv.setUint16(p, d, true);
    p += 2;
  }

  writeString('RIFF');              // ChunkID
  writeUint32(dataSize + 36);       // ChunkSize
  writeString('WAVE');              // Format
  writeString('fmt ');              // Subchunk1ID
  writeUint32(16);                  // Subchunk1Size
  writeUint16(format);              // AudioFormat
  writeUint16(numChannels);         // NumChannels
  writeUint32(sampleRate);          // SampleRate
  writeUint32(byteRate);            // ByteRate
  writeUint16(blockAlign);          // BlockAlign
  writeUint16(bytesPerSample * 8);  // BitsPerSample
  writeString('data');              // Subchunk2ID
  writeUint32(dataSize);            // Subchunk2Size

  return buffer;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: center;
  padding-top: 1rem;
}
[hidden] {
  display: none;
}
audio {
  display: inline-block;
}</code>```

Loading...

<audio hidden controls></audio>```

Title: How to Play RAW Audio Files?

Body:
RAW files are already decoded PCM audio, but Audio elements can't play PCM directly.  You'll need to append a RIFF/WAV header to the PCM bytes first.  Multiple RAW files could be combined, setting the total sample/frame length in the header.  50 minutes of decoded audio will take up a lot of memory in the browser, so keep an eye on that and measure/optimize accordingly.

initAudio()

async function initAudio() {
  // specify your file and its audio properties
  const url = 'https://dev.anthum.com/audio-worklet/audio/decoded-left.raw'
  const sampleRate = 48000
  const numChannels = 1 // mono or stereo
  const isFloat = true  // integer or floating point

  const buffer = await (await fetch(url)).arrayBuffer()

  // create WAV header
  const [type, format] = isFloat ? [Float32Array, 3] : [Uint8Array, 1]
  const wavHeader = new Uint8Array(buildWaveHeader({
    numFrames: buffer.byteLength / type.BYTES_PER_ELEMENT,
    bytesPerSample: type.BYTES_PER_ELEMENT,
    sampleRate,
    numChannels,
    format
  }))

  // create WAV file with header and downloaded PCM audio
  const wavBytes = new Uint8Array(wavHeader.length + buffer.byteLength)
  wavBytes.set(wavHeader, 0)
  wavBytes.set(new Uint8Array(buffer), wavHeader.length)

  // show audio player
  const audio = document.querySelector('audio')
  const blob = new Blob([wavBytes], { type: 'audio/wav' })
  audio.src = URL.createObjectURL(blob)

  document.querySelector('#loading').hidden = true
  audio.hidden = false
}

// adapted from https://gist.github.com/also/900023
function buildWaveHeader(opts) {
  const numFrames =      opts.numFrames;
  const numChannels =    opts.numChannels || 2;
  const sampleRate =     opts.sampleRate || 44100;
  const bytesPerSample = opts.bytesPerSample || 2;
  const format =         opts.format

  const blockAlign = numChannels * bytesPerSample;
  const byteRate = sampleRate * blockAlign;
  const dataSize = numFrames * blockAlign;

  const buffer = new ArrayBuffer(44);
  const dv = new DataView(buffer);

  let p = 0;

  function writeString(s) {
    for (let i = 0; i < s.length; i++) {
      dv.setUint8(p + i, s.charCodeAt(i));
    }
    p += s.length;
}

  function writeUint32(d) {
    dv.setUint32(p, d, true);
    p += 4;
  }

  function writeUint16(d) {
    dv.setUint16(p, d, true);
    p += 2;
  }

  writeString('RIFF');              // ChunkID
  writeUint32(dataSize + 36);       // ChunkSize
  writeString('WAVE');              // Format
  writeString('fmt ');              // Subchunk1ID
  writeUint32(16);                  // Subchunk1Size
  writeUint16(format);              // AudioFormat
  writeUint16(numChannels);         // NumChannels
  writeUint32(sampleRate);          // SampleRate
  writeUint32(byteRate);            // ByteRate
  writeUint16(blockAlign);          // BlockAlign
  writeUint16(bytesPerSample * 8);  // BitsPerSample
  writeString('data');              // Subchunk2ID
  writeUint32(dataSize);            // Subchunk2Size

  return buffer;
}

body {
  text-align: center;
  padding-top: 1rem;
}
[hidden] {
  display: none;
}
audio {
  display: inline-block;
}

<div id="loading">Loading...</div>
<audio hidden controls></audio>


问:
Making sense of database table references with foreign and primary keys
I am relatively new to database logic, and am trying to figure out how multiple tables should/shouldn't reference each other.

I have a table, 'Book', that should have columns:

```<code>| 'title' | 'genre' | 'author' | 'buyOption' | 'pubDate'
</code>```

I want each book to have the possibility to have 1 or more genres.

I want each book to have the possibility to have 1 or more authors.

I want each book to have the possibility to have 1 or more purchase options ('buyOption').

and each purchase option (Amazon, Walmart, etc.) for each book has a unique url.

What I think makes sense (please correct me where I'm wrong):

```<code>   __________________________
   |                        |
   |           Book         |
   |________________________|
   |Primary Key | book_id   | //seems redundant (same as title_id)...would like to just use title_id, but idk if that's possible
   |------------|-----------|
   |Foreign Key | title_id  | <--------------------------------------------|
   |Foreign Key | bo_id     | <----------------------------------|         |
   |Foreign Key | genre_id  | <--------------------------|       |         |
   |Foreign Key | author_id | <-------------------|      |       |         |
   | - - - - -  | - - - - - |                     |      |       |         |
   |            | pubDate   | //publish date      |      |       |         |
   |________________________|                     |      |       |         |
                                                  |      |       |         |
                                                  |      |       |         |
                                                  |      |       |         |
      __________________________                  |      |       |         |
      |                        |                  |      |       |         |
      |         Authors        |                  |      |       |         |
      |________________________|                  |      |       |         |
      |Primary Key | author_id |------------------|      |       |         |
      |------------|-----------|                         |       |         |
 |--->|Foreign Key | title_id  |                         |       |         |
 |    | - - - - -  | - - - - - |                         |       |         |
 |    |            |  author   |                         |       |         |
 |    |____________|___________|                         |       |         |
 |                                                       |       |         |
 |                                                       |       |         |
 |    __________________________                         |       |         |
 |    |                        |                         |       |         |
 |    |         Genres         |                         |       |         |
 |    |________________________|                         |       |         |
 |    |Primary Key |  genre_id |-------------------------|       |         |
 |    |------------|-----------|                                 |         |
 |--->|Foreign Key |  title_id |                                 |         |
 |    | - - - - -  | - - - - - |                                 |         |
 |    |            |   genre   |                                 |         |
 |    |____________|___________|                                 |         |
 |                                                               |         |
 |    __________________________                                 |         |
 |    |                        |                                 |         |
 |    |       Buy Options      |                                 |         |
 |    |________________________|                                 |         |
 |    |Primary Key |  bo_id    |---------------------------------|         |
 |    |------------|-----------|                                           |
 |--->|Foreign Key | title_id  |                                           |
 |    | - - - - -  | - - - - - |                                           |
 |    |            | buyBrand  |   //(Walmart, Amazon, etc.)               |
 |    |            | buyUrl    |   //(ex: https://www.amzn.com/buyBook1)   |
 |    |____________|___________|                                           |
 |                                                                         |
 |                                                                         |
 |                                                                         |
 |         __________________________                                      |
 |         |                        |                                      |
 |         |          Title         |                                      |
 |         |________________________|                                      |
 |---------|Primary Key | title_id  |--------------------------------------|
           |------------|-----------|
           |            |   title   |
           |____________|___________|
</code>```

Does it make sense to have the title table? If so, can i use its primary key to fill various other tables, as depicted?

If the 'Buy Options' table is going to have a bunch of different options and associated urls for each book, will it be possible to get the buyBrand and buyUrl directly from the main 'Book' table? In the end, I just want a giant table that I can grab cell data from. Right now I'm trying to figure out how to populate tables with my data, and what tables to fill for each piece of data.

(again, I'm new to database logic, so I apologize if my wording is hard to understand)

答:
Your design does not look good. You are describing many-to-many relationships between books and genres, books and authors, books and options.

Storing references to the related genre, author, and option in the books table is not the right way to go: you can only store one related value per book (one genre, one author, one option), while you need many. Instead, for each of these relationships, you should have a separate table, called a bridge table, that references the associations.

On the other hand, information that is dependent on the book (say, the title) should be stored in the book table.

Here is one example for books and genres:

```<code>create table books(
    book_id int primary key,
    title varchar(100),  --dependent column
    pub_date date        --dependent column
);

create table genres(
    genre_id int primary key,
    name varchar(100)
);

create table book_genres(
    book_id int references book(book_id),
    genre_id int references genre(genre_id),
    primary key (book_id, genre_id)
);
</code>```

Now, say you want to list all books that belong to genre 'Sci-Fi'; you would go:

```<code>select b.*
from books b
inner join book_genres bg on bg.book_id = b.book_id
inner join genres g on g.genre_id = bg.genre_id
where g.name = 'Sci-Fi'
</code>```

The same logic should be implemented for each and every many-to-many relationship in your schema.

Body:
I am relatively new to database logic, and am trying to figure out how multiple tables should/shouldn't reference each other.

I have a table, 'Book', that should have columns:

| 'title' | 'genre' | 'author' | 'buyOption' | 'pubDate'

I want each book to have the possibility to have 1 or more genres.

I want each book to have the possibility to have 1 or more authors.

I want each book to have the possibility to have 1 or more purchase options ('buyOption').

and each purchase option (Amazon, Walmart, etc.) for each book has a unique url.

What I think makes sense (please correct me where I'm wrong):

   __________________________
   |                        |
   |           Book         |
   |________________________|
   |Primary Key | book_id   | //seems redundant (same as title_id)...would like to just use title_id, but idk if that's possible
   |------------|-----------|
   |Foreign Key | title_id  | <--------------------------------------------|
   |Foreign Key | bo_id     | <----------------------------------|         |
   |Foreign Key | genre_id  | <--------------------------|       |         |
   |Foreign Key | author_id | <-------------------|      |       |         |
   | - - - - -  | - - - - - |                     |      |       |         |
   |            | pubDate   | //publish date      |      |       |         |
   |________________________|                     |      |       |         |
                                                  |      |       |         |
                                                  |      |       |         |
                                                  |      |       |         |
      __________________________                  |      |       |         |
      |                        |                  |      |       |         |
      |         Authors        |                  |      |       |         |
      |________________________|                  |      |       |         |
      |Primary Key | author_id |------------------|      |       |         |
      |------------|-----------|                         |       |         |
 |--->|Foreign Key | title_id  |                         |       |         |
 |    | - - - - -  | - - - - - |                         |       |         |
 |    |            |  author   |                         |       |         |
 |    |____________|___________|                         |       |         |
 |                                                       |       |         |
 |                                                       |       |         |
 |    __________________________                         |       |         |
 |    |                        |                         |       |         |
 |    |         Genres         |                         |       |         |
 |    |________________________|                         |       |         |
 |    |Primary Key |  genre_id |-------------------------|       |         |
 |    |------------|-----------|                                 |         |
 |--->|Foreign Key |  title_id |                                 |         |
 |    | - - - - -  | - - - - - |                                 |         |
 |    |            |   genre   |                                 |         |
 |    |____________|___________|                                 |         |
 |                                                               |         |
 |    __________________________                                 |         |
 |    |                        |                                 |         |
 |    |       Buy Options      |                                 |         |
 |    |________________________|                                 |         |
 |    |Primary Key |  bo_id    |---------------------------------|         |
 |    |------------|-----------|                                           |
 |--->|Foreign Key | title_id  |                                           |
 |    | - - - - -  | - - - - - |                                           |
 |    |            | buyBrand  |   //(Walmart, Amazon, etc.)               |
 |    |            | buyUrl    |   //(ex: https://www.amzn.com/buyBook1)   |
 |    |____________|___________|                                           |
 |                                                                         |
 |                                                                         |
 |                                                                         |
 |         __________________________                                      |
 |         |                        |                                      |
 |         |          Title         |                                      |
 |         |________________________|                                      |
 |---------|Primary Key | title_id  |--------------------------------------|
           |------------|-----------|
           |            |   title   |
           |____________|___________|

Does it make sense to have the title table? If so, can i use its primary key to fill various other tables, as depicted?

If the 'Buy Options' table is going to have a bunch of different options and associated urls for each book, will it be possible to get the buyBrand and buyUrl directly from the main 'Book' table? In the end, I just want a giant table that I can grab cell data from. Right now I'm trying to figure out how to populate tables with my data, and what tables to fill for each piece of data.

(again, I'm new to database logic, so I apologize if my wording is hard to understand)

Body:
Your design does not look good. You are describing many-to-many relationships between books and genres, books and authors, books and options.

Storing references to the related genre, author, and option in the books table is not the right way to go: you can only store one related value per book (one genre, one author, one option), while you need many. Instead, for each of these relationships, you should have a separate table, called a bridge table, that references the associations.

On the other hand, information that is dependent on the book (say, the title) should be stored in the book table.

Here is one example for books and genres:

create table books(
    book_id int primary key,
    title varchar(100),  --dependent column
    pub_date date        --dependent column
);

create table genres(
    genre_id int primary key,
    name varchar(100)
);

create table book_genres(
    book_id int references book(book_id),
    genre_id int references genre(genre_id),
    primary key (book_id, genre_id)
);

Now, say you want to list all books that belong to genre 'Sci-Fi'; you would go:

select b.*
from books b
inner join book_genres bg on bg.book_id = b.book_id
inner join genres g on g.genre_id = bg.genre_id
where g.name = 'Sci-Fi'

The same logic should be implemented for each and every many-to-many relationship in your schema.


问:
Apache Nifi error: The specified template is not in a valid format
I saved a flow in JSON format, but when tried to load it as a template the following error appeared:
"The specified template is not in a valid format".

I noticed the other templates I uploaded were XML files and not JSON.
How can the template be saved as XML?

答:
Saving a flow is a different action than saving a template.
The template should be saved by "Create Template" action, which saves it in the templates list of the Nifi instance.
Then, it is accessible via the Templates menu item:

Under the templates list, there is an option to download a selected template as an XML file. With that, the template can be exported and uploaded into another Nifi instance correctly without any error.


问:
Why is there Log4j output to the console from other code, but not from my code?
I have a web app built with Eclipse/STS and Spring MVC.

I'm using slf4j and log4j for logging.

Here's my log4j.properties file ... I know it's being used because I added the text "MY TEST PROPS FILE" to the date pattern and it appears in the logs ...

```<code># Root logger option
log4j.rootLogger=DEBUG, INFO, WARN, ERROR, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=MY TEST PROPS FILE - %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code>```

When I run my web app, the console output looks like this ... you can see the "MY TEST PROPS FILE" in the output ...

```<code>MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:422 - decremented pending_acquires: 0
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG NewProxyConnection:1260 - com.mchange.v2.c3p0.impl.NewProxyConnection@71cf92cb: close() called more than once.
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)
</code>```

My problem is, the logging I attempt from my code doesn't appear in the console output.

I'm doing this ...

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* ... */

    private static Logger logger = LoggerFactory.getLogger(WebController.class);

/* ... */

    @RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
    public ModelAndView showHome(Model model) {

        logger.info("########### TEST LOG INFO");
        logger.error("########### TEST LOG ERROR");
        logger.warn("########### TEST LOG WARN");
        logger.debug("########### TEST LOG DEBUG");

/* ... */
    }
</code>```

I must be missing something simple.  Why are my test logger calls not appearing in the Console output?

UPDATE - SOLUTION FOUND: I found a solution and posted it as an answer below.

答:
I found a solution to my issue.

I changed to log4j2 by putting this in my pom.xml ...

```<code><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.7</version>
</dependency>
</code>```

And then I created a log4j2.properties file like this ...

```<code>status = error
name = PropertiesConfig

filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
</code>```

Works now.

Cheers, all.

Body:
I have a web app built with Eclipse/STS and Spring MVC.

I'm using slf4j and log4j for logging.

Here's my log4j.properties file ... I know it's being used because I added the text "MY TEST PROPS FILE" to the date pattern and it appears in the logs ...

# Root logger option
log4j.rootLogger=DEBUG, INFO, WARN, ERROR, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=MY TEST PROPS FILE - %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

When I run my web app, the console output looks like this ... you can see the "MY TEST PROPS FILE" in the output ...

MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:422 - decremented pending_acquires: 0
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG NewProxyConnection:1260 - com.mchange.v2.c3p0.impl.NewProxyConnection@71cf92cb: close() called more than once.
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)
MY TEST PROPS FILE - 2020-05-29 17:18:36 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@468f3122 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@642b4cb2)

My problem is, the logging I attempt from my code doesn't appear in the console output.

I'm doing this ...

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* ... */

    private static Logger logger = LoggerFactory.getLogger(WebController.class);

/* ... */

    @RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
    public ModelAndView showHome(Model model) {

        logger.info("########### TEST LOG INFO");
        logger.error("########### TEST LOG ERROR");
        logger.warn("########### TEST LOG WARN");
        logger.debug("########### TEST LOG DEBUG");

/* ... */
    }

I must be missing something simple.  Why are my test logger calls not appearing in the Console output?

UPDATE - SOLUTION FOUND: I found a solution and posted it as an answer below.

Body:
I found a solution to my issue.

I changed to log4j2 by putting this in my pom.xml ...

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.7</version>
</dependency>

And then I created a log4j2.properties file like this ...

status = error
name = PropertiesConfig

filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Works now.

Cheers, all.


问:
How to delete partiton data in dolphindb
In DolphinDB, I have a distributed database that partitions by date and stock code.  I want to delete the data from the past week. I found that the function dropPartition  can do this, but it can only delete the leaf partition, not the top partition directly, so how can I clean up the data distributed on the cluster machines last week?</p>

答:
When using COMPO partition by date and stock code, you can drop partition by date as follows</p>

```<code>db1= database(,VALUE,2007.08.01..2007.08.30)
db2=database(, VALUE,  symbol(`A`B`C`D`E))
db = database(dbPath, COMPO, [db1,db2])
dropPartition(db,[2007.08.01,2007.08.02],,true)
</code>```

Body:
When using COMPO partition by date and stock code, you can drop partition by date as follows

db1= database(,VALUE,2007.08.01..2007.08.30)
db2=database(, VALUE,  symbol(`A`B`C`D`E))
db = database(dbPath, COMPO, [db1,db2])
dropPartition(db,[2007.08.01,2007.08.02],,true)


问:
How to add a value to an integer field via a form in Django?
I'm currently trying to make a form that adds the value to the"point" model that I created but it seems to not go through. I made a form that should allow the user to put any integer value and it should add (or subtract) to the model. Can anyone point me to the right direction on what to do? Any help is appreciated.

Here is my forms.py:

```<code>class addpointForm(forms.ModelForm):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)
    class Meta:
        model = Points
        fields = ['user']
</code>```

Model.py:

```<code>class Points(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    points = models.IntegerField(default=0, null=False)

    def __str__(self):
        return self.user.username
</code>```

views.py:

```<code>@login_required
def pointform(request):
    if request.method=='POST':
        form = addpointForm(request.POST)
        if form.is_valid():

            instance = form.save(commit=False)
            messages.success(request, 'Success! Points has been added!')
            instance.user.points += addpointForm.add_point_field
            form.save()
        else:
            messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()
    return render (request,'users/addpoints.html',{'form':form})
</code>```

答:
Change your code to this:

```<code>instance.points += form.add_point_field
instance.save()
</code>```

You don't actually use the user's input; instead you accidentally use addpointForm.add_point_field.

While we're at it, let's change some other things to clarify what you're doing:

Don't use a ModelForm; change your form class to inherit from forms.Form. Do this because your form does not actually modify a model; it merely accepts input from a user, which you then accept and use to modify a model. In this case, it using a Form seems to me more idiomatic and intuitive:

```<code>class addpointForm(forms.Form):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)
</code>```

Then, let's clarify and simplify the view:

```<code>if request.method=='POST':
    form = addpointForm(request.POST)
    # Get the user from the request.
    user = request.user

    if form.is_valid():
        points_instance = user.points
        points_instance.points += form.add_point_field
        points_instance.save()

        messages.success(request, 'Success! Points has been added!')

    else:
        messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()

    return render (request,'users/addpoints.html',{'form':form})
</code>```

Body:
I'm currently trying to make a form that adds the value to the"point" model that I created but it seems to not go through. I made a form that should allow the user to put any integer value and it should add (or subtract) to the model. Can anyone point me to the right direction on what to do? Any help is appreciated.

Here is my forms.py:

class addpointForm(forms.ModelForm):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)
    class Meta:
        model = Points
        fields = ['user']

Model.py:

class Points(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    points = models.IntegerField(default=0, null=False)

    def __str__(self):
        return self.user.username

views.py:

@login_required
def pointform(request):
    if request.method=='POST':
        form = addpointForm(request.POST)
        if form.is_valid():

            instance = form.save(commit=False)
            messages.success(request, 'Success! Points has been added!')
            instance.user.points += addpointForm.add_point_field
            form.save()
        else:
            messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()
    return render (request,'users/addpoints.html',{'form':form})

Body:
Change your code to this:

instance.points += form.add_point_field
instance.save()

You don't actually use the user's input; instead you accidentally use addpointForm.add_point_field.

While we're at it, let's change some other things to clarify what you're doing:

Don't use a ModelForm; change your form class to inherit from forms.Form. Do this because your form does not actually modify a model; it merely accepts input from a user, which you then accept and use to modify a model. In this case, it using a Form seems to me more idiomatic and intuitive:

class addpointForm(forms.Form):
    add_point_field = forms.IntegerField(widget=forms.NumberInput)

Then, let's clarify and simplify the view:

if request.method=='POST':
    form = addpointForm(request.POST)
    # Get the user from the request.
    user = request.user

    if form.is_valid():
        points_instance = user.points
        points_instance.points += form.add_point_field
        points_instance.save()

        messages.success(request, 'Success! Points has been added!')

    else:
        messages.error(request, 'Oh no! There was an error when you were adding points!')

    form = addpointForm()

    return render (request,'users/addpoints.html',{'form':form})