问:
Logical operator treating fractions as FALSE
I am getting an unexpected result when using logical operators on numbers less than 1.
I thought VBA would treat any number other than zero as TRUE, but it seems to be treating fractions as FALSE. So strange.

What am I misunderstanding.

I have boiled it down to these two line of VBA code. The first returns what I expect, but not the second.

Thanks
kbrown4600

```<code>MsgBox 1 And True   ' returns 1
MsgBox 0.5 And True ' returns 0. Unexpected result
</code>```

答:
Bitwise operators don't do floating-point math, so there's an implicit conversion going on before the operands are given for the And operator to do its bitwise thing.

 "Logical" operators are a scam. There's no such thing, we've been lied to all this time - it's another Santa / Tooth Fairy / <s>Easter Bunny</s> (never mind, I'm being told the Easter Bunny is real): they're bitwise operators, always, regardless of what you give them.

And since the bitwise math yields 0, then it can only mean that the implicit conversion is simply slicing off the decimal portion.

Bottom line, ...don't do bitwise stuff with non-integers, and avoid implicit type conversions in general. The standard library has a bunch of explicit conversion functions for that:

```<code>Debug.Print VBA.Conversion.CLng(0.5) And True '<~ explicit conversion
</code>```

CLng is documented to round 0.5 down to 0,  If you need to determine whether to round down to 0 or up to 1, then be explicit about it:

```<code>Debug.Print CInt(0.5 + 0.01) And True '<~ explicit "round 0.5 up to 1"
</code>```

In any case, working with non-integer operands to a bitwise operator makes no sense.

When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Javascript has worse quirks than that around those parts, not sure how fair calling implicit type conversions "strange" is.

I thought VBA would treat any number other than zero as TRUE

That depends on the context. -1 is True, but True is Not False. That makes True -1 internally, probably as a 32-bit integer, so in binary it might look like this:

```<code>11111111 11111111 11111111 11111111
</code>```

Bit-wise, the Boolean value True must have this representation, because this needs to be the representation for False:

```<code>00000000 00000000 00000000 00000000
</code>```

Bitwise logic needs the two operands to be the same type, so that the bits mean the same thing on both sides, otherwise the bitwise operation - which is supposed to be simple and fast - needs to start doing complicated analysis to work out what it's looking at, when it simply doesn't need to.. if we accept that bitwise logic works with integer types, period.

You can do MsgBox 42 And 12, you'll get the bitwise result 8:

```<code>00000000 00000000 00000000 00101010 ' 42
00000000 00000000 00000000 00001100 ' 12
00000000 00000000 00000000 00001000 '  8 (AND)
</code>```

The result of the And operator is always going to be a bitwise-and result - what we call "logical operators" is just bitwise operators working with Boolean operands:

```<code>00000000 00000000 00000000 00000000 ' False
11111111 11111111 11111111 11111111 ' True
00000000 00000000 00000000 00000000 ' False (AND)
</code>```

But if the operand themselves aren't of an integer type, then they get converted to one before the operator gets to look at them. That's when True becomes -1, and that's when 0.5 becomes 0.

Body:
I am getting an unexpected result when using logical operators on numbers less than 1.
I thought VBA would treat any number other than zero as TRUE, but it seems to be treating fractions as FALSE. So strange.

What am I misunderstanding.

I have boiled it down to these two line of VBA code. The first returns what I expect, but not the second.

Thanks
kbrown4600

MsgBox 1 And True   ' returns 1
MsgBox 0.5 And True ' returns 0. Unexpected result

Body:
Bitwise operators don't do floating-point math, so there's an implicit conversion going on before the operands are given for the And operator to do its bitwise thing.

 "Logical" operators are a scam. There's no such thing, we've been lied to all this time - it's another Santa / Tooth Fairy / <s>Easter Bunny</s> (never mind, I'm being told the Easter Bunny is real): they're bitwise operators, always, regardless of what you give them.

And since the bitwise math yields 0, then it can only mean that the implicit conversion is simply slicing off the decimal portion.

Bottom line, ...don't do bitwise stuff with non-integers, and avoid implicit type conversions in general. The standard library has a bunch of explicit conversion functions for that:

Debug.Print VBA.Conversion.CLng(0.5) And True '<~ explicit conversion

CLng is documented to round 0.5 down to 0,  If you need to determine whether to round down to 0 or up to 1, then be explicit about it:

Debug.Print CInt(0.5 + 0.01) And True '<~ explicit "round 0.5 up to 1"

In any case, working with non-integer operands to a bitwise operator makes no sense.

When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Javascript has worse quirks than that around those parts, not sure how fair calling implicit type conversions "strange" is.

I thought VBA would treat any number other than zero as TRUE

That depends on the context. -1 is True, but True is Not False. That makes True -1 internally, probably as a 32-bit integer, so in binary it might look like this:

11111111 11111111 11111111 11111111

Bit-wise, the Boolean value True must have this representation, because this needs to be the representation for False:

00000000 00000000 00000000 00000000

Bitwise logic needs the two operands to be the same type, so that the bits mean the same thing on both sides, otherwise the bitwise operation - which is supposed to be simple and fast - needs to start doing complicated analysis to work out what it's looking at, when it simply doesn't need to.. if we accept that bitwise logic works with integer types, period.

You can do MsgBox 42 And 12, you'll get the bitwise result 8:

00000000 00000000 00000000 00101010 ' 42
00000000 00000000 00000000 00001100 ' 12
00000000 00000000 00000000 00001000 '  8 (AND)

The result of the And operator is always going to be a bitwise-and result - what we call "logical operators" is just bitwise operators working with Boolean operands:

00000000 00000000 00000000 00000000 ' False
11111111 11111111 11111111 11111111 ' True
00000000 00000000 00000000 00000000 ' False (AND)

But if the operand themselves aren't of an integer type, then they get converted to one before the operator gets to look at them. That's when True becomes -1, and that's when 0.5 becomes 0.


来源: stackexchange

问:
How to showvariable with gitversion Docker
I can successfully get the full json string with:

```<code>docker run --rm -v `pwd`:`pwd` gittools/gitversion-dotnetcore:linux-4.0.0 `pwd` -output json
</code>```

which outputs to something like:

```<code>{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "SemVer":"0.1.0-dev-2.1",
.
.
.
  "CommitsSinceVersionSource":20,
  "CommitsSinceVersionSourcePadded":"0020",
  "CommitDate":"2020-05-28"
}
</code>```

Since I am only interested in SemVer variable I try to use the -showvariable FullSemVer with:

```<code>docker run --rm -v `pwd`:`pwd` gittools/gitversion-dotnetcore:linux-4.0.0 `pwd` -output json -showvariable FullSemVer
</code>```

But it fails with a quite long and nasty error log.

```<code>INFO [05/28/20 18:23:12:10] End: Loading version variables from disk cache (Took: 76.31ms)
ERROR [05/28/20 18:23:12:13] An unexpected error occurred:
System.NotImplementedException: The method or operation is not implemented.
</code>```

I wonder if there is a way to use the -showvariable flag with the gitversion Docker container?

答:
I think the problem is the path argument passed to GitVersion. pwd will give you the working directory on your host, not within the container. GitVersion is unfortunately not aware of the fact that it's executing within a container, so it needs to be provided with the volume directory /repo as the path to calculate a version number for. This is something we should consider changing in version 6.

I also can't remember when -showvariable was implemented, so to be on the safe side you should try with a newer version of our Docker containers. I can also recommend using the alpine container, as it's the smallest one we offer (only 83.9 MB). This works:

docker run \
    --rm \
    --volume "$(pwd):/repo" \
    gittools/gitversion:5.3.4-linux-alpine.3.10-x64-netcoreapp3.1 \
    /repo \
    -output json \
    -showvariable FullSemVer
```

ContentLicense: CC BY-SA 4.0

Body:
I can successfully get the full json string with:

docker run --rm -v `pwd`:`pwd` gittools/gitversion-dotnetcore:linux-4.0.0 `pwd` -output json

which outputs to something like:

{
  "Major":0,
  "Minor":1,
  "Patch":0,
  "SemVer":"0.1.0-dev-2.1",
.
.
.
  "CommitsSinceVersionSource":20,
  "CommitsSinceVersionSourcePadded":"0020",
  "CommitDate":"2020-05-28"
}

Since I am only interested in SemVer variable I try to use the -showvariable FullSemVer with:

docker run --rm -v `pwd`:`pwd` gittools/gitversion-dotnetcore:linux-4.0.0 `pwd` -output json -showvariable FullSemVer

But it fails with a quite long and nasty error log.

INFO [05/28/20 18:23:12:10] End: Loading version variables from disk cache (Took: 76.31ms)
ERROR [05/28/20 18:23:12:13] An unexpected error occurred:
System.NotImplementedException: The method or operation is not implemented.

I wonder if there is a way to use the -showvariable flag with the gitversion Docker container?


问:
unable to use constructor in java
I have started learing java generics and this is my priority queue implementation:

```<code>public class MinPQ<Key> implements Iterable<Key> {
   private Key[] pq;                    // store items at indices 1 to n
   private int n;                       // number of items on priority queue
   private Comparator<Key> comparator;  // optional comparator

   public MinPQ(Key[] keys) {
        n = keys.length;
        pq = (Key[]) new Object[keys.length + 1];
        .....
        .....
    }
}
</code>```

And this is my main class :

```<code>public class Demo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            int[] ar = {1,2,3};
            MinPQ<Integer> pq = new MinPQ<Integer>(ar);
        }
}
</code>```

But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?

答:
You can't use primitive types with generics. Just change:

```<code>int[] ar = {1,2,3};
</code>```

to:

```<code>Integer[] ar = {1,2,3};
</code>```

or box it with

```<code>IntStream.of(ar).boxed().toArray(Integer[]::new)
</code>```

Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ<Integer> declaration. So, in tehory it should work if you declared it as MinPQ<int> - but as stated at the beginning we can't use primitive types for generics.

Title: unable to use constructor in java

Body:
I have started learing java generics and this is my priority queue implementation:

public class MinPQ<Key> implements Iterable<Key> {
   private Key[] pq;                    // store items at indices 1 to n
   private int n;                       // number of items on priority queue
   private Comparator<Key> comparator;  // optional comparator

   public MinPQ(Key[] keys) {
        n = keys.length;
        pq = (Key[]) new Object[keys.length + 1];
        .....
        .....
    }
}

And this is my main class :

public class Demo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            int[] ar = {1,2,3};
            MinPQ<Integer> pq = new MinPQ<Integer>(ar);
        }
}

But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?

Body:
You can't use primitive types with generics. Just change:

int[] ar = {1,2,3};

to:

Integer[] ar = {1,2,3};

or box it with

IntStream.of(ar).boxed().toArray(Integer[]::new)

Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ<Integer> declaration. So, in tehory it should work if you declared it as MinPQ<int> - but as stated at the beginning we can't use primitive types for generics.


问:
Assigning json array to interface when string[] does not work
I have the following json file which holds a list of blacklist terms.

```<code>{
  "blacklist": [
    "term1",
    "term2",
    "term3",
    "term4",
    "term5"
   ]
}
</code>```

It is used in blacklist service:

```<code>@Injectable()
export class BlacklistService {
  private readonly BLACKLIST_TERMS_FOLDER = './assets/data/web-blacklist-terms';
  private readonly blacklistTerms1: any;
  private readonly blacklistTerms2: any;
}

constructor(
  public httpClient: HttpClient
) {
  this.blacklistTerms1 = this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);
}

public getAllBlackListTerms(): Observable<any> {
  return combineLatest([this.blacklistTerms1, this.blacklistTerms2])
}
</code>```

How would I add a type to blacklistTerms? I have tried string[] but it gives me the message Type 'Observable ' is missing the following properties from type 'string[]': length, pop, push, concat, and 27 more.

答:
How about you add a interface like this at top of your class

```<code>interface BlackList{
   blacklist: string[]
}
</code>```

And use it in your code as

```<code>this.blacklistTerms1: Observable<BlackList>  = this.httpClient.get<BlackList>(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);
</code>```

If you want to reuse the interface in other components it would be ideal to move it in another file where you place other interfaces as well and import it from there.

Body:
I have the following json file which holds a list of blacklist terms.

{
  "blacklist": [
    "term1",
    "term2",
    "term3",
    "term4",
    "term5"
   ]
}

It is used in blacklist service:

@Injectable()
export class BlacklistService {
  private readonly BLACKLIST_TERMS_FOLDER = './assets/data/web-blacklist-terms';
  private readonly blacklistTerms1: any;
  private readonly blacklistTerms2: any;
}

constructor(
  public httpClient: HttpClient
) {
  this.blacklistTerms1 = this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);
}

public getAllBlackListTerms(): Observable<any> {
  return combineLatest([this.blacklistTerms1, this.blacklistTerms2])
}

How would I add a type to blacklistTerms? I have tried string[] but it gives me the message Type 'Observable ' is missing the following properties from type 'string[]': length, pop, push, concat, and 27 more.

Body:
How about you add a interface like this at top of your class

interface BlackList{
   blacklist: string[]
}

And use it in your code as

this.blacklistTerms1: Observable<BlackList>  = this.httpClient.get<BlackList>(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);

If you want to reuse the interface in other components it would be ideal to move it in another file where you place other interfaces as well and import it from there.


问:
SKStoreReviewController.requestReview() rates don't come to Appstore
```<code>    if UsesCount < 10
    {
    UsesCount += 1
    }
    else
    {
        if UsesCount == 10
        {
            SKStoreReviewController.requestReview()
            UsesCount += 1
        }
    }
    UserDefaults.standard.set(UsesCount, forKey: "UsesCount")
    UserDefaults.standard.synchronize()
</code>```

All work right jpg attacked

but in AppStore and AppStore Connect i don't see this rates in all versions.
What it can be?

答: Solved. In Appstore showed locale rates and comments. Rate which I want to found is from Russia, i can see it only in AppStore Connect by filter All rates or Russia.</p>

Body:
    if UsesCount < 10
    {
    UsesCount += 1
    }
    else
    {
        if UsesCount == 10
        {
            SKStoreReviewController.requestReview()
            UsesCount += 1
        }
    }
    UserDefaults.standard.set(UsesCount, forKey: "UsesCount")
    UserDefaults.standard.synchronize()

All work right jpg attacked

but in AppStore and AppStore Connect i don't see this rates in all versions.
What it can be?


问:
As a system user I have this error: ORA-01031: insufficient privileges
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

```<code>BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;
</code>```

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.

答:
Works for me on 11g XE:

```<code>SQL> show user
USER is "SCOTT"
SQL>
SQL> create table test
  2    (id     number   constraint pk_test primary key,
  3     name   varchar2(20)
  4    );

Table created.

SQL> connect system
Enter password:
Connected.
SQL> begin
  2    execute immediate 'alter table scott.test disable constraint pk_test';
  3    return;
  4  end;
  5  /

PL/SQL procedure successfully completed.

SQL>
</code>```

Please, follow that example and execute it in your database. Post the result (by editing the question, not as a comment).

Body:
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.

Body:
Works for me on 11g XE:

SQL> show user
USER is "SCOTT"
SQL>
SQL> create table test
  2    (id     number   constraint pk_test primary key,
  3     name   varchar2(20)
  4    );

Table created.

SQL> connect system
Enter password:
Connected.
SQL> begin
  2    execute immediate 'alter table scott.test disable constraint pk_test';
  3    return;
  4  end;
  5  /

PL/SQL procedure successfully completed.

SQL>

Please, follow that example and execute it in your database. Post the result (by editing the question, not as a comment).


问:
SQL server/Azure SQL: NVARCHAR(MAX) vs NVARCHAR(#) vs buffer cache
We are in the process of migrating our SAAS system from Oracle to Azure SQL. We anticipate that we will have less available buffer cache in Azure SQL than we have in our Oracle server (even with sliders maxed out in Azure). Our application is quite dependent on the buffer cache for performance. Selects causing table scans being run frequently will cause a lot of data to be stored in the buffer cache, and the complete page will be read. We are not able to remove these table scans completely. So, to try to reduce the need for buffer cache in Azure SQL, we are considering to store nvarchar(max) values out-of-row with the command

```<code>EXEC sp_tableoption 'MYTABLE.NVARCHARMAX_COL', 'large value types out of row', 1;
</code>```

The idea is that this will cause less data to scan as the column values are not stored in the page and hence less data to store in the buffer cache.

Is this a correct assumption?

nvarchar(#) will cause a memory grant of #/2 for queries, as far as we understand.

What is the memory grant for nvarchar(max)?

Will memory grants compete with buffer cache memory, or will buffer cache memory have priority over memory grants?

Is there anything to gain using nvarchar(max) with out-of-row storage instead of nvarchar(#) when it comes to buffer cache usage? Or to the contrary?

We are aware of other drawbacks with nvarchar(max) like slower reads and writes (50%-100%?) and that it cannot be indexed.

Some more details:

Our application is an Applicant Tracking System. It may be so that we will be ok with the default settings for nvarchar(max), but we want to be as sure as possible that Azure SQL will handle the full operational load before the launch. We are thinking that the increased IO with out-of-row storage is small compared to the anticipated benefit of savings in query time. We are currently running stress tests to try to figure this out. A good example is the job application table, where each row in the table consists of very little data other than the cover letter, and the table is included in a lot of queries where the cover letter column is neither a part of the where condition nor in the select column list. In Oracle, this table is currently 90% cached using 47GB of the buffer cache.
We would like to inspect the buffer cache in Azure SQL in more detail, that is to see which tables are buffered and to what extent, does Azure SQL allow this?

答:
We have done some performance testing comparing nvarchar(max) in-row with out-of-row using column values between 3000 and 3800 characters. The query times in table scans are down by 60% in favour of out-of-row. The buffercache usage is also significantly less. Read penalty about 10% compared to in-row.

To specify Out-of-row:
EXEC sp_tableoption 'MY_TABLE', 'large value types out of row', 1;

Queries to inspect the buffercache in detail:
https://www.sqlshack.com/insight-into-the-sql-server-buffer-cache/

Body:
We are in the process of migrating our SAAS system from Oracle to Azure SQL. We anticipate that we will have less available buffer cache in Azure SQL than we have in our Oracle server (even with sliders maxed out in Azure). Our application is quite dependent on the buffer cache for performance. Selects causing table scans being run frequently will cause a lot of data to be stored in the buffer cache, and the complete page will be read. We are not able to remove these table scans completely. So, to try to reduce the need for buffer cache in Azure SQL, we are considering to store nvarchar(max) values out-of-row with the command

EXEC sp_tableoption 'MYTABLE.NVARCHARMAX_COL', 'large value types out of row', 1;

The idea is that this will cause less data to scan as the column values are not stored in the page and hence less data to store in the buffer cache.

Is this a correct assumption?

nvarchar(#) will cause a memory grant of #/2 for queries, as far as we understand.

What is the memory grant for nvarchar(max)?

Will memory grants compete with buffer cache memory, or will buffer cache memory have priority over memory grants?

Is there anything to gain using nvarchar(max) with out-of-row storage instead of nvarchar(#) when it comes to buffer cache usage? Or to the contrary?

We are aware of other drawbacks with nvarchar(max) like slower reads and writes (50%-100%?) and that it cannot be indexed.

Some more details:

Our application is an Applicant Tracking System. It may be so that we will be ok with the default settings for nvarchar(max), but we want to be as sure as possible that Azure SQL will handle the full operational load before the launch. We are thinking that the increased IO with out-of-row storage is small compared to the anticipated benefit of savings in query time. We are currently running stress tests to try to figure this out. A good example is the job application table, where each row in the table consists of very little data other than the cover letter, and the table is included in a lot of queries where the cover letter column is neither a part of the where condition nor in the select column list. In Oracle, this table is currently 90% cached using 47GB of the buffer cache.
We would like to inspect the buffer cache in Azure SQL in more detail, that is to see which tables are buffered and to what extent, does Azure SQL allow this?


问:
Application Root Path of Spring Boot application
This answer is not a standard way to get application root path (file system path). I need to upload a file to a directory e.g. uploads created in application main directory. How can I get the application root path in my Java Class. I am developing Rest API. Please help in this regard.</p>

答:
You can simply use FileSystemResource to get the root directory:

```<code>new FileSystemResource("").getFile().getAbsolutePath()
</code>```

Non spring way:

Alternatively, you can also get it using System.getProperty("user.dir"). This works with properties, yml or pom.xml files as well.

```<code># properties file
info.root-dir=${user.dir}
</code>```

```<code><!-- pom.xml -->
<properties> <!-- not really sure if anyone would ever do it -->
    <another.project.dir>${user.dir}/../someproject</another.project.dir>
</properties>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can simply use FileSystemResource to get the root directory:

new FileSystemResource("").getFile().getAbsolutePath()

Non spring way:

Alternatively, you can also get it using System.getProperty("user.dir"). This works with properties, yml or pom.xml files as well.

# properties file
info.root-dir=${user.dir}

<!-- pom.xml -->
<properties> <!-- not really sure if anyone would ever do it -->
    <another.project.dir>${user.dir}/../someproject</another.project.dir>
</properties>


问:
How to perform a basic Spring Boot application security
I'm looking forward to deploying my Spring Application on a production environment and i'd like to include some basic and solid security measures.

First things first, i extended WebSecurityConfigurerAdapter into my SecurityConfiguration.java

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService ;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable().authorizeRequests()
        .antMatchers("/admin").hasAuthority("ADMIN")
        .antMatchers("/ekab").hasAuthority("EKAB")
        .antMatchers("/dimos").hasAuthority("DIMOS")
        .antMatchers("/","/users/**","/aeds/**","/events/**","/reports/**","*/static/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin().loginPage("/login")
    .defaultSuccessUrl("/dashboard",true)
        .permitAll()
        .and()
    .logout()
        .permitAll();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}

```

On a production environment CSRF should be enabled, although i don't handle any csrf tokens for now

GET Endpoints: Note that /users/** contains some GET endpoints containing User Information, can i apply limitations to who visits them?

POST Endpoints: I've also found some ways to secure POST by using
a JSON Web Token , is it a best practice?

Spring also provides OAuth2.0 , RSA, LDAP, dependencies to enhance security.

Which one should i use? Does these prevent DDOS attacks as well as brute force attacks?

Do i have to make modifications in the application's deployment environment?

答:
Spring Security provides various default security attack implementation to make sure the application is secured.

Since you asked to include some basic and solid security measures. Below are a few of my thoughts which can improve a bit.

As you told, You have disabled 'CSRF token' which is not good when you think your application should be highly secured. Usually, most of the people disable(in demo code) because they won't be able to call /logout URL with the GET method as it requires you to submit it via POST with _csrf token. Good that you have taken care of in production.

Session Fixation Attack: This is the type of attack where one can steal your current session by offering their URL of the same website and append JSESSIONID into URL, with the URL rewrite approach.  Spring Security Framework has taken care of this by default and it migrates the session once the user logs in. The corresponding configuration would be -

```<code>http.sessionManagement()
  .sessionFixation().migrateSession()
</code>```

Securing session cookie: Malicious script can read your cookie information from the browser end so you need to make sure that your cookie is secured and are accessible by server-side code by making them HttpOnly. For that, you can use the below config in your application.properties -

```<code>server.servlet.session.cookie.http-only=true
</code>```

Running your app on Https: Make sure that you use https in production and also in that case you can force your cookies to travel over https protocol only by adding below config in your application.properties.

```<code> server.servlet.session.cookie.secure=true
</code>```

and to force https connection add below lines in configure() method (this won't be enough though because you have to get your public/private key setup also using keytool)

```<code>   http.requiresChannel().requiresSecure();
</code>```

Applying CSP: User Content security policy to avoid any XSS attacks. Spring security by default provides various security headers. But it does not add Content security policy headers you can add them in your security config file like below

```<code> @EnableWebSecurity
 public class WebSecurityConfig extends
 WebSecurityConfigurerAdapter {
 @Override
 protected void configure(HttpSecurity http)
 throws Exception {
 http.headers().contentSecurityPolicy("script-src
'self' https://myclientscriptlocation.example.com; object-src
 https://myclientsideplugins.example.com; report-uri /cspreport-endpoint/");
}
</code>```

}

Password hashing: Which you are not using your security config. You have to keep password hashed while storing them into the database.

Securing your application.properties' Security should be applied not only from outsiders, but it should also be protected from insiders as well. Like encryption and decryption of database passwords or any other config passwords. Follow here on how to secure your application properties.

GET Endpoints: Note that /users/** contains some GET endpoints
containing User Information, can I apply limitations to who visits
them?

Yes, you can apply. But that depends on your requirement what you want here. One example that I can think of is, IP Address filtering. Like if you want only those users can access which are in the US or if you know the IP range of user etc.

```<code>  .antMatchers("/foos/**").hasIpAddress("xx.xxx.xxx.xx")
</code>```

POST Endpoints: I've also found some ways to secure POST by using a
JSON Web Token , is it a best practice?

JWT mostly used in RESTful web services. If your application is exposing rest endpoints and requires authenticated access then JWT is the best option.

Spring also provides OAuth2.0, RSA, LDAP, dependencies to enhance
security.

These are different ways of authentication and authorization. Some of them has multiple flows to do authentication and authorization but The same security factors would be applied to these when they are accessed by outside the users.

It totally depends on your project requirement whether you need them or not. For example, if you are developing an application for internal organization use where user/employee has everything set up at the organization level and you want everyone to access this application then LDAP integration is better.

OAuth2.0 is better when you have multiple microservices + you want any social login implementation like Login with Google or Login with Facebook then you can follow OAuth2.0 integration

Does these prevent DDOS attacks as well as brute force attacks?

No. This should be taken care of by tuning various security parameters like limiting the session time, checking security headers, handling memory leaks, applying timeout for POST requests so that no one could post a huge request payload, etc. You have to do a bit of leg work to mitigate such security attacks.

PS: Remove permitAll() from security configuration.

```<code>.defaultSuccessUrl("/dashboard",true)
    .permitAll()
</code>```

Body:
I'm looking forward to deploying my Spring Application on a production environment and i'd like to include some basic and solid security measures.

First things first, i extended WebSecurityConfigurerAdapter into my SecurityConfiguration.java

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService ;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable().authorizeRequests()
        .antMatchers("/admin").hasAuthority("ADMIN")
        .antMatchers("/ekab").hasAuthority("EKAB")
        .antMatchers("/dimos").hasAuthority("DIMOS")
        .antMatchers("/","/users/**","/aeds/**","/events/**","/reports/**","*/static/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin().loginPage("/login")
    .defaultSuccessUrl("/dashboard",true)
        .permitAll()
        .and()
    .logout()
        .permitAll();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}

On a production environment CSRF should be enabled, although i don't handle any csrf tokens for now

GET Endpoints: Note that /users/** contains some GET endpoints containing User Information, can i apply limitations to who visits them?

POST Endpoints: I've also found some ways to secure POST by using
a JSON Web Token , is it a best practice?

Spring also provides OAuth2.0 , RSA, LDAP, dependencies to enhance security.

Which one should i use? Does these prevent DDOS attacks as well as brute force attacks?

Do i have to make modifications in the application's deployment environment?

Body:
Spring Security provides various default security attack implementation to make sure the application is secured.

Since you asked to include some basic and solid security measures. Below are a few of my thoughts which can improve a bit.

As you told, You have disabled 'CSRF token' which is not good when you think your application should be highly secured. Usually, most of the people disable(in demo code) because they won't be able to call /logout URL with the GET method as it requires you to submit it via POST with _csrf token. Good that you have taken care of in production.

Session Fixation Attack: This is the type of attack where one can steal your current session by offering their URL of the same website and append JSESSIONID into URL, with the URL rewrite approach.  Spring Security Framework has taken care of this by default and it migrates the session once the user logs in. The corresponding configuration would be -

http.sessionManagement()
  .sessionFixation().migrateSession()

Securing session cookie: Malicious script can read your cookie information from the browser end so you need to make sure that your cookie is secured and are accessible by server-side code by making them HttpOnly. For that, you can use the below config in your application.properties -

server.servlet.session.cookie.http-only=true

Running your app on Https: Make sure that you use https in production and also in that case you can force your cookies to travel over https protocol only by adding below config in your application.properties.

 server.servlet.session.cookie.secure=true

and to force https connection add below lines in configure() method (this won't be enough though because you have to get your public/private key setup also using keytool)

   http.requiresChannel().requiresSecure();

Applying CSP: User Content security policy to avoid any XSS attacks. Spring security by default provides various security headers. But it does not add Content security policy headers you can add them in your security config file like below

 @EnableWebSecurity
 public class WebSecurityConfig extends
 WebSecurityConfigurerAdapter {
 @Override
 protected void configure(HttpSecurity http)
 throws Exception {
 http.headers().contentSecurityPolicy("script-src
'self' https://myclientscriptlocation.example.com; object-src
 https://myclientsideplugins.example.com; report-uri /cspreport-endpoint/");
}

}

Password hashing: Which you are not using your security config. You have to keep password hashed while storing them into the database.

Securing your application.properties' Security should be applied not only from outsiders, but it should also be protected from insiders as well. Like encryption and decryption of database passwords or any other config passwords. Follow here on how to secure your application properties.

GET Endpoints: Note that /users/** contains some GET endpoints
containing User Information, can I apply limitations to who visits
them?

Yes, you can apply. But that depends on your requirement what you want here. One example that I can think of is, IP Address filtering. Like if you want only those users can access which are in the US or if you know the IP range of user etc.

  .antMatchers("/foos/**").hasIpAddress("xx.xxx.xxx.xx")

POST Endpoints: I've also found some ways to secure POST by using a
JSON Web Token , is it a best practice?

JWT mostly used in RESTful web services. If your application is exposing rest endpoints and requires authenticated access then JWT is the best option.

Spring also provides OAuth2.0, RSA, LDAP, dependencies to enhance
security.

These are different ways of authentication and authorization. Some of them has multiple flows to do authentication and authorization but The same security factors would be applied to these when they are accessed by outside the users.

It totally depends on your project requirement whether you need them or not. For example, if you are developing an application for internal organization use where user/employee has everything set up at the organization level and you want everyone to access this application then LDAP integration is better.

OAuth2.0 is better when you have multiple microservices + you want any social login implementation like Login with Google or Login with Facebook then you can follow OAuth2.0 integration

Does these prevent DDOS attacks as well as brute force attacks?

No. This should be taken care of by tuning various security parameters like limiting the session time, checking security headers, handling memory leaks, applying timeout for POST requests so that no one could post a huge request payload, etc. You have to do a bit of leg work to mitigate such security attacks.

PS: Remove permitAll() from security configuration.

.defaultSuccessUrl("/dashboard",true)
    .permitAll()


问:
How to insert into a row, a value from other table?
I have 3 Mysql tables.

A table with the classes and the labs and their id.

A table with the teachers_list and their subject.
A table which is going to be the schedule.**

I want to randomly assign one of the physicists to one of the physics labs on my third table which is going to be the schedule.

```<code>INSERT INTO schedule(teacher_name, class_id)
VALUES (select teacher_name from teachers_list where subject="Physicist” order by rand() limit 1,

select id from lab_list where lab="Physics_lab" order by rand() limit 1);
</code>```

**This one doesn't work :(

Can you help me?**

答:
I think that you want the insert ... select syntax, along with a subquery:

```<code>insert into schedule(teacher_name, class_id)
select
    (
        select teacher_name
        from teachers_list
        where subject = 'Physicist'
        order by rand()
        limit 1
    ),
    id
from lab_list
where lab = 'Physics_lab'
</code>```

Body:
I have 3 Mysql tables.

A table with the classes and the labs and their id.

A table with the teachers_list and their subject.
A table which is going to be the schedule.**

I want to randomly assign one of the physicists to one of the physics labs on my third table which is going to be the schedule.

INSERT INTO schedule(teacher_name, class_id)
VALUES (select teacher_name from teachers_list where subject="Physicist” order by rand() limit 1,

select id from lab_list where lab="Physics_lab" order by rand() limit 1);

**This one doesn't work :(

Can you help me?**

Body:
I think that you want the insert ... select syntax, along with a subquery:

insert into schedule(teacher_name, class_id)
select
    (
        select teacher_name
        from teachers_list
        where subject = 'Physicist'
        order by rand()
        limit 1
    ),
    id
from lab_list
where lab = 'Physics_lab'


问:
media query working on chrome but not on mobile
this is a piece of my CSS:

@media (max-width: 800px) {

    body {
        background:black;
        background-image:none;
        font-size:30px;
    }

    #logo {
        width: 100%;
        height: 100%;

    }
    .mobile {
        display: inline;
        align-content: center;
        font-size:60px;
    }
    .longtext {
        display: none;
    }
}
```

On chrome, when I resize the window it changes to the setting i wanted to, but when going to devtools responsive check or visiting on mobile, it just doesn't work. Not a single setting.

heeeelp

答:
You should add this meta tag in . More information from MDN

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0" />
</code>```

Body:
this is a piece of my CSS:

@media (max-width: 800px) {

    body {
        background:black;
        background-image:none;
        font-size:30px;
    }

    #logo {
        width: 100%;
        height: 100%;

    }
    .mobile {
        display: inline;
        align-content: center;
        font-size:60px;
    }
    .longtext {
        display: none;
    }
}

On chrome, when I resize the window it changes to the setting i wanted to, but when going to devtools responsive check or visiting on mobile, it just doesn't work. Not a single setting.

heeeelp

Body:
You should add this meta tag in <head></head>. More information from MDN

<meta name="viewport" content="width=device-width, initial-scale=1.0" />


问:
SetInterval is not working in Kindle and Kobo Browsers
I want do stream images to my e-ink reader's browser. I have a Kobo Aura H2O and a Kindle Paperwhite.

I have tried multiple mechanics but nothing seems to work, because the browser ignores half of the javascript.

Websockets do not work, setInterval to update the image regularly does not work neither

Are there any Specs of this Browsers to be found? What other alternatives within Javascript are there to test?

答:
The Kindle browser does technically support WebSockets (even on the very first Kindle Touch), however because it's based on a very old version of Webkit, it's the very first version (or one of the first versions, I'm not exactly sure) of the WebSocket spec which is very different from the current one and isn't supported in the majority of Websocket libraries.

I made a very bad patch for the Node ws library here: https://github.com/HimbeersaftLP/ws

Google's pywebsocket also supports it: https://github.com/google/pywebsocket/wiki/WebSocketProtocolSpec


问:
Add an XML node to the existing XML node
I am working on a script where the objective is to read data from excel and parse it into XML. There is a need for mapping a few of the details under one node if it exists. Considering the below data, I am looking to map the spouse under the subscriber if member id of both of them matches.

expected output:

```<code><Member>
  <MemberDetail>
    <FIRSTNAME>Kevin</FIRSTNAME>
    <LASTNAME>Adams</LASTNAME>
    <ID>1</ID>
    <Dependent>
      <FIRSTNAME>Kelly</FIRSTNAME>
      <LASTNAME>Adams</LASTNAME>
      <ID>1</ID>
    </Dependent>
  </MemberDetail>
</Member>
</code>```

current output:

```<code><Member>
  <MemberDetail>
    <FIRSTNAME>Kevin</FIRSTNAME>
    <LASTNAME>Adams</LASTNAME>
    <ID>1</ID>
  </MemberDetail>
  <MemberDetail>
    <Dependent>
      <FIRSTNAME>Kelly</FIRSTNAME>
      <LASTNAME>Adams</LASTNAME>
      <ID>1</ID>
    </Dependent>
  <MemberDetail>
</Member>
</code>```

code:

```<code>const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;

xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
const typeColumn = rows[0].indexOf('MEMBER TYPE');
rows.forEach((row, rowIndex) => {
        if (rowIndex !== 0) {
            const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
            if (row[typeColumn] == 'SUBSCRIBER') {
                row.forEach((cellValue, cellIndex) => {
                    detail.ele(rows[0][cellIndex].split(" ").join(""))
                        .txt(cellValue ? cellValue.toString() : 'empty')
                        .up()
                })
            }
            else {
                const dependentDetail = detail.ele('Dependent').att('for', 'dependent')
                row.forEach((cellValue, cellIndex) => {
                    dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
                        .txt(cellValue ? cellValue.toString() : 'empty')
                        .up()
                })
            }
        }
    })
    fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
        if (error) {
            console.log('Error', error)
        }
        else {
            console.log('Your file has been saved')
        }
    })
})
    .catch(err => console.log(err))

  [1]: https://i.stack.imgur.com/giOUj.png
</code>```

答:
My only suggestion would be to isolate the element that you are mapping 'MemberDetail' as a constant and add dependentDetail to that.

try this

```<code>const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;

xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
  const typeColumn = rows[0].indexOf('MEMBER TYPE');
  rows.forEach((row, rowIndex) => {
    if (rowIndex !== 0) {
      const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
      row.forEach((cellValue, cellIndex) => {
        if (row[typeColumn] == 'SUBSCRIBER') {
          const subscriber = detail.ele(rows[0][cellIndex].split(" ").join(""))
            .txt(cellValue ? cellValue.toString() : 'empty')
            .up()
          row.forEach((cellValue, cellIndex) => {
            if (row[typeColumn] !== 'SUBSCRIBER') {
              const dependentDetail = subscriber.ele('Dependent').att('for', 'dependent')
              dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
                .txt(cellValue ? cellValue.toString() : 'empty')
                .up()
            }
          })
        }})
  fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
    if (error) {
      console.log('Error', error)
    }
    else {
      console.log('Your file has been saved')
    }
  })
}})
  .catch(err => console.log(err))})
</code>```

Body:
I am working on a script where the objective is to read data from excel and parse it into XML. There is a need for mapping a few of the details under one node if it exists. Considering the below data, I am looking to map the spouse under the subscriber if member id of both of them matches.

expected output:

<Member>
  <MemberDetail>
    <FIRSTNAME>Kevin</FIRSTNAME>
    <LASTNAME>Adams</LASTNAME>
    <ID>1</ID>
    <Dependent>
      <FIRSTNAME>Kelly</FIRSTNAME>
      <LASTNAME>Adams</LASTNAME>
      <ID>1</ID>
    </Dependent>
  </MemberDetail>
</Member>

current output:

<Member>
  <MemberDetail>
    <FIRSTNAME>Kevin</FIRSTNAME>
    <LASTNAME>Adams</LASTNAME>
    <ID>1</ID>
  </MemberDetail>
  <MemberDetail>
    <Dependent>
      <FIRSTNAME>Kelly</FIRSTNAME>
      <LASTNAME>Adams</LASTNAME>
      <ID>1</ID>
    </Dependent>
  <MemberDetail>
</Member>

code:

const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;

xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
const typeColumn = rows[0].indexOf('MEMBER TYPE');
rows.forEach((row, rowIndex) => {
        if (rowIndex !== 0) {
            const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
            if (row[typeColumn] == 'SUBSCRIBER') {
                row.forEach((cellValue, cellIndex) => {
                    detail.ele(rows[0][cellIndex].split(" ").join(""))
                        .txt(cellValue ? cellValue.toString() : 'empty')
                        .up()
                })
            }
            else {
                const dependentDetail = detail.ele('Dependent').att('for', 'dependent')
                row.forEach((cellValue, cellIndex) => {
                    dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
                        .txt(cellValue ? cellValue.toString() : 'empty')
                        .up()
                })
            }
        }
    })
    fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
        if (error) {
            console.log('Error', error)
        }
        else {
            console.log('Your file has been saved')
        }
    })
})
    .catch(err => console.log(err))

  [1]: https://i.stack.imgur.com/giOUj.png

Body:
My only suggestion would be to isolate the element that you are mapping 'MemberDetail' as a constant and add dependentDetail to that.

try this

const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;

xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
  const typeColumn = rows[0].indexOf('MEMBER TYPE');
  rows.forEach((row, rowIndex) => {
    if (rowIndex !== 0) {
      const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
      row.forEach((cellValue, cellIndex) => {
        if (row[typeColumn] == 'SUBSCRIBER') {
          const subscriber = detail.ele(rows[0][cellIndex].split(" ").join(""))
            .txt(cellValue ? cellValue.toString() : 'empty')
            .up()
          row.forEach((cellValue, cellIndex) => {
            if (row[typeColumn] !== 'SUBSCRIBER') {
              const dependentDetail = subscriber.ele('Dependent').att('for', 'dependent')
              dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
                .txt(cellValue ? cellValue.toString() : 'empty')
                .up()
            }
          })
        }})
  fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
    if (error) {
      console.log('Error', error)
    }
    else {
      console.log('Your file has been saved')
    }
  })
}})
  .catch(err => console.log(err))})


问:
When connecting java to Google Big Query I get Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/json/JsonFactory
I have a Java program that I want to use to run queries against google big query.

I am getting this error when starting my program:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/json/JsonFactory
    at com.simba.googlebigquery.googlebigquery.core.BQConnection.connect(Unknown Source)
    at com.simba.googlebigquery.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
    at com.simba.googlebigquery.jdbc.common.AbstractDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:270)
    at missioncontrol.main(missioncontrol.java:60)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.json.JsonFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 6 more
</code>```

I have downloaded the Simba gbq jdbc driver.  I have set up my authorizations.  My connection string looks like this:

```<code>jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=redacted;OAuthType=0;OAuthServiceAcctEmail=;redaacted@redacted.iam.gserviceaccount.com;OAuthPvtKeyPath=/home/redacted/redacted/redacted.p12;
</code>```

My CLASSPATH Originally looked like this:
/opt/google/GoogleBigQueryJDBC42.jar

But I've added a bunch of jar files in an effort to solve this problem, so now it looks like this:

```<code>/google-http-client-1.29.0.jar:/opt/google/google-http-client-jackson2-1.28.0.jar:/opt/google/jackson-annotations-2.9.0.jar:/opt/google/jackson-core-2.9.8.jar:/opt/google/jackson-databind-2.9.8.jar:/opt/google/GoogleBigQueryJDBC42.jar
</code>```

This is my environment:

```<code>$uname -a
Linux ip-172-31-59-210.ec2.internal 4.14.123-111.109.amzn2.x86_64 #1 SMP Mon Jun 10 19:37:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

$java -version
openjdk version "1.8.0_222-ea"
OpenJDK Runtime Environment (build 1.8.0_222-ea-b03)
OpenJDK 64-Bit Server VM (build 25.222-b03, mixed mode)
</code>```

Any thoughts on what I am missing?

Thanks,
Mary

答: The error is likely because the parent class of JsonFactory.jar is not included in your classpath. Instead of listing every .jar individually in your classpath, try using '/opt/google/*' instead.</p>

Body:
I have a Java program that I want to use to run queries against google big query.

I am getting this error when starting my program:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/json/JsonFactory
    at com.simba.googlebigquery.googlebigquery.core.BQConnection.connect(Unknown Source)
    at com.simba.googlebigquery.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
    at com.simba.googlebigquery.jdbc.common.AbstractDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:270)
    at missioncontrol.main(missioncontrol.java:60)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.json.JsonFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 6 more

I have downloaded the Simba gbq jdbc driver.  I have set up my authorizations.  My connection string looks like this:

jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=redacted;OAuthType=0;OAuthServiceAcctEmail=;redaacted@redacted.iam.gserviceaccount.com;OAuthPvtKeyPath=/home/redacted/redacted/redacted.p12;

My CLASSPATH Originally looked like this:
/opt/google/GoogleBigQueryJDBC42.jar

But I've added a bunch of jar files in an effort to solve this problem, so now it looks like this:

/google-http-client-1.29.0.jar:/opt/google/google-http-client-jackson2-1.28.0.jar:/opt/google/jackson-annotations-2.9.0.jar:/opt/google/jackson-core-2.9.8.jar:/opt/google/jackson-databind-2.9.8.jar:/opt/google/GoogleBigQueryJDBC42.jar

This is my environment:

$uname -a
Linux ip-172-31-59-210.ec2.internal 4.14.123-111.109.amzn2.x86_64 #1 SMP Mon Jun 10 19:37:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

$java -version
openjdk version "1.8.0_222-ea"
OpenJDK Runtime Environment (build 1.8.0_222-ea-b03)
OpenJDK 64-Bit Server VM (build 25.222-b03, mixed mode)

Any thoughts on what I am missing?

Thanks,
Mary


问:
Are there any ready-to-use map controls for wp7?
I know microsoft provides a bing map control.
And ESRI has a map control for wp7.

Are there any other map controls?

答:
I know that ThinkGeo are planning on releasing their mapping control for Windows Phone but I'm not sure when.

I also need something that can display tiles link Bing but also shape files from ESRI.

Have a look at the bottom of this thread


问:
How can i make this button on React.js with Material UI or other tool?
I want to make a button similiar as this image. I think is composed by a button (left side) i dont know how i can make the right side of it (the arrow figure) and inside the arrow is an image and a Typography i guess. Hope you can help me!!

答:
I would just divide the element in 3 divs: two rectangles and the triangle shape. Left rectangle - button with an icon in it, right rectangle - image and text and the triangle just an empty div. That's the style you can give to a div to make it looking like the triangle you need.

```<code>triangle: {
 width: 0,
 height: 0,
 backgroundColor: "transparent",
 borderStyle: "solid",
 borderLeftWidth: 50,
 borderRightWidth: 50,
 borderBottomWidth: 100,
 borderLeftColor: "transparent",
 borderRightColor: "transparent",
 borderBottomColor: "red",
 transform: "rotate(90deg)" }
</code>```

division

Body:
I would just divide the element in 3 divs: two rectangles and the triangle shape. Left rectangle - button with an icon in it, right rectangle - image and text and the triangle just an empty div. That's the style you can give to a div to make it looking like the triangle you need.

triangle: {
 width: 0,
 height: 0,
 backgroundColor: "transparent",
 borderStyle: "solid",
 borderLeftWidth: 50,
 borderRightWidth: 50,
 borderBottomWidth: 100,
 borderLeftColor: "transparent",
 borderRightColor: "transparent",
 borderBottomColor: "red",
 transform: "rotate(90deg)" }

division


问:
How to set selected select option in Handlebars template
With a Handlebars.js template like this...

```<code><select>
    <option value="Completed">Completed</option>
    <option value="OverDue">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
</select>
</code>```

... and data like this...

```<code>{
    "id"     : 1,
    "name"   : "World"
    "status" : "OverDue",
    "date"   : "2012-12-21"
}
</code>```

I want to render HTML like this.

```<code><select>
    <option value="Completed">Completed</option>
    <option value="OverDue" selected="selected">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
</select>
</code>```

Which way is the easiest?

答:
I know this does not answer the question directly, but in this situation, I passed the unselected html options to the template, and after it is rendered, I use jquery to
mark as selected the value that the json object indicates </p>

Body:
With a Handlebars.js template like this...

<select>
    <option value="Completed">Completed</option>
    <option value="OverDue">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
</select>

... and data like this...

{
    "id"     : 1,
    "name"   : "World"
    "status" : "OverDue",
    "date"   : "2012-12-21"
}

I want to render HTML like this.

<select>
    <option value="Completed">Completed</option>
    <option value="OverDue" selected="selected">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
</select>

Which way is the easiest?


问:
iOS: Sharing via UIActivityViewController does not work with UIActivityItemSource
I wanted to further customize how content is shared from my app and instead of providing UIActivityViewController with image and title use the UIActivityItemSource protocol to implement methods that provide this content.

So I created extension for my model Scan like this:

```<code>extension Scan: UIActivityItemSource {
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return self.title as Any
    }

    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return self.orderedDocuments.map({ $0.image }) as Any
    }

    func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivity.ActivityType?, suggestedSize size: CGSize) -> UIImage? {
        return self.thumbnailImage
    }

    func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
        return "Scan from: \(String(describing: self.created))"
    }
}
</code>```

But when I pass instance of Scan to the UIActivityViewController it opens but it is empty. I cannot see the title, preview or the actual images.. These methods are getting called.

I am presenting the UIActivityViewController like this as there is not much to customize:

```<code>func share(_ scan: Scan) {

        let shareController = UIActivityViewController(activityItems: [scan], applicationActivities: nil)

        present(shareController, animated: true)
}
</code>```

The Scan is Core Data entity but I tried creating separate class just for sharing and that did not work either.

EDIT: So I got some progress with metadata like this:

```<code>func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
        guard let image = self.orderedDocuments.first?.image else { return nil }
        let imageProvider = NSItemProvider(object: image)
        let metadata = LPLinkMetadata()
        metadata.imageProvider = imageProvider
        metadata.title = title
        return metadata
    }
</code>```

It at least shows proper title and thumbnail. I have seen some apps even displaying subtitle and file size which I guess is not possible for in-memory images?

I still have issues with sharing more than one image.

My updated activity controller methods:

```<code>func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return self.orderedDocuments.first?.image
    }

    func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
        return kUTTypePNG as String
    }
</code>```

答:
Regarding:

I have seen some apps even displaying subtitle and file size which I
  guess is not possible for in-memory images?

It's silly, but can be done with:

linkMetaData.originalURL = URL(fileURLWithPath: "Insert whatever info here")
```

<p>For example, for a result like this (custom thumbnail, custom title and subtitle with file size):</p>

<p><img src="https://i.stack.imgur.com/0lZHP.jpg" alt="myBaby"></p>

<p>... the code is:</p>

<pre class="lang-swift prettyprint-override"><code>func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {

    let linkMetaData = LPLinkMetadata()

    // Thumbnail
    linkMetaData.iconProvider = NSItemProvider(object: someValidUIImage)

    // Title
    linkMetaData.title = "Ohay title!"

    // Subtitle with file size
    let prefix = "PNG Image"

    let fileSizeResourceValue = try! someValidURL.resourceValues(forKeys: [.fileSizeKey])
    let fileSizeInt = fileSizeResourceValue.fileSize

    let byteCountFormatter = ByteCountFormatter()
    byteCountFormatter.countStyle = .file
    let fileSizeString = byteCountFormatter.string(fromByteCount: Int64(fileSizeInt))

    let suffix = "・\(fileSizeString)"

    //
    linkMetaData.originalURL = URL(fileURLWithPath: "\(prefix)\(suffix)")

    return linkMetaData
}
</code>```

Body:
I wanted to further customize how content is shared from my app and instead of providing UIActivityViewController with image and title use the UIActivityItemSource protocol to implement methods that provide this content.

So I created extension for my model Scan like this:

extension Scan: UIActivityItemSource {
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return self.title as Any
    }

    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return self.orderedDocuments.map({ $0.image }) as Any
    }

    func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivity.ActivityType?, suggestedSize size: CGSize) -> UIImage? {
        return self.thumbnailImage
    }

    func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
        return "Scan from: \(String(describing: self.created))"
    }
}

But when I pass instance of Scan to the UIActivityViewController it opens but it is empty. I cannot see the title, preview or the actual images.. These methods are getting called.

I am presenting the UIActivityViewController like this as there is not much to customize:

func share(_ scan: Scan) {

        let shareController = UIActivityViewController(activityItems: [scan], applicationActivities: nil)

        present(shareController, animated: true)
}

The Scan is Core Data entity but I tried creating separate class just for sharing and that did not work either.

EDIT: So I got some progress with metadata like this:

func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
        guard let image = self.orderedDocuments.first?.image else { return nil }
        let imageProvider = NSItemProvider(object: image)
        let metadata = LPLinkMetadata()
        metadata.imageProvider = imageProvider
        metadata.title = title
        return metadata
    }

It at least shows proper title and thumbnail. I have seen some apps even displaying subtitle and file size which I guess is not possible for in-memory images?

I still have issues with sharing more than one image.

My updated activity controller methods:

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return self.orderedDocuments.first?.image
    }

    func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
        return kUTTypePNG as String
    }

Body:
Regarding:

I have seen some apps even displaying subtitle and file size which I
  guess is not possible for in-memory images?

It's silly, but can be done with:

linkMetaData.originalURL = URL(fileURLWithPath: "Insert whatever info here")

For example, for a result like this (custom thumbnail, custom title and subtitle with file size):

... the code is:

func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {

    let linkMetaData = LPLinkMetadata()

    // Thumbnail
    linkMetaData.iconProvider = NSItemProvider(object: someValidUIImage)

    // Title
    linkMetaData.title = "Ohay title!"

    // Subtitle with file size
    let prefix = "PNG Image"

    let fileSizeResourceValue = try! someValidURL.resourceValues(forKeys: [.fileSizeKey])
    let fileSizeInt = fileSizeResourceValue.fileSize

    let byteCountFormatter = ByteCountFormatter()
    byteCountFormatter.countStyle = .file
    let fileSizeString = byteCountFormatter.string(fromByteCount: Int64(fileSizeInt))

    let suffix = "・\(fileSizeString)"

    //
    linkMetaData.originalURL = URL(fileURLWithPath: "\(prefix)\(suffix)")

    return linkMetaData
}


问:
How to create linked/chained pull request on GitHub
I have multiple feature branches, and usually when i do a git push from my feature branch (checked out locally) , gitHub wants to merge to the master.

However, i have observed pull requests which contain commits from different feature branches all rolled into one PR.
I have also seen commits from different feature branches trying to merge commits into the other, all in one PR.

None of the branches exist on the github repo yet.

How is this done ?

Pardon me if this question is too trivial, i'm new to github !

答:
When you create a pull request, you can specify the base branch, which is the branch it's based off of and into which it will be merged.  If you set the base branch of your first PR to master and you set the base branch of subsequent PRs to that of your first PR, then those subsequent PRs will merge into your first PR, and then it will merge into master.

Typically, you'd only want to do this if you had multiple related PRs, or if you had one series that built upon another.  If you have the latter case, GitHub will exclude commits in the base branch (that is, the first PR's branch) from display in the latter, showing only the commits that are new in your other PR.


问:
How to control the placement of GameObject in a scene programmatically in Unity
I have created a code file in Unity and assigned it to an empty GameObject I have placed in the scene:

```<code>var obj = new GameObject("Sample");
obj.transform.position = new Vector3(0, 0, 0);
var text = obj.AddComponent<TextMesh>();
text.text = "Hello world";
</code>```

When I run the scene, I can see the text. And that is my problem: I did not specify anywhere in code to add obj to the scene, but it gets placed automatically apparently.
This can be a problem if I want to introduce an object later than instantiation time.

What am I doing wrong? How can this be achieved? What are the patterns/best-practices here?

答:
Immediate fix:

Use obj.SetActive(false) to temporarily disable the object and then use obj.SetActive(true) when you need the object to be active.

Other solutions / best practices:

Create the object you desire in the scene, save it as a prefab (prefabricated object) and then only instantiate it when you need it. Here's a link for further reading into the prefab system. https://docs.unity3d.com/Manual/Prefabs.html

Object pooling is typically used when you will have a bunch of the same objects (like lasers, bullets, etc). Watching this video may be of help: https://www.youtube.com/watch?v=tdSmKaJvCoA

Body:
I have created a code file in Unity and assigned it to an empty GameObject I have placed in the scene:

var obj = new GameObject("Sample");
obj.transform.position = new Vector3(0, 0, 0);
var text = obj.AddComponent<TextMesh>();
text.text = "Hello world";

When I run the scene, I can see the text. And that is my problem: I did not specify anywhere in code to add obj to the scene, but it gets placed automatically apparently.
This can be a problem if I want to introduce an object later than instantiation time.

What am I doing wrong? How can this be achieved? What are the patterns/best-practices here?


问:
Ifelse statement in R: One value cannot equal another
I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user is high_user he cannot also be a small_user.

```<code>head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

</code>```

Any help would be greatly appreciated.

答:
An option with base R

```<code>df$new_type <- with(df, ave(type, User, FUN = function(x) x[1]))
</code>```

data

```<code>df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'),
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))
</code>```

Body:
I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user is high_user he cannot also be a small_user.

head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

Any help would be greatly appreciated.

Body:
An option with base R

df$new_type <- with(df, ave(type, User, FUN = function(x) x[1]))

data

df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'),
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))


问:
Multi Query / Multi Sort (?) with Mongoose in Node.js
I've been working on a news site where users can post articles and leave comments. Part of the comments is to designate an emotion to the comment (one of 5 options: Amazed, Happy, Neutral, Sad, Angry).

What i want to do with this is make a 'top 5' of articles with the highest emotion count for a specific emotion. And sure, i know on a forum the emotion is always 'angry' so i should just work with that ;D , but this is part of a learning experience and i'd like to know how to do this.

So for other top5's ( 'hot discussion' and 'hot news' ) i have introduced counters in my Article Schema, that get incremented either when a comment is made (for 'hotDiscussion'), or when a user designates something as truly 'hot news' ( 'like button functionality' ). Then i simply search for the Articles and sort by these counters...

BUT, for this specific case, where there are 5 options, how do i sort ?!? ... at first i thought i would just implement the counters when a certain emotion is picked (pull down menu). But then all the counters are 'on the Article' as a single entity and i don't see how you would sort by all of them to get a comprehensive list. So then i though to put them in an object or array... something like:

```<code>Article {
   title: String,
   author: user...
   comments: []
   emotions: [ or {
        Amazed: amazedCount,
        Happy: happyCount,
        Neutral: neutralCount,
        Sad: sadCount,
        Angry: angryCount
   } or ]
</code>```

Then, maybe i can find all the articles and sort by emotions (somehow?) and then skim off the top 5 from the list. But here again i run into the 5 options thing. And i have no clue how to sort the emotions? to then perhaps within the results, sort by the first (highest) count. To then skim of the top5.

So looking around here somewhat hints at me going for something like this

```<code>Article {
   ...
   ...
   emotions: [
       {name: Amazed, value: amazedCount},
       {name: Happy, value: happyCount},
       {name: Neutral, value: neutralCount},
       {name: Sad, value: sadCount},
       {name: Angry, value: angryCount}
     ]
</code>```

And i like this direction somewhat, due to the clear keys 'name' & 'value'.
But here i run into the same issue, aka. lack of knowledge ... Because:

how to sort on a second order value, as i would be sorting on value?

will the same article just show up multiple times in the result? (i'dd like to prevent that if at all possible, a very busy mixed emotion thread should not show up twice over a less busy but clearly 'happy' thread in the top5 ).

So hopefully somebody can help me, as i can see this type of searching valuable in various types of situations, not just for some learning environment type 'forum' top5.

For those needing a more useful 'use case'

```<code>warehouse{
   name: String,
   ... : ...
   parts: [
        {name: part1, value: Count}
        {name: part2, value: Count}
        {etc }
         ]
    }
</code>```

Generating a list of warehouses based upon the count of parts (where double mention of a certain warehouse isn't a problem); Or say a list of Car Dealers with the highest count for available brands or models (to get input for redistribution f/e). Or a list of online shops with a multi value rating system (f/e: delivery speed, customer service, price of products, etc.)

答:
Well, it turns out this is actually fairly simple ... as i was most the way there. Just needed to put the sort criteria in between '...'  /doh !

! THIS CODE IS NOT COMPLETE, as in Copy/Paste you are done, but the Code below does show you most the places where you need to 'do' things to make this work (/show routes not included, aka the pages the user sees and can input stuff on)

```<code>    // In the Schemas:
        Article {
           ...
           ...
           emotions: [ {emotion: String, eCount: Number} ]
        }

        Comment{
           emotion: String;  //to save the emotion of the user on the comment
         }

    // Upon initializing an Article:
        router.post("/route", function(req, res){
            let etcetera: etc,
            let theEmotions = [  // in your usecase you may populate these elsewhere
                            { emotion: "Amazed", eCount: 0 },
                            { emotion: "Happy", eCount: 0 },
                            { emotion: "Neutral", eCount: 0 },
                            { emotion: "Sad", eCount: 0 },
                            { emotion: "Angry", eCount: 0 }
                        ];

            let newArticle = {
              etc: etc,
              emotions: theEmotions
            };

            Article.create(newArticle, function(err, newArticle){
               *stuff here*
            });
        });

    // when a comment gets made, it updates the scores based upon the emotion selected
    //REST :: CREATE --> actually creates a new comment
    router.post("/", function(req, res){
        Article.findById(req.params.id, function(err, foundArticle){
            if(err){
                console.log("ERROR @ finding article to POST the COMMENT");
                res.redirect('/articles');
            } else {
                Comment.create(req.body.comment, function(err, createdComment){
                    if(err){
                        console.log("ERROR @ CREATing new COMMENT");
                    } else {
                        switch(createdComment.emotion){
                            case "Amazed":
                                foundArticle.emotions[0].eCount += 1;
                                break;
                            case "Happy":
                                foundArticle.emotions[1].eCount += 1;
                                break;
                            case "Neutral":
                                foundArticle.emotions[2].eCount += 1;
                                break;
                            case "Sad":
                                foundArticle.emotions[3].eCount += 1;
                                break;
                            case "Angry":
                                foundArticle.emotions[4].eCount += 1;
                                break;
                            default:
                                console.log("ERROR @ Emotion Switch in comments route");
                        }
                        //add username and id to comment
                        createdComment.user.id = req.user._id;
                        createdComment.user.username = req.user.username;
                        createdComment.save();
                        foundArticle.comments.push(createdComment);
                        foundArticle.save();
                        console.log("SUCCESS @ CREATing new COMMENT");
                        res.redirect('/articles/' + foundArticle._id);
                    }
                });
            }
        });
    });

    //Where one wants to sort: ... note the '...' around 'emotions.eCount'
    router.get("/specificRoute, function(req, res){
        Article.find({}).sort({'emotions.eCount': -1}).exec(function(err, hotEmotions){

            *stuff happens here*

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

Hopefully this will be of some help to someone somewhere in the future :)

Body:
I've been working on a news site where users can post articles and leave comments. Part of the comments is to designate an emotion to the comment (one of 5 options: Amazed, Happy, Neutral, Sad, Angry).

What i want to do with this is make a 'top 5' of articles with the highest emotion count for a specific emotion. And sure, i know on a forum the emotion is always 'angry' so i should just work with that ;D , but this is part of a learning experience and i'd like to know how to do this.

So for other top5's ( 'hot discussion' and 'hot news' ) i have introduced counters in my Article Schema, that get incremented either when a comment is made (for 'hotDiscussion'), or when a user designates something as truly 'hot news' ( 'like button functionality' ). Then i simply search for the Articles and sort by these counters...

BUT, for this specific case, where there are 5 options, how do i sort ?!? ... at first i thought i would just implement the counters when a certain emotion is picked (pull down menu). But then all the counters are 'on the Article' as a single entity and i don't see how you would sort by all of them to get a comprehensive list. So then i though to put them in an object or array... something like:

Article {
   title: String,
   author: user...
   comments: []
   emotions: [ or {
        Amazed: amazedCount,
        Happy: happyCount,
        Neutral: neutralCount,
        Sad: sadCount,
        Angry: angryCount
   } or ]

Then, maybe i can find all the articles and sort by emotions (somehow?) and then skim off the top 5 from the list. But here again i run into the 5 options thing. And i have no clue how to sort the emotions? to then perhaps within the results, sort by the first (highest) count. To then skim of the top5.

So looking around here somewhat hints at me going for something like this

Article {
   ...
   ...
   emotions: [
       {name: Amazed, value: amazedCount},
       {name: Happy, value: happyCount},
       {name: Neutral, value: neutralCount},
       {name: Sad, value: sadCount},
       {name: Angry, value: angryCount}
     ]

And i like this direction somewhat, due to the clear keys 'name' & 'value'.
But here i run into the same issue, aka. lack of knowledge ... Because:

how to sort on a second order value, as i would be sorting on value?

will the same article just show up multiple times in the result? (i'dd like to prevent that if at all possible, a very busy mixed emotion thread should not show up twice over a less busy but clearly 'happy' thread in the top5 ).

So hopefully somebody can help me, as i can see this type of searching valuable in various types of situations, not just for some learning environment type 'forum' top5.

For those needing a more useful 'use case'

warehouse{
   name: String,
   ... : ...
   parts: [
        {name: part1, value: Count}
        {name: part2, value: Count}
        {etc }
         ]
    }

Generating a list of warehouses based upon the count of parts (where double mention of a certain warehouse isn't a problem); Or say a list of Car Dealers with the highest count for available brands or models (to get input for redistribution f/e). Or a list of online shops with a multi value rating system (f/e: delivery speed, customer service, price of products, etc.)

Body:
Well, it turns out this is actually fairly simple ... as i was most the way there. Just needed to put the sort criteria in between '...'  /doh !

! THIS CODE IS NOT COMPLETE, as in Copy/Paste you are done, but the Code below does show you most the places where you need to 'do' things to make this work (/show routes not included, aka the pages the user sees and can input stuff on)

    // In the Schemas:
        Article {
           ...
           ...
           emotions: [ {emotion: String, eCount: Number} ]
        }

        Comment{
           emotion: String;  //to save the emotion of the user on the comment
         }

    // Upon initializing an Article:
        router.post("/route", function(req, res){
            let etcetera: etc,
            let theEmotions = [  // in your usecase you may populate these elsewhere
                            { emotion: "Amazed", eCount: 0 },
                            { emotion: "Happy", eCount: 0 },
                            { emotion: "Neutral", eCount: 0 },
                            { emotion: "Sad", eCount: 0 },
                            { emotion: "Angry", eCount: 0 }
                        ];

            let newArticle = {
              etc: etc,
              emotions: theEmotions
            };

            Article.create(newArticle, function(err, newArticle){
               *stuff here*
            });
        });

    // when a comment gets made, it updates the scores based upon the emotion selected
    //REST :: CREATE --> actually creates a new comment
    router.post("/", function(req, res){
        Article.findById(req.params.id, function(err, foundArticle){
            if(err){
                console.log("ERROR @ finding article to POST the COMMENT");
                res.redirect('/articles');
            } else {
                Comment.create(req.body.comment, function(err, createdComment){
                    if(err){
                        console.log("ERROR @ CREATing new COMMENT");
                    } else {
                        switch(createdComment.emotion){
                            case "Amazed":
                                foundArticle.emotions[0].eCount += 1;
                                break;
                            case "Happy":
                                foundArticle.emotions[1].eCount += 1;
                                break;
                            case "Neutral":
                                foundArticle.emotions[2].eCount += 1;
                                break;
                            case "Sad":
                                foundArticle.emotions[3].eCount += 1;
                                break;
                            case "Angry":
                                foundArticle.emotions[4].eCount += 1;
                                break;
                            default:
                                console.log("ERROR @ Emotion Switch in comments route");
                        }
                        //add username and id to comment
                        createdComment.user.id = req.user._id;
                        createdComment.user.username = req.user.username;
                        createdComment.save();
                        foundArticle.comments.push(createdComment);
                        foundArticle.save();
                        console.log("SUCCESS @ CREATing new COMMENT");
                        res.redirect('/articles/' + foundArticle._id);
                    }
                });
            }
        });
    });

    //Where one wants to sort: ... note the '...' around 'emotions.eCount'
    router.get("/specificRoute, function(req, res){
        Article.find({}).sort({'emotions.eCount': -1}).exec(function(err, hotEmotions){

            *stuff happens here*

        });
    });

Hopefully this will be of some help to someone somewhere in the future :)